promptfoo 0.68.1 → 0.68.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/package.json +6 -3
  2. package/dist/src/assertions.d.ts.map +1 -1
  3. package/dist/src/assertions.js +1 -5
  4. package/dist/src/assertions.js.map +1 -1
  5. package/dist/src/prompts/index.d.ts.map +1 -1
  6. package/dist/src/prompts/index.js +5 -0
  7. package/dist/src/prompts/index.js.map +1 -1
  8. package/dist/src/prompts/utils.d.ts.map +1 -1
  9. package/dist/src/prompts/utils.js +0 -1
  10. package/dist/src/prompts/utils.js.map +1 -1
  11. package/dist/src/providers/openai.d.ts +1 -0
  12. package/dist/src/providers/openai.d.ts.map +1 -1
  13. package/dist/src/providers/openai.js +7 -1
  14. package/dist/src/providers/openai.js.map +1 -1
  15. package/dist/src/web/nextui/404/index.html +1 -1
  16. package/dist/src/web/nextui/404.html +1 -1
  17. package/dist/src/web/nextui/_next/static/chunks/166-157bfb431b68d949.js +1 -1
  18. package/dist/src/web/nextui/_next/static/chunks/2-d534f7b3af3e0505.js +1 -0
  19. package/dist/src/web/nextui/_next/static/chunks/954-c35d4864ecbacd62.js +6 -0
  20. package/dist/src/web/nextui/_next/static/chunks/app/auth/login/{page-ee73165dd261f3ca.js → page-6fcc9431205718c7.js} +1 -1
  21. package/dist/src/web/nextui/_next/static/chunks/app/auth/signup/{page-7375a6707eb8675e.js → page-8caf49a834d34420.js} +1 -1
  22. package/dist/src/web/nextui/_next/static/chunks/app/datasets/page-4f93aacd25866d60.js +1 -0
  23. package/dist/src/web/nextui/_next/static/chunks/app/eval/[id]/not-found-ce320e6d1e6d1d23.js +1 -0
  24. package/dist/src/web/nextui/_next/static/chunks/app/eval/[id]/{page-c6f4e3651d190322.js → page-0a71ecaf651124c2.js} +1 -1
  25. package/dist/src/web/nextui/_next/static/chunks/app/eval/page-bf3968ed106645c6.js +1 -0
  26. package/dist/src/web/nextui/_next/static/chunks/app/{layout-aab36608271969ed.js → layout-b7b366d291dbc9db.js} +1 -1
  27. package/dist/src/web/nextui/_next/static/chunks/app/{page-251d4ea0ac894cd9.js → page-e07a0ddbf3d6e21c.js} +1 -1
  28. package/dist/src/web/nextui/_next/static/chunks/app/progress/page-52079a97d0c2e2ea.js +1 -0
  29. package/dist/src/web/nextui/_next/static/chunks/app/prompts/{page-f31dd67a60140868.js → page-7da4796409bc2636.js} +1 -1
  30. package/dist/src/web/nextui/_next/static/chunks/app/report/{page-49d3492c635a81f5.js → page-a0a68795eb905dcc.js} +1 -1
  31. package/dist/src/web/nextui/_next/static/chunks/app/setup/page-71b3060b06865254.js +1 -0
  32. package/dist/src/web/nextui/_next/static/chunks/{main-app-345c3eca7e5cf432.js → main-app-929a26b3c8cd3f7a.js} +1 -1
  33. package/dist/src/web/nextui/auth/login/index.html +1 -1
  34. package/dist/src/web/nextui/auth/login/index.txt +3 -3
  35. package/dist/src/web/nextui/auth/signup/index.html +1 -1
  36. package/dist/src/web/nextui/auth/signup/index.txt +3 -3
  37. package/dist/src/web/nextui/datasets/index.html +1 -1
  38. package/dist/src/web/nextui/datasets/index.txt +3 -3
  39. package/dist/src/web/nextui/eval/index.html +1 -1
  40. package/dist/src/web/nextui/eval/index.txt +3 -3
  41. package/dist/src/web/nextui/index.html +1 -1
  42. package/dist/src/web/nextui/index.txt +2 -2
  43. package/dist/src/web/nextui/progress/index.html +1 -1
  44. package/dist/src/web/nextui/progress/index.txt +3 -3
  45. package/dist/src/web/nextui/prompts/index.html +1 -1
  46. package/dist/src/web/nextui/prompts/index.txt +3 -3
  47. package/dist/src/web/nextui/report/index.html +1 -1
  48. package/dist/src/web/nextui/report/index.txt +3 -3
  49. package/dist/src/web/nextui/setup/index.html +2 -2
  50. package/dist/src/web/nextui/setup/index.txt +3 -3
  51. package/package.json +6 -3
  52. package/dist/src/web/nextui/_next/static/chunks/2-c749131e7095aef3.js +0 -1
  53. package/dist/src/web/nextui/_next/static/chunks/954-58788165fb1e9563.js +0 -6
  54. package/dist/src/web/nextui/_next/static/chunks/app/datasets/page-c11cfb1b2c58325f.js +0 -1
  55. package/dist/src/web/nextui/_next/static/chunks/app/eval/[id]/not-found-50073ee4b153b82b.js +0 -1
  56. package/dist/src/web/nextui/_next/static/chunks/app/eval/page-f9f3c8b30c6aef5b.js +0 -1
  57. package/dist/src/web/nextui/_next/static/chunks/app/progress/page-f1bd840ce9168e13.js +0 -1
  58. package/dist/src/web/nextui/_next/static/chunks/app/setup/page-6cd68647af1a20aa.js +0 -1
  59. /package/dist/src/web/nextui/_next/static/{tUB-fEjoICDbTDdLhchKo → 4W0Qng9llk0Tg-jZCYupr}/_buildManifest.js +0 -0
  60. /package/dist/src/web/nextui/_next/static/{tUB-fEjoICDbTDdLhchKo → 4W0Qng9llk0Tg-jZCYupr}/_ssgManifest.js +0 -0
@@ -1 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[2],{49532:function(e,t,s){"use strict";let n,l;async function a(){if(n||(l||(l=fetch("/api/config").then(e=>e.json()).then(e=>n=e.apiBaseUrl)),await l),void 0===n)throw Error("API base URL is undefined");return n}s.d(t,{b:function(){return a}})},72002:function(e,t,s){"use strict";s.r(t),s.d(t,{default:function(){return e2}});var n=s(24004),l=s(14978),a=s(77580);let r=a.env.NEXT_PUBLIC_PROMPTFOO_REMOTE_API_BASE_URL||a.env.NEXT_PUBLIC_PROMPTFOO_BASE_URL||a.env.PROMPTFOO_REMOTE_API_BASE_URL||"https://api.promptfoo.dev",i=a.env.NEXT_PUBLIC_PROMPTFOO_BASE_URL||a.env.PROMPTFOO_REMOTE_APP_BASE_URL||"https://app.promptfoo.dev";a?.stdout?.columns&&a?.stdout?.columns>10&&a?.stdout?.columns;var o=s(49532);let c=(0,l.createContext)(void 0),d=e=>{let{children:t}=e,[s,a]=(0,l.useState)(!1);return(0,l.useEffect)(()=>{let e=e=>{"Shift"===e.key&&a(!0)},t=e=>{"Shift"===e.key&&a(!1)};return window.addEventListener("keydown",e),window.addEventListener("keyup",t),()=>{window.removeEventListener("keydown",e),window.removeEventListener("keyup",t)}},[]),(0,n.jsx)(c.Provider,{value:s,children:t})};var u=s(52428),p=s(11615),h=s(12594),m=s(28891),x=s(74997),g=s(93179),j=s(47887),v=s(43205),f=s(5592),b=s(14931),y=s(75307),Z=s(17178),w=s(42610),C=s(68873),k=s(49567),S=s(40982),N=s(24362),R=s(39813),I=s(1852),P=s(57027),E=s(94941),F=s(36273),O=s(96976),T=s(8508),M=s(34304),D=s(32414),L=s(67339),A=s(65969),U=s(63147),W=s(14059),_=s(23223),z=s(26110),V=s(48931),B=s(99645),J=s(29794),H=s(22701),G=s(51956),X=s(82669),Y=s(77656),q=s(37204),$=s(79685),K=s(74595);let Q={getItem:async e=>await (0,q.U2)(e)||null,setItem:async(e,t)=>{await (0,q.t8)(e,t)},removeItem:async e=>{await (0,q.IV)(e)}},ee=(0,$.Ue)()((0,K.tJ)((e,t)=>({evalId:null,setEvalId:t=>e(()=>({evalId:t})),table:null,setTable:t=>e(()=>({table:t})),config:null,setConfig:t=>e(()=>({config:t})),maxTextLength:250,setMaxTextLength:t=>e(()=>({maxTextLength:t})),wordBreak:"break-word",setWordBreak:t=>e(()=>({wordBreak:t})),showInferenceDetails:!0,setShowInferenceDetails:t=>e(()=>({showInferenceDetails:t})),renderMarkdown:!1,setRenderMarkdown:t=>e(()=>({renderMarkdown:t})),prettifyJson:!1,setPrettifyJson:t=>e(()=>({prettifyJson:t})),showPrompts:!1,setShowPrompts:t=>e(()=>({showPrompts:t})),showPassFail:!0,setShowPassFail:t=>e(()=>({showPassFail:t}))}),{name:"ResultsViewStorage",storage:(0,K.FL)(()=>Q)}));function et(e){let{open:t,onClose:a}=e,{config:r}=ee(),i=l.useRef(null),[o,c]=l.useState(!1),[d,u]=l.useState("");l.useEffect(()=>{t&&(async()=>{let{default:e}=await Promise.resolve().then(s.bind(s,34235));u(e.dump(r))})()},[t,r]);let p=()=>{c(!1),a()};return(0,n.jsxs)(J.Z,{open:t,onClose:p,"aria-labelledby":"config-dialog-title",maxWidth:"md",fullWidth:!0,children:[(0,n.jsx)(X.Z,{id:"config-dialog-title",children:(0,n.jsxs)(k.Z,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[(0,n.jsx)(U.Z,{variant:"h6",style:{flexGrow:1},children:"Config"}),(0,n.jsxs)(k.Z,{children:[(0,n.jsx)(A.Z,{title:"Copy to clipboard",children:(0,n.jsx)(Y.Z,{onClick:()=>{i.current&&(i.current.select(),document.execCommand("copy"),c(!0))},children:o?(0,n.jsx)(z.Z,{}):(0,n.jsx)(B.Z,{})})}),(0,n.jsx)(A.Z,{title:"Download .yaml",children:(0,n.jsx)(Y.Z,{onClick:()=>{let e=new Blob([d],{type:"text/yaml;charset=utf-8"}),t=URL.createObjectURL(e),s=document.createElement("a");s.href=t,s.download="config.yaml",document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(t)},children:(0,n.jsx)(V.Z,{})})})]})]})}),(0,n.jsx)(G.Z,{children:(0,n.jsx)(U.Z,{variant:"body1",component:"div",children:(0,n.jsx)("textarea",{ref:i,readOnly:!0,value:d,style:{width:"100%",minHeight:"400px",fontFamily:"monospace",border:"1px solid #ccc"}})})}),(0,n.jsx)(H.Z,{children:(0,n.jsx)(S.Z,{onClick:p,color:"primary",children:"Close"})})]})}var es=s(79715),en=s(34235),el=function(){let{table:e,config:t,evalId:s}=ee(),[a,r]=l.useState(!1),i=(e,t)=>{let s=URL.createObjectURL(e),n=document.createElement("a");n.href=s,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(s)},o=()=>{r(!1)};return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)(O.Z,{onClick:()=>{r(!0)},children:[(0,n.jsx)(P.Z,{children:(0,n.jsx)(V.Z,{fontSize:"small"})}),(0,n.jsx)(E.Z,{children:"Download"})]}),(0,n.jsx)(J.Z,{onClose:o,open:a,children:(0,n.jsx)(G.Z,{children:(0,n.jsxs)(D.Z,{direction:"column",spacing:2,sx:{width:"100%"},children:[(0,n.jsx)(S.Z,{onClick:()=>{let e=en.default.dump(t),s=new Blob([e],{type:"text/yaml;charset=utf-8"});i(s,"promptfooconfig.yaml"),o()},startIcon:(0,n.jsx)(V.Z,{}),fullWidth:!0,sx:{justifyContent:"flex-start"},children:"Download YAML Config"}),(0,n.jsx)(S.Z,{onClick:()=>{if(!e){alert("No table data");return}let t=[],n=[...e.head.vars,...e.head.prompts.map(e=>"[".concat(e.provider,"] ").concat(e.label))];t.push(n),e.body.forEach(e=>{let s=[...e.vars,...e.outputs.map(e=>{let{pass:t,text:s}=e;return(t?"[PASS] ":"[FAIL] ")+s})];t.push(s)});let l=(0,es.P)(t),a=new Blob([l],{type:"text/csv;charset=utf-8;"});i(a,"".concat(s,"-table.csv")),o()},startIcon:(0,n.jsx)(V.Z,{}),fullWidth:!0,sx:{justifyContent:"flex-start"},children:"Download Table CSV"}),(0,n.jsx)(S.Z,{onClick:()=>{if(!e){alert("No table data");return}let t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"});i(t,"".concat(s,"-table.json")),o()},startIcon:(0,n.jsx)(V.Z,{}),fullWidth:!0,sx:{justifyContent:"flex-start"},children:"Download Table JSON"}),(0,n.jsx)(S.Z,{onClick:()=>{if(!e){alert("No table data");return}let t=e.body.map((t,s)=>({chosen:t.outputs.filter(e=>e.pass).map(e=>e.text),rejected:t.outputs.filter(e=>!e.pass).map(e=>e.text),vars:t.test.vars,providers:e.head.prompts.map(e=>e.provider),prompts:e.head.prompts.map(e=>e.label||e.display||e.raw)})),n=new Blob([JSON.stringify(t,null,2)],{type:"application/json"});i(n,"".concat(s,"-dpo.json")),o()},startIcon:(0,n.jsx)(V.Z,{}),fullWidth:!0,sx:{justifyContent:"flex-start"},children:"Download DPO JSON"})]})})})]})},ea=s(69179),er=s(92715),ei=s(37803),eo=s(92863),ec=s(36001);let ed=["#fd7f6f","#7eb0d5","#b2e061","#bd7ebe","#ffb55a","#ffee65","#beb9db","#fdcce5","#8bd3c7"];function eu(e){let{table:t}=e,s=(0,l.useRef)(null),a=(0,l.useRef)(null);return(0,l.useEffect)(()=>{if(!s.current)return;a.current&&a.current.destroy();let e=t.body.flatMap(e=>e.outputs.map(e=>e.score)),n=Math.min(...e),l=(Math.ceil(Math.max(...e))-Math.floor(n))/10,r=Array.from({length:11},(e,t)=>parseFloat((Math.floor(n)+t*l).toFixed(2))),i=t.head.prompts.map((e,s)=>{let n=t.body.flatMap(e=>e.outputs[s].score),a=r.map(e=>n.filter(t=>t>=e&&t<e+l).length);return{label:"Column ".concat(s+1),data:a,backgroundColor:ed[s%ed.length]}});a.current=new ec.kL(s.current,{type:"bar",data:{labels:r,datasets:i},options:{animation:!1,plugins:{title:{display:!0,text:"Score Distribution"},legend:{display:!1},tooltip:{callbacks:{title:function(e){let t=e[0].datasetIndex;return"Column ".concat(t+1)},label:function(e){let t=e.dataIndex,s=r[t],n=r[t+1];return n?"".concat(s," <= score < ").concat(n):"".concat(s," <= score")}}}}}})},[t]),(0,n.jsx)("canvas",{ref:s,style:{maxHeight:"300px"}})}function ep(e){let{table:t}=e,s=(0,l.useRef)(null),a=(0,l.useRef)(null);return(0,l.useEffect)(()=>{if(!s.current)return;a.current&&a.current.destroy();let e=t.head.prompts.map((e,s)=>{let n=t.body.flatMap(e=>e.outputs[s]),l=n.filter(e=>e.pass).length,a=l/n.length*100;return{label:"Column ".concat(s+1),data:[a],backgroundColor:ed[s%ed.length]}});a.current=new ec.kL(s.current,{type:"bar",data:{labels:["Pass Rate (%)"],datasets:e},options:{animation:!1,plugins:{title:{display:!0,text:"Pass rate"},legend:{display:!0}}}})},[t]),(0,n.jsx)("canvas",{ref:s,style:{maxHeight:"300px"}})}function eh(e){let{table:t}=e,s=(0,l.useRef)(null),a=(0,l.useRef)(null),[r,i]=(0,l.useState)(0),[o,c]=(0,l.useState)(1),[d,u]=(0,l.useState)(!1);return(0,l.useEffect)(()=>{if(!s.current)return;a.current&&a.current.destroy();let e=t.body.flatMap(e=>e.outputs.map(e=>e.score)),n=Math.min(...e),l=Math.max(...e),i=t.body.map(e=>{let t=e.outputs[r].score,s=e.outputs[o].score;return{x:t,y:s,backgroundColor:s>t?"green":s<t?"red":"gray"}});a.current=new ec.kL(s.current,{type:"scatter",data:{datasets:[{data:i,backgroundColor:i.map(e=>e.backgroundColor)},{type:"line",data:[{x:n,y:n},{x:l,y:l}],borderColor:"gray",borderWidth:1,borderDash:[5,5],pointRadius:0}]},options:{animation:!1,plugins:{legend:{display:!1},tooltip:{callbacks:{label:function(e){let s=t.body[e.dataIndex],n=s.outputs[0].text,l=s.outputs[1].text;return n.length>30&&(n=n.substring(0,30)+"..."),l.length>30&&(l=l.substring(0,30)+"..."),"Output 1: ".concat(n,"\nOutput 2: ").concat(l)}}}},scales:{x:{title:{display:!0,text:"Prompt ".concat(r+1," Score")},ticks:{callback:function(e,t,s){let n=String(Math.round(100*Number(e)));return t===s.length-1&&(n+="%"),n}}},y:{title:{display:!0,text:"Prompt ".concat(o+1," Score")},ticks:{callback:function(e,t,s){let n=String(Math.round(100*Number(e)));return t===s.length-1&&(n+="%"),n}}}}}})},[t,r,o]),(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)(J.Z,{open:d,onClose:()=>u(!1),children:[(0,n.jsx)(X.Z,{children:"Compare prompt outputs"}),(0,n.jsxs)(G.Z,{children:[(0,n.jsx)(R.Z,{sx:{m:1,minWidth:120},children:(0,n.jsx)(M.Z,{value:r,onChange:e=>i(Number(e.target.value)),children:t.head.prompts.map((e,t)=>(0,n.jsxs)(O.Z,{value:t,children:["Prompt ",t+1]},t))})}),(0,n.jsx)(R.Z,{sx:{m:1,minWidth:120},children:(0,n.jsx)(M.Z,{value:o,onChange:e=>c(Number(e.target.value)),children:t.head.prompts.map((e,t)=>(0,n.jsxs)(O.Z,{value:t,children:["Prompt ",t+1]},t))})})]})]}),(0,n.jsx)("canvas",{ref:s,style:{maxHeight:"300px",cursor:"pointer"},onClick:()=>u(!0)})]})}function em(e){let{table:t}=e,s=(0,l.useRef)(null),a=(0,l.useRef)(null);return(0,l.useEffect)(()=>{var e;if(!s.current)return;a.current&&a.current.destroy();let n=Object.keys((null===(e=t.head.prompts[0].metrics)||void 0===e?void 0:e.namedScores)||{}),l=t.head.prompts.map((e,s)=>{let l=n.map(s=>{var n;let l=(null===(n=e.metrics)||void 0===n?void 0:n.namedScores[s])||0,a=Math.max(...t.head.prompts.map(e=>{var t;return(null===(t=e.metrics)||void 0===t?void 0:t.namedScores[s])||0}));return l/a});return{label:"".concat(t.head.prompts[s].provider),data:l,backgroundColor:ed[s%ed.length]}});a.current=new ec.kL(s.current,{type:"bar",data:{labels:n,datasets:l},options:{scales:{x:{grid:{display:!1}},y:{ticks:{callback:function(e,t,s){let n=String(Math.round(100*Number(e)));return t===s.length-1&&(n+="%"),n}}}},plugins:{tooltip:{callbacks:{title:function(e){return e[0].dataset.label},label:function(e){let t=e.parsed.y;return"".concat(n[e.dataIndex],": ").concat((100*t).toFixed(2),"% pass rate")}}}}}})},[t]),(0,n.jsx)("canvas",{ref:s,style:{maxHeight:"300px"}})}ec.kL.register(ec.vn,ec.ST,ec.ho,ec.uw,ec.f$,ec.ZL,ec.jn,ec.od,ec.u,ec.wL);var ex=l.memo(function(e){var t;let{columnVisibility:s}=e,a=(0,eo.Z)();ec.kL.defaults.color="dark"===a.palette.mode?"#aaa":"#666";let[r,i]=(0,l.useState)(!0),{table:o}=ee();if(!o||!r||o.head.prompts.length<2)return null;let c=o.body.flatMap(e=>e.outputs.map(e=>e.score)),d=new Set(c);return 1===d.size?null:(0,n.jsx)(ea.SV,{fallback:null,children:(0,n.jsxs)(ei.Z,{style:{position:"relative",padding:a.spacing(3)},children:[(0,n.jsx)(Y.Z,{style:{position:"absolute",right:0,top:0},onClick:()=>i(!1),children:(0,n.jsx)(er.Z,{})}),(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",width:"100%"},children:[(0,n.jsx)("div",{style:{width:"33%"},children:(0,n.jsx)(ep,{table:o})}),(0,n.jsx)("div",{style:{width:"33%"},children:d.size<=3&&Object.keys((null===(t=o.head.prompts[0].metrics)||void 0===t?void 0:t.namedScores)||{}).length>1?(0,n.jsx)(em,{table:o}):(0,n.jsx)(eu,{table:o})}),(0,n.jsx)("div",{style:{width:"33%"},children:(0,n.jsx)(eh,{table:o})})]})]})})}),eg=s(36128),ej=s(9317),ev=s(20286);s(55974);var ef=e=>{let{lookup:t,onSearchTextChange:s}=e;return t&&Object.keys(t).length?(0,n.jsx)("div",{className:"custom-metric-container",children:Object.entries(t).map(e=>{let[t,l]=e;return t&&void 0!==l?(0,n.jsxs)("span",{onClick:()=>s&&s("metric=".concat(t,":[^0]")),className:s?"clickable":"",children:[t,": ",l.toFixed(2)]},t):null})}):null},eb=s(35185),ey=s(65068),eZ=s(70417),ew=s(21303),eC=s(61451),ek=s(26485),eS=s(30021),eN=s(613);function eR(e){let{gradingResults:t}=e;return t?(0,n.jsxs)(k.Z,{mt:2,children:[(0,n.jsx)(U.Z,{variant:"subtitle1",children:"Assertions"}),(0,n.jsx)(eC.Z,{children:(0,n.jsxs)(ey.Z,{children:[(0,n.jsx)(ek.Z,{children:(0,n.jsxs)(eS.Z,{children:[(0,n.jsx)(ew.Z,{style:{fontWeight:"bold"},children:"Pass"}),(0,n.jsx)(ew.Z,{style:{fontWeight:"bold"},children:"Score"}),(0,n.jsx)(ew.Z,{style:{fontWeight:"bold"},children:"Type"}),(0,n.jsx)(ew.Z,{style:{fontWeight:"bold"},children:"Value"}),(0,n.jsx)(ew.Z,{style:{fontWeight:"bold"},children:"Reason"})]})}),(0,n.jsx)(eZ.Z,{children:t.map((e,t)=>{var s,l;return e?(0,n.jsxs)(eS.Z,{children:[(0,n.jsx)(ew.Z,{children:e.pass?"✅":"❌"}),(0,n.jsx)(ew.Z,{children:e.score.toFixed(2)}),(0,n.jsx)(ew.Z,{children:(null===(s=e.assertion)||void 0===s?void 0:s.type)||""}),(0,n.jsx)(ew.Z,{style:{whiteSpace:"pre-wrap"},children:(null===(l=e.assertion)||void 0===l?void 0:l.value)?String(e.assertion.value):"-"}),(0,n.jsx)(ew.Z,{style:{whiteSpace:"pre-wrap"},children:e.reason})]},t):null})})]})})]}):null}function eI(e){let{open:t,onClose:s,prompt:a,provider:r,output:i,gradingResults:o,metadata:c}=e,[d,u]=(0,l.useState)(!1);(0,l.useEffect)(()=>{u(!1)},[a]);let p=async e=>{await navigator.clipboard.writeText(e),u(!0)};return(0,n.jsxs)(J.Z,{open:t,onClose:s,fullWidth:!0,maxWidth:"lg",children:[(0,n.jsxs)(X.Z,{children:["Details",r&&": ".concat(r)]}),(0,n.jsxs)(G.Z,{children:[(0,n.jsxs)(k.Z,{mb:2,children:[(0,n.jsx)(U.Z,{variant:"subtitle1",style:{marginBottom:"1rem"},children:"Prompt"}),(0,n.jsx)(eN.u,{readOnly:!0,value:a,style:{width:"100%",padding:"0.75rem"},maxRows:20}),(0,n.jsx)(Y.Z,{onClick:()=>p(a),style:{position:"absolute",right:"10px",top:"10px"},children:d?(0,n.jsx)(z.Z,{}):(0,n.jsx)(eb.Z,{})})]}),(null==c?void 0:c.redteamFinalPrompt)&&(0,n.jsxs)(k.Z,{my:2,children:[(0,n.jsx)(U.Z,{variant:"subtitle1",style:{marginBottom:"1rem",marginTop:"1rem"},children:"Modified Prompt (Red Team)"}),(0,n.jsx)(eN.u,{readOnly:!0,maxRows:20,value:c.redteamFinalPrompt,style:{width:"100%",padding:"0.75rem"}})]}),i&&(0,n.jsxs)(k.Z,{my:2,children:[(0,n.jsx)(U.Z,{variant:"subtitle1",style:{marginBottom:"1rem",marginTop:"1rem"},children:"Output"}),(0,n.jsx)(eN.u,{readOnly:!0,maxRows:20,value:i,style:{width:"100%",padding:"0.75rem"}})]}),(0,n.jsx)(eR,{gradingResults:o})]}),(0,n.jsx)(H.Z,{children:(0,n.jsx)(S.Z,{onClick:s,children:"Close"})})]})}var eP=s(12431),eE=s(8541),eF=function(){let e=(0,eo.Z)(),[t,s]=l.useState(!1),a=()=>{s(!1)};return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{style:{textAlign:"center",marginTop:20,marginBottom:40},children:(0,n.jsx)(S.Z,{variant:"text",color:"primary",startIcon:(0,n.jsx)(eP.Z,{}),onClick:()=>{s(!0)},children:"Generate test cases"})}),(0,n.jsxs)(J.Z,{open:t,onClose:a,children:[(0,n.jsx)(X.Z,{children:"Run on Command Line"}),(0,n.jsx)(G.Z,{children:(0,n.jsxs)(eE.Z,{children:[(0,n.jsx)("p",{children:"This feature is in beta. UI coming soon."}),(0,n.jsxs)("p",{children:["Run"," ",(0,n.jsx)(k.Z,{component:"code",sx:{backgroundColor:"dark"===e.palette.mode?"#424242":"#f0f0f0",padding:"2px 4px",borderRadius:"4px"},children:"promptfoo generate dataset"}),"to generate test cases on the command line."]})]})}),(0,n.jsx)(H.Z,{children:(0,n.jsx)(S.Z,{onClick:a,color:"primary",children:"Close"})})]})]})};function eO(e){return"string"==typeof e||"number"==typeof e?e.toString().length:Array.isArray(e)?e.reduce((e,t)=>e+eO(t),0):l.isValidElement(e)&&e.props.children?l.Children.toArray(e.props.children).reduce((e,t)=>e+eO(t),0):0}let eT=l.memo(function(e){let t,{text:s,maxLength:a}=e,[r,i]=l.useState(!0),o=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if("string"==typeof e||"number"==typeof e){let s=e.toString();return s.slice(0,a-t)}if(Array.isArray(e)){let s=[],n=t;for(let t of e){let e=eO(t);if(n+e>a){s.push(o(t,n));break}s.push(t),n+=e}return s}if(l.isValidElement(e)&&e.props.children){let s=eO(e.props.children);if(s>a-t)return l.cloneElement(e,{...e.props,children:o(e.props.children,t)})}return e};t=l.isValidElement(s)||"string"==typeof s?s:JSON.stringify(s);let c=r?o(t):t,d=eO(t)>a;return(0,n.jsxs)("div",{style:{cursor:d?"pointer":"normal"},onClick:()=>{i(!r)},children:[c,r&&eO(t)>a&&(0,n.jsx)("span",{children:"..."})]})});var eM=s(59682),eD=s(62268),eL=s(38640),eA=s.n(eL),eU=s(33352),eW=s(73490),e_=s(24495);s(16658);var ez=e=>{let{failReasons:t}=e,[s,a]=(0,l.useState)(0);return t.length<1?null:(0,n.jsxs)("div",{className:"fail-reason",children:[t.length>1&&(0,n.jsxs)("span",{className:"fail-reason-carousel-controls",children:[(0,n.jsx)(Y.Z,{onClick:()=>{a(e=>e>0?e-1:t.length-1)},children:(0,n.jsx)(eW.Z,{sx:{fontSize:12}})}),(0,n.jsxs)("span",{children:[s+1,"/",t.length]}),(0,n.jsx)(Y.Z,{onClick:()=>{a(e=>e<t.length-1?e+1:0)},children:(0,n.jsx)(e_.Z,{sx:{fontSize:12}})})]}),t[s].trim().split("\n").map((e,t)=>(0,n.jsxs)(l.Fragment,{children:[e,(0,n.jsx)("br",{})]},t))]})},eV=e=>{let{open:t,contextText:s,commentText:l,onClose:a,onSave:r,onChange:i}=e;return(0,n.jsxs)(J.Z,{open:t,onClose:a,fullWidth:!0,maxWidth:"sm",children:[(0,n.jsx)(X.Z,{children:"Edit Comment"}),(0,n.jsxs)(G.Z,{children:[(0,n.jsx)(k.Z,{sx:{backgroundColor:"#f0f0f0",padding:2,marginBottom:2},children:s}),(0,n.jsx)(L.Z,{autoFocus:!0,margin:"dense",type:"text",fullWidth:!0,multiline:!0,rows:4,value:l,onChange:e=>i(e.target.value)})]}),(0,n.jsxs)(H.Z,{children:[(0,n.jsx)(S.Z,{onClick:r,color:"primary",variant:"contained",children:"Save"}),(0,n.jsx)(S.Z,{onClick:a,color:"primary",children:"Cancel"})]})]})};let eB=()=>{let e=(0,l.useContext)(c);if(void 0===e)throw Error("useShiftKey must be used within a ShiftKeyProvider");return e};var eJ=s(19116);let eH=l.memo(function(e){var t,s,a,r,i,o,c,d,u,p,h,m,x;let g,j,v,f,b,y,{output:Z,maxTextLength:w,rowIndex:C,promptIndex:k,onRating:S,firstOutput:N,showDiffs:R,searchText:I,showStats:P}=e,{renderMarkdown:E,prettifyJson:F,showPrompts:O,showPassFail:T}=ee(),[M,D]=l.useState(!1),[L,U]=l.useState(!1),[W,_]=l.useState(null),z=e=>{_(e||null),U(!L)},[V,B]=l.useState(!1),[J,H]=l.useState((null===(t=Z.gradingResult)||void 0===t?void 0:t.comment)||""),G=()=>{B(!0)},X="string"==typeof Z.text?Z.text:JSON.stringify(Z.text),Y=[];if(!Z.pass&&X.includes("---")&&(Y=((null===(p=Z.gradingResult)||void 0===p?void 0:p.componentResults)||[]).filter(e=>!!e&&!e.pass).map(e=>e.reason),X=X.split("---").slice(1).join("---")),R&&N){let e,t="string"==typeof N.text?N.text:JSON.stringify(N.text);t.includes("---")&&(t=t.split("---").slice(1).join("---"));try{JSON.parse(t),JSON.parse(X),e=(0,eJ.CT)(t,X)}catch(s){e=t.includes(". ")&&X.includes(". ")?(0,eJ.SY)(t,X):(0,eJ.NV)(t,X)}g=(0,n.jsx)(n.Fragment,{children:e.map((e,t)=>e.added?(0,n.jsx)("ins",{children:e.value},t):e.removed?(0,n.jsx)("del",{children:e.value},t):(0,n.jsx)("span",{children:e.value},t))})}if(I)try{let e;let t=RegExp(I,"gi"),s=[];for(;null!==(e=t.exec(X));)s.push({start:e.index,end:t.lastIndex});g=(0,n.jsx)(n.Fragment,{children:s.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{children:X.substring(0,s[0].start)},"text-before"),s.map((e,t)=>(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"search-highlight",children:X.substring(e.start,e.end)},"match-"+t),(0,n.jsx)("span",{children:X.substring(e.end,s[t+1]?s[t+1].start:X.length)},"text-after-"+t)]}))]}):(0,n.jsx)("span",{children:X},"no-match")})}catch(e){console.error("Invalid regular expression:",e.message)}else if(E)g=(0,n.jsx)(ev.U,{remarkPlugins:[eU.Z],components:{img:e=>{let{src:t,alt:s}=e;return(0,n.jsx)("img",{loading:"lazy",src:t,alt:s,onClick:()=>z(t),style:{cursor:"pointer"}})}},children:X});else if(F)try{g=(0,n.jsx)("pre",{children:JSON.stringify(JSON.parse(X),null,2)})}catch(e){}let q=l.useCallback(e=>{var t;S(e,void 0,null===(t=Z.gradingResult)||void 0===t?void 0:t.comment)},[S,null===(s=Z.gradingResult)||void 0===s?void 0:s.comment]),$=l.useCallback(()=>{let e=prompt("Set test score (0.0 - 1.0):",String(Z.score));if(null!==e){let s=parseFloat(e);if(!isNaN(s)&&s>=0&&s<=1){var t;S(void 0,s,null===(t=Z.gradingResult)||void 0===t?void 0:t.comment)}else alert("Invalid score. Please enter a value between 0.0 and 1.0.")}},[S,Z.score,null===(a=Z.gradingResult)||void 0===a?void 0:a.comment]),[K,Q]=l.useState(!1),et=l.useCallback(()=>{navigator.clipboard.writeText(Z.text),Q(!0)},[Z.text]);if(Z.latencyMs&&(v=(0,n.jsxs)("span",{children:[Intl.NumberFormat(void 0,{maximumFractionDigits:0}).format(Z.latencyMs)," ms"]})),null===(r=Z.tokenUsage)||void 0===r?void 0:r.completion){let e=Z.tokenUsage.completion/(Z.latencyMs/1e3);f=(0,n.jsx)("span",{children:Intl.NumberFormat(void 0,{maximumFractionDigits:0}).format(e)})}if(Z.cost&&(b=(0,n.jsxs)("span",{children:["$",Z.cost.toPrecision(2)]})),null===(i=Z.tokenUsage)||void 0===i?void 0:i.cached)j=(0,n.jsxs)("span",{children:[Intl.NumberFormat(void 0,{maximumFractionDigits:0}).format(Z.tokenUsage.cached)," ","(cached)"]});else if(null===(o=Z.tokenUsage)||void 0===o?void 0:o.total){let e=Intl.NumberFormat(void 0,{maximumFractionDigits:0}).format(null!==(h=Z.tokenUsage.prompt)&&void 0!==h?h:0),t=Intl.NumberFormat(void 0,{maximumFractionDigits:0}).format(null!==(m=Z.tokenUsage.completion)&&void 0!==m?m:0),s=Intl.NumberFormat(void 0,{maximumFractionDigits:0}).format(Z.tokenUsage.total);j=(0,n.jsx)(A.Z,{title:"".concat(e," prompt tokens + ").concat(t," completion tokens = ").concat(s," total"),children:(0,n.jsxs)("span",{children:[s,("0"!==e||"0"!==t)&&" (".concat(e,"+").concat(t,")")]})})}let es=(null===(c=Z.gradingResult)||void 0===c?void 0:c.comment)&&"!highlight"!==Z.gradingResult.comment?(0,n.jsx)("div",{className:"comment",onClick:G,children:Z.gradingResult.comment}):null,en=P?(0,n.jsxs)("div",{className:"cell-detail",children:[j&&(0,n.jsxs)("div",{className:"stat-item",children:[(0,n.jsx)("strong",{children:"Tokens:"})," ",j]}),v&&(0,n.jsxs)("div",{className:"stat-item",children:[(0,n.jsx)("strong",{children:"Latency:"})," ",v]}),f&&(0,n.jsxs)("div",{className:"stat-item",children:[(0,n.jsx)("strong",{children:"Tokens/Sec:"})," ",f]}),b&&(0,n.jsxs)("div",{className:"stat-item",children:[(0,n.jsx)("strong",{children:"Cost:"})," ",b]})]}):null,el=eB(),ea=(0,n.jsxs)("div",{className:"cell-actions",children:[el&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"action",onClick:et,onMouseDown:e=>e.preventDefault(),children:(0,n.jsx)(A.Z,{title:"Copy output to clipboard",children:(0,n.jsx)("span",{children:K?"✅":"\uD83D\uDCCB"})})}),(0,n.jsx)("span",{className:"action",onClick:()=>{let e;J.startsWith("!highlight")?S(void 0,void 0,e=J.slice(10).trim()):S(void 0,void 0,e=("!highlight "+J).trim()),H(e)},onMouseDown:e=>e.preventDefault(),children:(0,n.jsx)(A.Z,{title:"Toggle test highlight",children:(0,n.jsx)("span",{children:"\uD83C\uDF1F"})})})]}),Z.prompt&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"action",onClick:()=>{D(!0)},children:(0,n.jsx)(A.Z,{title:"View ouput and test details",children:(0,n.jsx)("span",{children:"\uD83D\uDD0E"})})}),(0,n.jsx)(eI,{open:M,onClose:()=>{D(!1)},prompt:Z.prompt,provider:Z.provider,gradingResults:null===(d=Z.gradingResult)||void 0===d?void 0:d.componentResults,output:X,metadata:Z.metadata})]}),(0,n.jsx)("span",{className:"action",onClick:()=>q(!0),children:(0,n.jsx)(A.Z,{title:"Mark test passed (score 1.0)",children:(0,n.jsx)("span",{children:"\uD83D\uDC4D"})})}),(0,n.jsx)("span",{className:"action",onClick:()=>q(!1),children:(0,n.jsx)(A.Z,{title:"Mark test failed (score 0.0)",children:(0,n.jsx)("span",{children:"\uD83D\uDC4E"})})}),(0,n.jsx)("span",{className:"action",onClick:$,children:(0,n.jsx)(A.Z,{title:"Set test score",children:(0,n.jsx)("span",{children:"\uD83D\uDD22"})})}),(0,n.jsx)("span",{className:"action",onClick:G,children:(0,n.jsx)(A.Z,{title:"Edit comment",children:(0,n.jsx)("span",{children:"✏️"})})})]}),er={};(null===(u=Z.gradingResult)||void 0===u?void 0:u.comment)==="!highlight"&&(er.backgroundColor="#ffffeb");let ei=0,eo=0,ec=Z.gradingResult;if(ec?ec.componentResults?ec.componentResults.forEach(e=>{(null==e?void 0:e.pass)?ei++:eo++}):(ei=ec.pass?1:0,eo=ec.pass?0:1):Z.pass?ei=1:Z.pass||(eo=1),1===eo&&1===ei)y=(0,n.jsxs)(n.Fragment,{children:["".concat(eo," FAIL")," ","".concat(ei," PASS")]});else{let e="";eo>1||ei>1&&eo>0?e="".concat(eo," FAIL"):1===eo&&(e="FAIL");let t="";ei>1||eo>1&&ei>0?t="".concat(ei," PASS"):1===ei&&0===eo&&(t="PASS");let s=e&&t?" ":"";y=(0,n.jsxs)(n.Fragment,{children:[e,s,t]})}let ed=null===(x=Z.score)||0===x||1===x?"":"(".concat(x.toFixed(2),")");return(0,n.jsxs)("div",{className:"cell",style:er,children:[T&&(0,n.jsx)(n.Fragment,{children:Z.pass?(0,n.jsx)(n.Fragment,{children:(0,n.jsxs)("div",{className:"status pass",children:[(0,n.jsxs)("div",{className:"pill",children:[y,ed&&(0,n.jsxs)("span",{className:"score",children:[" ",ed]})]}),(0,n.jsx)(ef,{lookup:Z.namedScores})]})}):(0,n.jsx)(n.Fragment,{children:(0,n.jsxs)("div",{className:"status fail",children:[(0,n.jsxs)("div",{className:"pill",children:[y,ed&&(0,n.jsxs)("span",{className:"score",children:[" ",ed]})]}),(0,n.jsx)(ef,{lookup:Z.namedScores}),(0,n.jsx)("span",{className:"fail-reason",children:(0,n.jsx)(ez,{failReasons:Y})})]})})}),O&&N.prompt&&(0,n.jsxs)("div",{className:"prompt",children:[(0,n.jsx)("span",{className:"pill",children:"Prompt"}),Z.prompt]}),(0,n.jsx)(eT,{text:g||X,maxLength:w}),es,en,ea,L&&W&&(0,n.jsx)("div",{className:"lightbox",onClick:()=>z(),children:(0,n.jsx)("img",{src:W,alt:"Lightbox"})}),(0,n.jsx)(eV,{open:V,contextText:Z.text,commentText:J,onClose:()=>{B(!1)},onSave:()=>{S(void 0,void 0,J),B(!1)},onChange:H})]})});function eG(e){let{text:t,maxLength:s,expandedText:a,resourceId:r,className:i}=e,[o,c]=l.useState(!1);return(0,n.jsxs)("div",{className:"".concat(i||""),children:[(0,n.jsx)(eT,{text:t,maxLength:s}),a&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(A.Z,{title:"View prompt",children:(0,n.jsx)("span",{className:"action",onClick:()=>{c(!0)},children:"\uD83D\uDD0E"})}),(0,n.jsx)(eI,{open:o,onClose:()=>{c(!1)},prompt:a}),r&&(0,n.jsx)(A.Z,{title:"View other evals and datasets for this prompt",children:(0,n.jsx)("span",{className:"action",children:(0,n.jsx)(eA(),{href:"/prompts/?id=".concat(r),target:"_blank",children:(0,n.jsx)(eM.Z,{fontSize:"small"})})})})]})]})}s(93207);var eX=l.memo(function(e){let{maxTextLength:t,columnVisibility:s,wordBreak:a,filterMode:r,failureFilter:i,searchText:c,showStats:d,onFailureFilterToggle:u,onSearchTextChange:p}=e,{evalId:h,table:m,setTable:x}=ee();(0,g.Z)(m,"Table should be defined");let{head:j,body:v}=m,f=l.useCallback(async(e,t,s,n,l)=>{var a,r;let i=[...v],c={...i[e]},d=[...c.outputs],u=null!=s?s:d[t].pass,p=void 0===n?s?1:0:n||0;d[t].pass=u,d[t].score=p;let m=(null===(a=d[t].gradingResult)||void 0===a?void 0:a.componentResults)||[];if(void 0!==s){let e=m.findIndex(e=>{var t;return(null===(t=e.assertion)||void 0===t?void 0:t.type)==="human"}),t={pass:u,score:p,reason:"Manual result (overrides all other grading results)",comment:l,assertion:{type:"human"}};-1!==e?m[e]=t:m.push(t)}let g={...d[t].gradingResult||{},pass:u,score:p,reason:"Manual result (overrides all other grading results)",comment:l,assertion:(null===(r=d[t].gradingResult)||void 0===r?void 0:r.assertion)||null,componentResults:m};d[t].gradingResult=g,c.outputs=d,i[e]=c;let f={head:j,body:i};x(f);try{let e=await fetch("".concat(await (0,o.b)(),"/api/eval/").concat(h),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({table:f})});if(!e.ok)throw Error("Network response was not ok")}catch(e){console.error("Failed to update table:",e)}},[v,j,x,h]),b=Object.keys(s).length>0,y=l.useMemo(()=>{try{return RegExp(c,"i")}catch(e){return console.error("Invalid regular expression:",e.message),null}},[c]),Z=l.useMemo(()=>{try{return v.map((e,t)=>({...e,outputs:e.outputs.map((e,s)=>({...e,originalRowIndex:t,originalPromptIndex:s}))})).filter(e=>{let t=!0;return"failures"===r?t=e.outputs.some((e,t)=>{let n="Prompt ".concat(t+1);return i[n]&&!e.pass&&(!b||s[n])}):"different"===r?t=!e.outputs.every(t=>t.text===e.outputs[0].text):"highlights"===r&&(console.log(e.outputs[0].text),t=e.outputs.some(e=>{var t,s;return null===(s=e.gradingResult)||void 0===s?void 0:null===(t=s.comment)||void 0===t?void 0:t.startsWith("!highlight")})),!!t&&(!c||!y||e.outputs.some(t=>{var s,n;let l=e.vars.map(e=>"var=".concat(e)).join(" "),a="".concat(t.text," ").concat(Object.keys(t.namedScores).map(e=>"metric=".concat(e,":").concat(t.namedScores[e])).join(" ")," ").concat((null===(s=t.gradingResult)||void 0===s?void 0:s.reason)||""," ").concat((null===(n=t.gradingResult)||void 0===n?void 0:n.comment)||""),r="".concat(l," ").concat(a);return y.test(r)}))})}catch(e){return console.error("Invalid regular expression:",e.message),v}},[v,i,r,c,s,b,y]),[w,C]=l.useState({pageIndex:0,pageSize:50});l.useEffect(()=>{C(e=>({...e,pageIndex:0}))},[i,r,c]);let R=l.useMemo(()=>j.prompts.map((e,t)=>v.reduce((e,s)=>e+(s.outputs[t].pass?1:0),0)),[j.prompts,v]),I=l.useMemo(()=>j.prompts.map((e,t)=>v.reduce((e,s)=>{var n,l;return e+((null===(l=s.outputs[t].gradingResult)||void 0===l?void 0:null===(n=l.componentResults)||void 0===n?void 0:n.length)||0)},0)),[j.prompts,v]),P=l.useMemo(()=>j.prompts.map((e,t)=>v.reduce((e,s)=>{var n;let l=null===(n=s.outputs[t].gradingResult)||void 0===n?void 0:n.componentResults;return e+(l?l.filter(e=>null==e?void 0:e.pass).length:0)},0)),[j.prompts,v]),E=l.useMemo(()=>R.reduce((e,t,s,n)=>t>n[e]?s:e,0),[R]),F=R[E],T=l.useMemo(()=>(0,eg.Cl)(),[]),{renderMarkdown:D}=ee(),A=l.useMemo(()=>j.vars.length>0?[T.group({id:"vars",header:()=>(0,n.jsx)("span",{className:"font-bold",children:"Variables"}),columns:j.vars.map((e,s)=>T.accessor(e=>e.vars[s],{id:"Variable ".concat(s+1),header:()=>(0,n.jsx)(eG,{text:e,maxLength:t,className:"font-bold"}),cell:e=>{let s=e.getValue();return(0,n.jsx)("div",{className:"cell",children:D?(0,n.jsx)(ev.U,{remarkPlugins:[eU.Z],children:s}):(0,n.jsx)(eT,{text:s,maxLength:t})})},size:50}))})]:[],[T,j.vars,t,D]),W=l.useCallback((e,t)=>Z[e].outputs[t],[Z]),_=l.useCallback(e=>Z[e].outputs[0],[Z]),z=l.useMemo(()=>[T.group({id:"prompts",header:()=>(0,n.jsx)("span",{className:"font-bold",children:"Outputs"}),columns:j.prompts.map((e,s)=>T.accessor(e=>(function(e){if("string"==typeof e){let t=e.startsWith("[PASS]"),s=e;return e.startsWith("[PASS]")?s=s.slice(6):e.startsWith("[FAIL]")&&(s=s.slice(6)),{text:s,pass:t,score:t?1:0}}return e})(e.outputs[s]),{id:"Prompt ".concat(s+1),header:()=>{var l,a,o,c,h,m,x,g;let j=R[s]&&v.length?(R[s]/v.length*100).toFixed(2):"0.00",f=R[s]===F&&0!==F,b="Prompt ".concat(s+1),y=i[b]||!1,Z=d?(0,n.jsxs)("div",{className:"prompt-detail",children:[I[s]?(0,n.jsxs)("div",{children:[(0,n.jsx)("strong",{children:"Asserts:"})," ",P[s],"/",I[s]," passed"]}):null,(null===(l=e.metrics)||void 0===l?void 0:l.totalLatencyMs)?(0,n.jsxs)("div",{children:[(0,n.jsx)("strong",{children:"Avg Latency:"})," ",Intl.NumberFormat(void 0,{maximumFractionDigits:0}).format(e.metrics.totalLatencyMs/v.length)," ","ms"]}):null,(null===(o=e.metrics)||void 0===o?void 0:null===(a=o.tokenUsage)||void 0===a?void 0:a.total)?(0,n.jsxs)("div",{children:[(0,n.jsx)("strong",{children:"Avg Tokens:"})," ",Intl.NumberFormat(void 0,{maximumFractionDigits:0}).format(e.metrics.tokenUsage.total/v.length)]}):null,(null===(c=e.metrics)||void 0===c?void 0:c.totalLatencyMs)&&(null===(m=e.metrics)||void 0===m?void 0:null===(h=m.tokenUsage)||void 0===h?void 0:h.completion)?(0,n.jsxs)("div",{children:[(0,n.jsx)("strong",{children:"Tokens/Sec:"})," ",Intl.NumberFormat(void 0,{maximumFractionDigits:0}).format(e.metrics.tokenUsage.completion/(e.metrics.totalLatencyMs/1e3))]}):null,(null===(x=e.metrics)||void 0===x?void 0:x.cost)?(0,n.jsxs)("div",{children:[(0,n.jsx)("strong",{children:"Cost:"})," $",e.metrics.cost.toPrecision(2)]}):null]}):null,w=e.provider?e.provider.split(":"):[],C=w.length>1?(0,n.jsxs)(n.Fragment,{children:[w[0],":",(0,n.jsx)("strong",{children:w.slice(1).join(":")})]}):(0,n.jsx)("strong",{children:e.provider});return(0,n.jsxs)("div",{className:"output-header",children:[(0,n.jsxs)("div",{className:"pills",children:[e.provider?(0,n.jsx)("div",{className:"provider",children:C}):null,(0,n.jsx)("div",{className:"summary",children:(0,n.jsxs)("div",{className:"highlight ".concat(f?"success":""),children:[(0,n.jsxs)("strong",{children:[j,"% passing"]})," (",R[s],"/",v.length," cases)"]})}),(null===(g=e.metrics)||void 0===g?void 0:g.namedScores)&&Object.keys(e.metrics.namedScores).length>0?(0,n.jsx)(ef,{lookup:e.metrics.namedScores,onSearchTextChange:p}):null]}),(0,n.jsx)(eG,{className:"prompt-container",text:e.label||e.display||e.raw,expandedText:e.raw,maxLength:t,resourceId:e.id}),Z,"failures"===r&&(0,n.jsx)(eD.Z,{sx:{"& .MuiFormControlLabel-label":{fontSize:"0.75rem"}},control:(0,n.jsx)(N.Z,{checked:y,onChange:e=>u(b,e.target.checked)}),label:"Show failures"})]})},cell:e=>{var l,a;let i=W(e.row.index,s);return(0,n.jsx)(eH,{output:i,maxTextLength:t,rowIndex:e.row.index,promptIndex:s,onRating:f.bind(null,null!==(l=i.originalRowIndex)&&void 0!==l?l:e.row.index,null!==(a=i.originalPromptIndex)&&void 0!==a?a:s),firstOutput:_(e.row.index),showDiffs:"different"===r,searchText:c,showStats:d})}}))})],[T,j.prompts,R,v.length,F,i,d,I,P,t,u,r,c,W,_,f,p]),V=l.useMemo(()=>{let e=v.some(e=>e.description);return e?{accessorFn:e=>e.description||"",id:"description",header:()=>(0,n.jsx)("span",{className:"font-bold",children:"Description"}),cell:e=>(0,n.jsx)("div",{className:"cell",children:(0,n.jsx)(eT,{text:String(e.getValue()),maxLength:t})}),size:50}:null},[v,t]),B=l.useMemo(()=>{let e=[];return V&&e.push(V),e.push(...A,...z),e},[V,A,z]),J=(0,ej.b7)({data:Z,columns:B,columnResizeMode:"onChange",getCoreRowModel:(0,eg.sC)(),getPaginationRowModel:(0,eg.G_)(),state:{columnVisibility:s,pagination:w}});return(0,n.jsxs)("div",{children:[(0,n.jsxs)("table",{className:"results-table firefox-fix ".concat(t<=25?"compact":""),style:{wordBreak:a},children:[(0,n.jsx)("thead",{children:J.getHeaderGroups().map(e=>(0,n.jsx)("tr",{className:"header",children:e.headers.map(e=>(0,n.jsxs)("th",{colSpan:e.colSpan,style:{width:e.getSize()},children:[e.isPlaceholder?null:(0,ej.ie)(e.column.columnDef.header,e.getContext()),(0,n.jsx)("div",{onMouseDown:e.getResizeHandler(),onTouchStart:e.getResizeHandler(),className:"resizer ".concat(e.column.getIsResizing()?"isResizing":"")})]},e.id))},e.id))}),(0,n.jsx)("tbody",{children:J.getRowModel().rows.map((e,t)=>{let s=!1;return(0,n.jsx)("tr",{children:e.getVisibleCells().map(e=>{let l=e.column.id.startsWith("Variable")||"description"===e.column.id,a=!l&&!s;return a&&(s=!0),(0,n.jsx)("td",{style:{width:e.column.getSize()},className:"".concat(l?"variable":""," ").concat(0!==t||l?"":"first-prompt-row"," ").concat(a?"first-prompt-col":""),children:(0,ej.ie)(e.column.columnDef.cell,e.getContext())},e.id)})},e.id)})})]}),J.getPageCount()>1&&(0,n.jsxs)(k.Z,{className:"pagination",sx:{display:"flex",alignItems:"center",gap:2},children:[(0,n.jsx)(S.Z,{onClick:()=>{C(e=>({...e,pageIndex:Math.max(e.pageIndex-1,0)})),window.scrollTo(0,0)},disabled:0===J.getState().pagination.pageIndex,variant:"contained",children:"Previous"}),(0,n.jsxs)(U.Z,{component:"span",sx:{display:"flex",alignItems:"center",gap:1},children:["Page",(0,n.jsx)(L.Z,{size:"small",type:"number",value:J.getState().pagination.pageIndex+1,onChange:e=>{let t=e.target.value?Number(e.target.value)-1:0;C(e=>({...e,pageIndex:Math.min(Math.max(t,0),J.getPageCount()-1)}))},InputProps:{style:{width:"60px",textAlign:"center"}},variant:"outlined"}),(0,n.jsxs)("span",{children:["of ",J.getPageCount()]})]}),(0,n.jsx)(S.Z,{onClick:()=>{C(e=>({...e,pageIndex:Math.min(e.pageIndex+1,J.getPageCount()-1)})),window.scrollTo(0,0)},disabled:J.getState().pagination.pageIndex+1>=J.getPageCount(),variant:"contained",children:"Next"}),(0,n.jsxs)(U.Z,{component:"span",sx:{display:"flex",alignItems:"center",gap:1},children:[(0,n.jsxs)(M.Z,{value:w.pageSize,onChange:e=>{C({pageIndex:0,pageSize:Number(e.target.value)}),window.scrollTo(0,0)},displayEmpty:!0,inputProps:{"aria-label":"Results per page"},size:"small",sx:{m:1,minWidth:80},children:[(0,n.jsx)(O.Z,{value:10,children:"10"}),(0,n.jsx)(O.Z,{value:50,children:"50"}),(0,n.jsx)(O.Z,{value:100,children:"100"}),(0,n.jsx)(O.Z,{value:500,children:"500"}),(0,n.jsx)(O.Z,{value:1e3,children:"1000"})]}),(0,n.jsx)("span",{children:"results per page"})]})]}),(0,n.jsx)(eF,{})]})}),eY=s(22695),eq=e=>{let{open:t,onClose:s}=e,{maxTextLength:l,setMaxTextLength:a,wordBreak:r,setWordBreak:i,showInferenceDetails:o,setShowInferenceDetails:c,renderMarkdown:d,setRenderMarkdown:u,prettifyJson:p,setPrettifyJson:h,showPrompts:m,setShowPrompts:x,showPassFail:g,setShowPassFail:j}=ee();return(0,n.jsxs)(J.Z,{open:t,onClose:s,fullWidth:!0,maxWidth:"sm",children:[(0,n.jsx)(X.Z,{children:"Table View Settings"}),(0,n.jsxs)(G.Z,{children:[(0,n.jsx)(k.Z,{children:(0,n.jsx)(A.Z,{title:"Forcing line breaks makes it easier to adjust column widths to your liking",placement:"right",children:(0,n.jsx)(eD.Z,{control:(0,n.jsx)(N.Z,{checked:"break-all"===r,onChange:e=>i(e.target.checked?"break-all":"break-word")}),label:"Force line breaks"})})}),(0,n.jsx)(k.Z,{children:(0,n.jsx)(eD.Z,{control:(0,n.jsx)(N.Z,{checked:d,onChange:e=>u(e.target.checked)}),label:"Render model outputs as Markdown"})}),(0,n.jsx)(k.Z,{children:(0,n.jsx)(eD.Z,{control:(0,n.jsx)(N.Z,{checked:p,onChange:e=>h(e.target.checked)}),label:"Prettify JSON outputs"})}),(0,n.jsx)(k.Z,{children:(0,n.jsx)(A.Z,{title:"Show the final prompt that produced the output in each cell.",placement:"right",children:(0,n.jsx)(eD.Z,{control:(0,n.jsx)(N.Z,{checked:m,onChange:e=>x(e.target.checked)}),label:"Show full prompt in output cell"})})}),(0,n.jsx)(k.Z,{children:(0,n.jsx)(A.Z,{title:"Show pass/fail status for each output.",placement:"right",children:(0,n.jsx)(eD.Z,{control:(0,n.jsx)(N.Z,{checked:g,onChange:e=>j(e.target.checked)}),label:"Show pass/fail status"})})}),(0,n.jsx)(k.Z,{children:(0,n.jsx)(A.Z,{title:"Show detailed inference statistics such as latency, tokens used, cost, etc.",placement:"right",children:(0,n.jsx)(eD.Z,{control:(0,n.jsx)(N.Z,{checked:o,onChange:e=>c(e.target.checked)}),label:"Show inference details"})})}),(0,n.jsxs)(k.Z,{maxWidth:"sm",children:[(0,n.jsxs)(U.Z,{mt:2,children:["Max text length: ",l]}),(0,n.jsx)(eY.ZP,{min:25,max:1e3,value:l,onChange:(e,t)=>a(t)})]})]}),(0,n.jsx)(H.Z,{children:(0,n.jsx)(S.Z,{onClick:s,children:"Close"})})]})},e$=e=>{let{open:t,onClose:s,shareUrl:a}=e,r=(0,l.useRef)(null),[i,o]=(0,l.useState)(!1),c=()=>{s(),o(!1)};return(0,n.jsxs)(J.Z,{open:t,onClose:c,PaperProps:{style:{minWidth:"min(660px, 100%)"}},children:[(0,n.jsx)(X.Z,{children:"Your eval is ready to share"}),(0,n.jsxs)(G.Z,{children:[(0,n.jsx)(L.Z,{inputRef:r,value:a,fullWidth:!0,InputProps:{readOnly:!0,endAdornment:(0,n.jsx)(Y.Z,{onClick:()=>{r.current&&(r.current.select(),document.execCommand("copy"),o(!0))},children:i?(0,n.jsx)(z.Z,{}):(0,n.jsx)(B.Z,{})})}}),(0,n.jsx)(eE.Z,{sx:{fontSize:"0.75rem"},children:"Shared URLs are deleted after 2 weeks."})]}),(0,n.jsx)(H.Z,{children:(0,n.jsx)(S.Z,{onClick:c,color:"primary",children:"Close"})})]})};s(58022);let eK=(0,W.Z)(D.Z)(e=>{let{theme:t}=e;return{maxWidth:"100%",flexWrap:"wrap",[t.breakpoints.down("sm")]:{flexDirection:"column"}}});function eQ(e){var t;let{recentEvals:s,onRecentEvalSelected:a,defaultEvalId:c}=e,d=(0,m.useRouter)(),u=(0,m.useSearchParams)(),{table:h,config:x,setConfig:D,maxTextLength:W,wordBreak:z,showInferenceDetails:V,evalId:B}=ee(),{setStateFromConfig:J}=(0,j.o)(),[H,G]=l.useState((null==u?void 0:u.get("search"))||""),[X]=(0,_.Nr)(H,1e3),Y=e=>{G(e)},[q,$]=l.useState({}),K=l.useCallback((e,t)=>{$(s=>({...s,[e]:t}))},[$]);(0,g.Z)(h,"Table data must be loaded before rendering ResultsView");let{head:Q}=h,[es,en]=l.useState("all"),[ea,er]=l.useState(!1),[ei,eo]=l.useState(""),[ec,ed]=l.useState(!1),eu=async()=>{ed(!0);try{let e=await fetch("".concat(r,"/api/eval"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:{version:2,createdAt:new Date().toISOString(),results:{table:h},config:x}})}),{id:t}=await e.json(),s="".concat(i,"/eval/").concat(t);eo(s),er(!0)}catch(e){alert("Sorry, something went wrong.")}finally{ed(!1)}},ep=l.useMemo(()=>[...Q.vars.map((e,t)=>({value:"Variable ".concat(t+1),label:"Var ".concat(t+1,": ").concat(Q.vars[t].length>100?Q.vars[t].slice(0,97)+"...":Q.vars[t]),group:"Variables"})),...Q.prompts.map((e,t)=>{let s=Q.prompts[t],n=s.label||s.display||s.raw;return{value:"Prompt ".concat(t+1),label:"Prompt ".concat(t+1,": ").concat(n.length>100?n.slice(0,97)+"...":n),group:"Prompts"}})],[Q.vars,Q.prompts]),[eh,em]=l.useState(!1),[eg,ej]=l.useState(!1),[ev,ef]=l.useState({}),[eb,ey]=l.useState(ep.map(e=>e.value)),eZ=async()=>{(0,g.Z)(x,"Config must be loaded before clicking its description");let e=window.prompt("Enter new description:",x.description);if(null!==e&&e!==x.description){let t={...x,description:e};try{let e=await fetch("".concat(await (0,o.b)(),"/api/eval/").concat(B),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({config:t})});if(!e.ok)throw Error("Network response was not ok");D(t)}catch(e){console.error("Failed to update table:",e)}}},ew=async()=>{if(window.confirm("Are you sure you want to delete this evaluation?"))try{let e=await fetch("".concat(await (0,o.b)(),"/api/eval/").concat(B),{method:"DELETE"});if(!e.ok)throw Error("Network response was not ok");d.push("/")}catch(e){console.error("Failed to delete evaluation:",e),alert("Failed to delete evaluation")}},[eC,ek]=l.useState(null);return(0,n.jsxs)("div",{style:{marginLeft:"1rem",marginRight:"1rem"},children:[(0,n.jsx)(k.Z,{mb:2,sx:{display:"flex",alignItems:"center"},children:(0,n.jsxs)(U.Z,{variant:"h5",sx:{flexGrow:1},children:[(0,n.jsx)("span",{className:"description",onClick:eZ,children:(null==x?void 0:x.description)||B})," ",(null==x?void 0:x.description)&&(0,n.jsx)("span",{className:"description-filepath",children:B})]})}),(0,n.jsx)(k.Z,{py:"md",children:(0,n.jsxs)(eK,{direction:"row",spacing:4,alignItems:"center",children:[(0,n.jsx)(k.Z,{children:s&&s.length>0&&(0,n.jsx)(R.Z,{sx:{m:1,minWidth:200},size:"small",children:(0,n.jsx)(C.Z,{size:"small",options:s,renderOption:(e,t)=>(0,l.createElement)("li",{...e,key:t.id},t.label),style:{width:350},renderInput:e=>(0,n.jsx)(L.Z,{...e,label:"Eval run",variant:"outlined"}),defaultValue:s.find(e=>e.id===c)||s[0],onChange:(e,t)=>{t&&t.id&&a(t.id)},disableClearable:!0})})}),(0,n.jsx)(k.Z,{children:(0,n.jsxs)(R.Z,{sx:{m:1,minWidth:200,maxWidth:350},size:"small",children:[(0,n.jsx)(I.Z,{id:"visible-columns-label",children:"Columns"}),(0,n.jsx)(M.Z,{labelId:"visible-columns-label",id:"visible-columns",multiple:!0,value:eb,onChange:e=>{let{target:{value:t}}=e;ey("string"==typeof t?t.split(","):t);let s=[...Q.vars.map((e,t)=>"Variable ".concat(t+1)),...Q.prompts.map((e,t)=>"Prompt ".concat(t+1))],n={};s.forEach(e=>{n[e]=("string"==typeof t?t.split(","):t).includes(e)}),ef(n)},input:(0,n.jsx)(T.Z,{label:"Visible columns"}),renderValue:e=>e.join(", "),children:ep.map(e=>(0,n.jsxs)(O.Z,{dense:!0,value:e.value,children:[(0,n.jsx)(N.Z,{checked:eb.indexOf(e.value)>-1}),(0,n.jsx)(E.Z,{primary:e.label})]},e.value))})]})}),(0,n.jsx)(k.Z,{children:(0,n.jsxs)(R.Z,{sx:{minWidth:180},size:"small",children:[(0,n.jsx)(I.Z,{id:"failure-filter-mode-label",children:"Display"}),(0,n.jsxs)(M.Z,{labelId:"filter-mode-label",id:"filter-mode",value:es,onChange:e=>{let t=e.target.value;en(t);let s={};Q.prompts.forEach((e,n)=>{s["Prompt ".concat(n+1)]="failures"===t}),$(s)},label:"Filter",children:[(0,n.jsx)(O.Z,{value:"all",children:"Show all results"}),(0,n.jsx)(O.Z,{value:"failures",children:"Show failures only"}),(0,n.jsx)(O.Z,{value:"different",children:"Show different only"}),(0,n.jsx)(O.Z,{value:"highlights",children:"Show highlights only"})]})]})}),(0,n.jsx)(k.Z,{children:(0,n.jsx)(L.Z,{sx:{minWidth:180},size:"small",label:"Search",placeholder:"Text or regex",value:H,onChange:e=>Y(e.target.value)})}),(0,n.jsx)(k.Z,{flexGrow:1}),(0,n.jsx)(k.Z,{display:"flex",justifyContent:"flex-end",children:(0,n.jsxs)(eK,{direction:"row",spacing:2,children:[(0,n.jsx)(S.Z,{color:"primary",onClick:e=>{ek(e.currentTarget)},startIcon:(0,n.jsx)(v.Z,{}),children:"Eval actions"}),x&&(0,n.jsxs)(F.Z,{id:"eval-actions-menu",anchorEl:eC,keepMounted:!0,open:!!eC,onClose:()=>{ek(null)},children:[(0,n.jsx)(A.Z,{title:"View the configuration that defines this eval",placement:"left",children:(0,n.jsxs)(O.Z,{onClick:()=>em(!0),children:[(0,n.jsx)(P.Z,{children:(0,n.jsx)(w.Z,{fontSize:"small"})}),"View YAML"]})}),(0,n.jsx)(A.Z,{title:"Edit this eval in the web UI",placement:"left",children:(0,n.jsxs)(O.Z,{onClick:()=>{J(x),d.push("/setup/")},children:[(0,n.jsx)(P.Z,{children:(0,n.jsx)(b.Z,{fontSize:"small"})}),"Edit Eval"]})}),(0,n.jsx)(el,{}),(null==x?void 0:x.sharing)&&(0,n.jsx)(A.Z,{title:"Generate a unique URL that others can access",placement:"left",children:(0,n.jsxs)(O.Z,{onClick:eu,disabled:ec,children:[(0,n.jsx)(P.Z,{children:ec?(0,n.jsx)(p.Z,{size:16}):(0,n.jsx)(Z.Z,{fontSize:"small"})}),"Share"]})}),(0,n.jsx)(A.Z,{title:"Delete this eval",placement:"left",children:(0,n.jsxs)(O.Z,{onClick:ew,children:[(0,n.jsx)(P.Z,{children:(0,n.jsx)(f.Z,{fontSize:"small"})}),"Delete"]})})]}),(0,n.jsx)(A.Z,{title:"Edit table view settings",placement:"bottom",children:(0,n.jsx)(S.Z,{color:"primary",onClick:()=>ej(!0),startIcon:(0,n.jsx)(y.Z,{}),children:"Table Settings"})}),(null==x?void 0:null===(t=x.metadata)||void 0===t?void 0:t.redteam)&&(0,n.jsx)(A.Z,{title:"View vulnerability scan report",placement:"bottom",children:(0,n.jsx)(S.Z,{color:"primary",startIcon:(0,n.jsx)(w.Z,{}),onClick:()=>d.push("/report/?evalId=".concat(B)),children:"Vulnerability Report"})})]})})]})}),(0,n.jsx)(ex,{columnVisibility:ev}),(0,n.jsx)(eX,{maxTextLength:W,columnVisibility:ev,wordBreak:z,showStats:V,filterMode:es,failureFilter:q,searchText:X,onFailureFilterToggle:K,onSearchTextChange:Y}),(0,n.jsx)(et,{open:eh,onClose:()=>em(!1)}),(0,n.jsx)(e$,{open:ea,onClose:()=>er(!1),shareUrl:ei}),(0,n.jsx)(eq,{open:eg,onClose:()=>ej(!1)})]})}async function e0(){let e=(0,h.createClientComponentClient)(),{data:{user:t}}=await e.auth.getUser();(0,g.Z)(t,"User not logged in");let{data:s,error:n}=await e.from("EvaluationResult").select("id, createdAt").eq("user_id",t.id).order("createdAt",{ascending:!1}).limit(100);return s||[]}async function e1(e){let t=(0,h.createClientComponentClient)(),{data:s,error:n}=await t.from("EvaluationResult").select("*").eq("id",e).single();return s}function e2(e){var t;let{fetchId:s,preloadedData:a,recentEvals:i,defaultEvalId:c}=e,h=(0,m.useRouter)(),{table:j,setTable:v,setConfig:f,setEvalId:b}=ee(),[y,Z]=l.useState(!1),[w,C]=l.useState(!1),[k,S]=l.useState(i||[]),N=async()=>{let e=await fetch("".concat(await (0,o.b)(),"/api/results"),{cache:"no-store"}),t=await e.json();return S(t.data),t.data},R=l.useCallback(async e=>{let t=await fetch("".concat(await (0,o.b)(),"/api/results/").concat(e),{cache:"no-store"}),s=await t.json();v(s.data.results.table),f(s.data.config),b(e)},[v,f,b]),I=async e=>{u.Ox?(Z(!1),h.push("/eval/remote:".concat(encodeURIComponent(e)))):h.push("/eval/?evalId=".concat(encodeURIComponent(e)))},[P,E]=l.useState(c||(null===(t=k[0])||void 0===t?void 0:t.id)),F=(0,m.useSearchParams)(),O=F?F.get("evalId"):null;return(l.useEffect(()=>{if(O){let e=async()=>{await R(O),Z(!0),E(O),N()};e()}else if(a){var e;v(null===(e=a.data.results)||void 0===e?void 0:e.table),f(a.data.config),Z(!0)}else if(s){let e=async()=>{var e;let t="".concat(r,"/api/eval/").concat(s);console.log("Fetching eval from remote server",t);let n=await fetch(t);if(!n.ok){C(!0);return}let l=await n.json();v(null===(e=l.data.results)||void 0===e?void 0:e.table),f(l.data.config),Z(!0)};e()}else if(u.T8)(0,o.b)().then(e=>{let t=(0,x.io)(e);return t.on("init",e=>{console.log("Initialized socket connection",e),Z(!0),v(null==e?void 0:e.results.table),f(null==e?void 0:e.config),N().then(e=>{var t,s;E(null===(t=e[0])||void 0===t?void 0:t.id),b(null===(s=e[0])||void 0===s?void 0:s.id)})}),t.on("update",e=>{console.log("Received data update",e),v(e.results.table),f(e.config),N().then(e=>{var t;let s=null===(t=e[0])||void 0===t?void 0:t.id;s&&(E(s),b(s))})}),()=>{t.disconnect()}});else if(u.Ox)e0().then(e=>{S(e.map(e=>({id:e.id,label:e.createdAt}))),e.length>0&&e1(e[0].id).then(t=>{(0,g.Z)(t,"Eval not found");let s=t.results,n=t.config;E(e[0].id),v(s.table),f(n),Z(!0)})});else{let e=async()=>{let e=await N();if(!(e.length>0))return(0,n.jsx)("div",{className:"notice",children:"No evals yet. Share some evals to this server and they will appear here."});{let t=await (0,o.b)(),s=e[0].id,n=await fetch("".concat(t,"/api/results/").concat(s)),l=await n.json();v(l.data.results.table),f(l.data.config),Z(!0),E(s),b(s)}};e()}},[s,v,f,b,R,a,E,O]),w)?(0,n.jsx)("div",{className:"notice",children:"404 Eval not found"}):y&&j?(0,n.jsx)(d,{children:(0,n.jsx)(eQ,{defaultEvalId:P,recentEvals:k,onRecentEvalSelected:I})}):(0,n.jsxs)("div",{className:"notice",children:[(0,n.jsx)("div",{children:(0,n.jsx)(p.Z,{size:22})}),(0,n.jsx)("div",{children:"Waiting for eval data"})]})}s(94455)},52428:function(e,t,s){"use strict";s.d(t,{Ox:function(){return a},T8:function(){return l},eA:function(){return r}});var n=s(77580);let l=!n.env.NEXT_PUBLIC_PROMPTFOO_BUILD_STANDALONE_SERVER,a=!!n.env.NEXT_PUBLIC_PROMPTFOO_USE_SUPABASE,r=""},47887:function(e,t,s){"use strict";s.d(t,{o:function(){return a}});var n=s(79685),l=s(74595);let a=(0,n.Ue)()((0,l.tJ)((e,t)=>({env:{},testCases:[],description:"",providers:[],prompts:[],defaultTest:{},evaluateOptions:{},setEnv:t=>e({env:t}),setTestCases:t=>e({testCases:t}),setDescription:t=>e({description:t}),setProviders:t=>e({providers:t}),setPrompts:t=>e({prompts:t}),setDefaultTest:t=>e({defaultTest:t}),setEvaluateOptions:t=>e({evaluateOptions:t}),setStateFromConfig:t=>{let s={};t.description&&(s.description=t.description||""),t.tests&&(s.testCases=t.tests),t.providers&&(s.providers=t.providers),t.prompts&&("string"==typeof t.prompts?s.prompts=[t.prompts]:Array.isArray(t.prompts)?s.prompts=t.prompts.filter(e=>"string"==typeof e&&!e.endsWith(".txt")&&!e.endsWith(".json")&&!e.endsWith(".yaml")):console.warn("Invalid prompts config",t.prompts)),t.defaultTest&&(s.defaultTest=t.defaultTest),t.evaluateOptions&&(s.evaluateOptions=t.evaluateOptions),e(s)},getTestSuite:()=>{let{description:e,testCases:s,providers:n,prompts:l,env:a}=t();return{env:a,description:e,providers:n,prompts:l,tests:s}}}),{name:"promptfoo",skipHydration:!0}))},55974:function(){},94455:function(){},16658:function(){},93207:function(){},58022:function(){}}]);
@@ -1,6 +0,0 @@
1
- "use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[954],{14059:function(e,t,s){s.d(t,{Z:function(){return v}});var r=s(79042),i=s(94312),n=s(36975),a=s(41238),o=s(23437),l=s(60805);let h=["ownerState"],c=["variants"],u=["name","slot","skipVariantsResolver","skipSx","overridesResolver"];function d(e){return"ownerState"!==e&&"theme"!==e&&"sx"!==e&&"as"!==e}let f=(0,o.Z)(),p=e=>e?e.charAt(0).toLowerCase()+e.slice(1):e;function g({defaultTheme:e,theme:t,themeId:s}){return 0===Object.keys(t).length?e:t[s]||t}function y(e,t){let{ownerState:s}=t,n=(0,i.Z)(t,h),a="function"==typeof e?e((0,r.Z)({ownerState:s},n)):e;if(Array.isArray(a))return a.flatMap(e=>y(e,(0,r.Z)({ownerState:s},n)));if(a&&"object"==typeof a&&Array.isArray(a.variants)){let{variants:e=[]}=a,t=(0,i.Z)(a,c),o=t;return e.forEach(e=>{let t=!0;"function"==typeof e.props?t=e.props((0,r.Z)({ownerState:s},n,s)):Object.keys(e.props).forEach(r=>{(null==s?void 0:s[r])!==e.props[r]&&n[r]!==e.props[r]&&(t=!1)}),t&&(Array.isArray(o)||(o=[o]),o.push("function"==typeof e.style?e.style((0,r.Z)({ownerState:s},n,s)):e.style))}),o}return a}let m=function(e={}){let{themeId:t,defaultTheme:s=f,rootShouldForwardProp:o=d,slotShouldForwardProp:h=d}=e,c=e=>(0,l.Z)((0,r.Z)({},e,{theme:g((0,r.Z)({},e,{defaultTheme:s,themeId:t}))}));return c.__mui_systemSx=!0,(e,l={})=>{var f;let m;(0,n.internal_processStyles)(e,e=>e.filter(e=>!(null!=e&&e.__mui_systemSx)));let{name:v,slot:w,skipVariantsResolver:b,skipSx:_,overridesResolver:k=(f=p(w))?(e,t)=>t[f]:null}=l,S=(0,i.Z)(l,u),T=void 0!==b?b:w&&"Root"!==w&&"root"!==w||!1,O=_||!1,C=d;"Root"===w||"root"===w?C=o:w?C=h:"string"==typeof e&&e.charCodeAt(0)>96&&(C=void 0);let j=(0,n.default)(e,(0,r.Z)({shouldForwardProp:C,label:m},S)),I=e=>"function"==typeof e&&e.__emotion_real!==e||(0,a.P)(e)?i=>y(e,(0,r.Z)({},i,{theme:g({theme:i.theme,defaultTheme:s,themeId:t})})):e,E=(i,...n)=>{let a=I(i),o=n?n.map(I):[];v&&k&&o.push(e=>{let i=g((0,r.Z)({},e,{defaultTheme:s,themeId:t}));if(!i.components||!i.components[v]||!i.components[v].styleOverrides)return null;let n=i.components[v].styleOverrides,a={};return Object.entries(n).forEach(([t,s])=>{a[t]=y(s,(0,r.Z)({},e,{theme:i}))}),k(e,a)}),v&&!T&&o.push(e=>{var i;let n=g((0,r.Z)({},e,{defaultTheme:s,themeId:t})),a=null==n||null==(i=n.components)||null==(i=i[v])?void 0:i.variants;return y({variants:a},(0,r.Z)({},e,{theme:n}))}),O||o.push(c);let l=o.length-n.length;if(Array.isArray(i)&&l>0){let e=Array(l).fill("");(a=[...i,...e]).raw=[...i.raw,...e]}let h=j(a,...o);return e.muiName&&(h.muiName=e.muiName),h};return j.withConfig&&(E.withConfig=j.withConfig),E}}();var v=m},12594:function(e,t,s){var r,i=Object.defineProperty,n=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,l={};((e,t)=>{for(var s in t)i(e,s,{get:t[s],enumerable:!0})})(l,{createBrowserSupabaseClient:()=>j,createClientComponentClient:()=>c,createMiddlewareClient:()=>w,createMiddlewareSupabaseClient:()=>E,createPagesBrowserClient:()=>u,createPagesServerClient:()=>g,createRouteHandlerClient:()=>O,createServerActionClient:()=>C,createServerComponentClient:()=>k,createServerSupabaseClient:()=>I}),e.exports=((e,t,s,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let s of a(t))o.call(e,s)||void 0===s||i(e,s,{get:()=>t[s],enumerable:!(r=n(t,s))||r.enumerable});return e})(i({},"__esModule",{value:!0}),l);var h=s(79485);function c({supabaseUrl:e="https://vhywkeydkitmauabqnwv.supabase.co",supabaseKey:t="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZoeXdrZXlka2l0bWF1YWJxbnd2Iiwicm9sZSI6ImFub24iLCJpYXQiOjE2OTI5OTAwMjQsImV4cCI6MjAwODU2NjAyNH0.C02",options:s,cookieOptions:i,isSingleton:n=!0}={}){if(!e||!t)throw Error("either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!");let a=()=>{var r;return(0,h.createSupabaseClient)(e,t,{...s,global:{...null==s?void 0:s.global,headers:{...null==(r=null==s?void 0:s.global)?void 0:r.headers,"X-Client-Info":"@supabase/auth-helpers-nextjs@0.7.4"}},auth:{storageKey:null==i?void 0:i.name,storage:new h.BrowserCookieAuthStorageAdapter(i)}})};if(n){let e=r??a();return"undefined"==typeof window?e:(r||(r=e),r)}return a()}var u=c,d=s(79485),f=s(76051),p=class extends d.CookieAuthStorageAdapter{constructor(e,t){super(t),this.context=e}getCookie(e){var t;let s=(0,f.splitCookiesString)((null==(t=this.context.res.getHeader("set-cookie"))?void 0:t.toString())??"").map(t=>(0,d.parseCookies)(t)[e]).find(e=>!!e),r=s??this.context.req.cookies[e];return r}setCookie(e,t){this._setCookie(e,t)}deleteCookie(e){this._setCookie(e,"",{maxAge:0})}_setCookie(e,t,s){var r;let i=(0,f.splitCookiesString)((null==(r=this.context.res.getHeader("set-cookie"))?void 0:r.toString())??"").filter(t=>!(e in(0,d.parseCookies)(t))),n=(0,d.serializeCookie)(e,t,{...this.cookieOptions,...s,httpOnly:!1});this.context.res.setHeader("set-cookie",[...i,n])}};function g(e,{supabaseUrl:t="https://vhywkeydkitmauabqnwv.supabase.co",supabaseKey:s="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZoeXdrZXlka2l0bWF1YWJxbnd2Iiwicm9sZSI6ImFub24iLCJpYXQiOjE2OTI5OTAwMjQsImV4cCI6MjAwODU2NjAyNH0.C02",options:r,cookieOptions:i}={}){var n;if(!t||!s)throw Error("either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!");return(0,d.createSupabaseClient)(t,s,{...r,global:{...null==r?void 0:r.global,headers:{...null==(n=null==r?void 0:r.global)?void 0:n.headers,"X-Client-Info":"@supabase/auth-helpers-nextjs@0.7.4"}},auth:{storageKey:null==i?void 0:i.name,storage:new p(e,i)}})}var y=s(79485),m=s(76051),v=class extends y.CookieAuthStorageAdapter{constructor(e,t){super(t),this.context=e}getCookie(e){var t;let s=(0,m.splitCookiesString)((null==(t=this.context.res.headers.get("set-cookie"))?void 0:t.toString())??"").map(t=>(0,y.parseCookies)(t)[e]).find(e=>!!e);return s||(0,y.parseCookies)(this.context.req.headers.get("cookie")??"")[e]}setCookie(e,t){this._setCookie(e,t)}deleteCookie(e){this._setCookie(e,"",{maxAge:0})}_setCookie(e,t,s){let r=(0,y.serializeCookie)(e,t,{...this.cookieOptions,...s,httpOnly:!1});this.context.res.headers&&(this.context.res.headers.append("set-cookie",r),this.context.res.headers.append("cookie",r))}};function w(e,{supabaseUrl:t="https://vhywkeydkitmauabqnwv.supabase.co",supabaseKey:s="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZoeXdrZXlka2l0bWF1YWJxbnd2Iiwicm9sZSI6ImFub24iLCJpYXQiOjE2OTI5OTAwMjQsImV4cCI6MjAwODU2NjAyNH0.C02",options:r,cookieOptions:i}={}){var n;if(!t||!s)throw Error("either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!");return(0,y.createSupabaseClient)(t,s,{...r,global:{...null==r?void 0:r.global,headers:{...null==(n=null==r?void 0:r.global)?void 0:n.headers,"X-Client-Info":"@supabase/auth-helpers-nextjs@0.7.4"}},auth:{storageKey:null==i?void 0:i.name,storage:new v(e,i)}})}var b=s(79485),_=class extends b.CookieAuthStorageAdapter{constructor(e,t){super(t),this.context=e}getCookie(e){var t;let s=this.context.cookies();return null==(t=s.get(e))?void 0:t.value}setCookie(e,t){}deleteCookie(e){}};function k(e,{supabaseUrl:t="https://vhywkeydkitmauabqnwv.supabase.co",supabaseKey:s="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZoeXdrZXlka2l0bWF1YWJxbnd2Iiwicm9sZSI6ImFub24iLCJpYXQiOjE2OTI5OTAwMjQsImV4cCI6MjAwODU2NjAyNH0.C02",options:r,cookieOptions:i}={}){var n;if(!t||!s)throw Error("either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!");return(0,b.createSupabaseClient)(t,s,{...r,global:{...null==r?void 0:r.global,headers:{...null==(n=null==r?void 0:r.global)?void 0:n.headers,"X-Client-Info":"@supabase/auth-helpers-nextjs@0.7.4"}},auth:{storageKey:null==i?void 0:i.name,storage:new _(e,i)}})}var S=s(79485),T=class extends S.CookieAuthStorageAdapter{constructor(e,t){super(t),this.context=e}getCookie(e){var t;let s=this.context.cookies();return null==(t=s.get(e))?void 0:t.value}setCookie(e,t){let s=this.context.cookies();s.set(e,t,this.cookieOptions)}deleteCookie(e){let t=this.context.cookies();t.set(e,"",{maxAge:0})}};function O(e,{supabaseUrl:t="https://vhywkeydkitmauabqnwv.supabase.co",supabaseKey:s="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZoeXdrZXlka2l0bWF1YWJxbnd2Iiwicm9sZSI6ImFub24iLCJpYXQiOjE2OTI5OTAwMjQsImV4cCI6MjAwODU2NjAyNH0.C02",options:r,cookieOptions:i}={}){var n;if(!t||!s)throw Error("either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!");return(0,S.createSupabaseClient)(t,s,{...r,global:{...null==r?void 0:r.global,headers:{...null==(n=null==r?void 0:r.global)?void 0:n.headers,"X-Client-Info":"@supabase/auth-helpers-nextjs@0.7.4"}},auth:{storageKey:null==i?void 0:i.name,storage:new T(e,i)}})}var C=O;function j({supabaseUrl:e="https://vhywkeydkitmauabqnwv.supabase.co",supabaseKey:t="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZoeXdrZXlka2l0bWF1YWJxbnd2Iiwicm9sZSI6ImFub24iLCJpYXQiOjE2OTI5OTAwMjQsImV4cCI6MjAwODU2NjAyNH0.C02",options:s,cookieOptions:r}={}){return console.warn("Please utilize the `createPagesBrowserClient` function instead of the deprecated `createBrowserSupabaseClient` function. Learn more: https://supabase.com/docs/guides/auth/auth-helpers/nextjs-pages"),u({supabaseUrl:e,supabaseKey:t,options:s,cookieOptions:r})}function I(e,{supabaseUrl:t="https://vhywkeydkitmauabqnwv.supabase.co",supabaseKey:s="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZoeXdrZXlka2l0bWF1YWJxbnd2Iiwicm9sZSI6ImFub24iLCJpYXQiOjE2OTI5OTAwMjQsImV4cCI6MjAwODU2NjAyNH0.C02",options:r,cookieOptions:i}={}){return console.warn("Please utilize the `createPagesServerClient` function instead of the deprecated `createServerSupabaseClient` function. Learn more: https://supabase.com/docs/guides/auth/auth-helpers/nextjs-pages"),g(e,{supabaseUrl:t,supabaseKey:s,options:r,cookieOptions:i})}function E(e,{supabaseUrl:t="https://vhywkeydkitmauabqnwv.supabase.co",supabaseKey:s="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZoeXdrZXlka2l0bWF1YWJxbnd2Iiwicm9sZSI6ImFub24iLCJpYXQiOjE2OTI5OTAwMjQsImV4cCI6MjAwODU2NjAyNH0.C02",options:r,cookieOptions:i}={}){return console.warn("Please utilize the `createMiddlewareClient` function instead of the deprecated `createMiddlewareSupabaseClient` function. Learn more: https://supabase.com/docs/guides/auth/auth-helpers/nextjs#middleware"),w(e,{supabaseUrl:t,supabaseKey:s,options:r,cookieOptions:i})}},87407:function(e,t,s){s.r(t),s.d(t,{Headers:function(){return n},Request:function(){return a},Response:function(){return o},fetch:function(){return i}});var r=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==s.g)return s.g;throw Error("unable to locate global object")}();let i=r.fetch;t.default=r.fetch.bind(r);let n=r.Headers,a=r.Request,o=r.Response},76051:function(e){var t={decodeValues:!0,map:!1,silent:!1};function s(e){return"string"==typeof e&&!!e.trim()}function r(e,r){var i,n,a,o,l=e.split(";").filter(s),h=(i=l.shift(),n="",a="",(o=i.split("=")).length>1?(n=o.shift(),a=o.join("=")):a=i,{name:n,value:a}),c=h.name,u=h.value;r=r?Object.assign({},t,r):t;try{u=r.decodeValues?decodeURIComponent(u):u}catch(e){console.error("set-cookie-parser encountered an error while decoding a cookie with value '"+u+"'. Set options.decodeValues to false to disable this feature.",e)}var d={name:c,value:u};return l.forEach(function(e){var t=e.split("="),s=t.shift().trimLeft().toLowerCase(),r=t.join("=");"expires"===s?d.expires=new Date(r):"max-age"===s?d.maxAge=parseInt(r,10):"secure"===s?d.secure=!0:"httponly"===s?d.httpOnly=!0:"samesite"===s?d.sameSite=r:d[s]=r}),d}function i(e,i){if(i=i?Object.assign({},t,i):t,!e)return i.map?{}:[];if(e.headers){if("function"==typeof e.headers.getSetCookie)e=e.headers.getSetCookie();else if(e.headers["set-cookie"])e=e.headers["set-cookie"];else{var n=e.headers[Object.keys(e.headers).find(function(e){return"set-cookie"===e.toLowerCase()})];n||!e.headers.cookie||i.silent||console.warn("Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."),e=n}}return(Array.isArray(e)||(e=[e]),(i=i?Object.assign({},t,i):t).map)?e.filter(s).reduce(function(e,t){var s=r(t,i);return e[s.name]=s,e},{}):e.filter(s).map(function(e){return r(e,i)})}e.exports=i,e.exports.parse=i,e.exports.parseString=r,e.exports.splitCookiesString=function(e){if(Array.isArray(e))return e;if("string"!=typeof e)return[];var t,s,r,i,n,a=[],o=0;function l(){for(;o<e.length&&/\s/.test(e.charAt(o));)o+=1;return o<e.length}for(;o<e.length;){for(t=o,n=!1;l();)if(","===(s=e.charAt(o))){for(r=o,o+=1,l(),i=o;o<e.length&&"="!==(s=e.charAt(o))&&";"!==s&&","!==s;)o+=1;o<e.length&&"="===e.charAt(o)?(n=!0,o=i,a.push(e.substring(t,r)),t=o):o=r+1}else o+=1;(!n||o>=e.length)&&a.push(e.substring(t,e.length))}return a}},79485:function(e,t,s){s.r(t),s.d(t,{BrowserCookieAuthStorageAdapter:function(){return t0},CookieAuthStorageAdapter:function(){return tQ},DEFAULT_COOKIE_OPTIONS:function(){return tY},createSupabaseClient:function(){return t1},isBrowser:function(){return tW},parseCookies:function(){return t2},parseSupabaseCookie:function(){return tG},serializeCookie:function(){return t4},stringifySupabaseSession:function(){return tV}}),new TextEncoder;let r=new TextDecoder,i=e=>{let t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s};var n,a,o,l,h,c,u,d,f,p,g,y,m,v,w,b,_,k,S,T,O,C,j,I=crypto;I.getRandomValues.bind(I),Symbol();let E=e=>{let t=e;t instanceof Uint8Array&&(t=r.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return i(t)}catch(e){throw TypeError("The input to be decoded is not correctly encoded.")}},A=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>Promise.resolve().then(s.bind(s,87407)).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)};class P extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}}class x extends P{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class $ extends P{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class R extends P{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}(n=m||(m={})).Any="any",n.ApNortheast1="ap-northeast-1",n.ApNortheast2="ap-northeast-2",n.ApSouth1="ap-south-1",n.ApSoutheast1="ap-southeast-1",n.ApSoutheast2="ap-southeast-2",n.CaCentral1="ca-central-1",n.EuCentral1="eu-central-1",n.EuWest1="eu-west-1",n.EuWest2="eu-west-2",n.EuWest3="eu-west-3",n.SaEast1="sa-east-1",n.UsEast1="us-east-1",n.UsWest1="us-west-1",n.UsWest2="us-west-2";class U{constructor(e,{headers:t={},customFetch:s,region:r=m.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=A(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s,r,i,n,a;return r=this,i=void 0,n=void 0,a=function*(){try{let r;let{headers:i,method:n,body:a}=t,o={},{region:l}=t;l||(l=this.region),l&&"any"!==l&&(o["x-region"]=l),a&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&("undefined"!=typeof Blob&&a instanceof Blob||a instanceof ArrayBuffer?(o["Content-Type"]="application/octet-stream",r=a):"string"==typeof a?(o["Content-Type"]="text/plain",r=a):"undefined"!=typeof FormData&&a instanceof FormData?r=a:(o["Content-Type"]="application/json",r=JSON.stringify(a)));let h=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},o),this.headers),i),body:r}).catch(e=>{throw new x(e)}),c=h.headers.get("x-relay-error");if(c&&"true"===c)throw new $(h);if(!h.ok)throw new R(h);let u=(null!==(s=h.headers.get("Content-Type"))&&void 0!==s?s:"text/plain").split(";")[0].trim();return{data:"application/json"===u?yield h.json():"application/octet-stream"===u?yield h.blob():"text/event-stream"===u?h:"multipart/form-data"===u?yield h.formData():yield h.text(),error:null}}catch(e){return{data:null,error:e}}},new(n||(n=Promise))(function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):((r=t.value)instanceof n?r:new n(function(e){e(r)})).then(s,o)}l((a=a.apply(r,i||[])).next())})}}var L=s(87407);class N extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}}class D{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:"undefined"==typeof fetch?this.fetch=L.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),"GET"!==this.method&&"HEAD"!==this.method&&(this.headers["Content-Type"]="application/json");let s=this.fetch,r=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{var t,s,r;let i=null,n=null,a=null,o=e.status,l=e.statusText;if(e.ok){if("HEAD"!==this.method){let t=await e.text();""===t||(n="text/csv"===this.headers.Accept?t:this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?t:JSON.parse(t))}let r=null===(t=this.headers.Prefer)||void 0===t?void 0:t.match(/count=(exact|planned|estimated)/),h=null===(s=e.headers.get("content-range"))||void 0===s?void 0:s.split("/");r&&h&&h.length>1&&(a=parseInt(h[1])),this.isMaybeSingle&&"GET"===this.method&&Array.isArray(n)&&(n.length>1?(i={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,a=null,o=406,l="Not Acceptable"):n=1===n.length?n[0]:null)}else{let t=await e.text();try{i=JSON.parse(t),Array.isArray(i)&&404===e.status&&(n=[],i=null,o=200,l="OK")}catch(s){404===e.status&&""===t?(o=204,l="No Content"):i={message:t}}if(i&&this.isMaybeSingle&&(null===(r=null==i?void 0:i.details)||void 0===r?void 0:r.includes("0 rows"))&&(i=null,o=200,l="OK"),i&&this.shouldThrowOnError)throw new N(i)}let h={error:i,data:n,count:a,status:o,statusText:l};return h});return this.shouldThrowOnError||(r=r.catch(e=>{var t,s,r;return{error:{message:`${null!==(t=null==e?void 0:e.name)&&void 0!==t?t:"FetchError"}: ${null==e?void 0:e.message}`,details:`${null!==(s=null==e?void 0:e.stack)&&void 0!==s?s:""}`,hint:"",code:`${null!==(r=null==e?void 0:e.code)&&void 0!==r?r:""}`},data:null,count:null,status:0,statusText:""}})),r.then(e,t)}}class J extends D{select(e){let t=!1,s=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",s),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:r,referencedTable:i=r}={}){let n=i?`${i}.order`:"order",a=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${void 0===s?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let r=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:r=s}={}){let i=void 0===r?"offset":`${r}.offset`,n=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(n,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return"GET"===this.method?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:r=!1,wal:i=!1,format:n="text"}={}){var a;let o=[e?"analyze":null,t?"verbose":null,s?"settings":null,r?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=null!==(a=this.headers.Accept)&&void 0!==a?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${n}; for="${l}"; options=${o};`,this}rollback(){var e;return(null!==(e=this.headers.Prefer)&&void 0!==e?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}}class z extends J{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let s=Array.from(new Set(t)).map(e=>"string"==typeof e&&RegExp("[,()]").test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:r}={}){let i="";"plain"===r?i="pl":"phrase"===r?i="ph":"websearch"===r&&(i="w");let n=void 0===s?"":`(${s})`;return this.url.searchParams.append(e,`${i}fts${n}.${t}`),this}match(e){return Object.entries(e).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let r=s?`${s}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}}class F{constructor(e,{headers:t={},schema:s,fetch:r}){this.url=e,this.headers=t,this.schema=s,this.fetch=r}select(e,{head:t=!1,count:s}={}){let r=!1,i=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!r?"":('"'===e&&(r=!r),e)).join("");return this.url.searchParams.set("select",i),s&&(this.headers.Prefer=`count=${s}`),new z({method:t?"HEAD":"GET",url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let r=[];if(this.headers.Prefer&&r.push(this.headers.Prefer),t&&r.push(`count=${t}`),s||r.push("missing=default"),this.headers.Prefer=r.join(","),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);this.url.searchParams.set("columns",e.join(","))}}return new z({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:r,defaultToNull:i=!0}={}){let n=[`resolution=${s?"ignore":"merge"}-duplicates`];if(void 0!==t&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&n.push(this.headers.Prefer),r&&n.push(`count=${r}`),i||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);this.url.searchParams.set("columns",e.join(","))}}return new z({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let s=[];return this.headers.Prefer&&s.push(this.headers.Prefer),t&&s.push(`count=${t}`),this.headers.Prefer=s.join(","),new z({method:"PATCH",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t=[];return e&&t.push(`count=${e}`),this.headers.Prefer&&t.unshift(this.headers.Prefer),this.headers.Prefer=t.join(","),new z({method:"DELETE",url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}}let B={"X-Client-Info":"postgrest-js/1.15.2"};class M{constructor(e,{headers:t={},schema:s,fetch:r}={}){this.url=e,this.headers=Object.assign(Object.assign({},B),t),this.schemaName=s,this.fetch=r}from(e){let t=new URL(`${this.url}/${e}`);return new F(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new M(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:r=!1,count:i}={}){let n,a;let o=new URL(`${this.url}/rpc/${e}`);s||r?(n=s?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{o.searchParams.append(e,t)})):(n="POST",a=t);let l=Object.assign({},this.headers);return i&&(l.Prefer=`count=${i}`),new z({method:n,url:o,headers:l,schema:this.schemaName,body:a,fetch:this.fetch,allowEmpty:!1})}}let q={"X-Client-Info":"realtime-js/2.9.5"};(a=v||(v={}))[a.connecting=0]="connecting",a[a.open=1]="open",a[a.closing=2]="closing",a[a.closed=3]="closed",(o=w||(w={})).closed="closed",o.errored="errored",o.joined="joined",o.joining="joining",o.leaving="leaving",(l=b||(b={})).close="phx_close",l.error="phx_error",l.join="phx_join",l.reply="phx_reply",l.leave="phx_leave",l.access_token="access_token",(_||(_={})).websocket="websocket",(h=k||(k={})).Connecting="connecting",h.Open="open",h.Closing="closing",h.Closed="closed";class K{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}class X{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):"string"==typeof e?t(JSON.parse(e)):t({})}_binaryDecode(e){let t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){let r=t.getUint8(1),i=t.getUint8(2),n=this.HEADER_LENGTH+2,a=s.decode(e.slice(n,n+r));n+=r;let o=s.decode(e.slice(n,n+i));n+=i;let l=JSON.parse(s.decode(e.slice(n,e.byteLength)));return{ref:null,topic:a,event:o,payload:l}}}class Z{constructor(e,t,s={},r=1e4){this.channel=e,this.event=t,this.payload=s,this.timeout=r,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t(null===(s=this.receivedResp)||void 0===s?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){this.timeoutTimer||(this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref),this.channel._on(this.refEvent,{},e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout))}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}(c=S||(S={})).SYNC="sync",c.JOIN="join",c.LEAVE="leave";class H{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},e=>{let{onJoin:t,onLeave:s,onSync:r}=this.caller;this.joinRef=this.channel._joinRef(),this.state=H.syncState(this.state,e,t,s),this.pendingDiffs.forEach(e=>{this.state=H.syncDiff(this.state,e,t,s)}),this.pendingDiffs=[],r()}),this.channel._on(s.diff,{},e=>{let{onJoin:t,onLeave:s,onSync:r}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=H.syncDiff(this.state,e,t,s),r())}),this.onJoin((e,t,s)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:s})}),this.onLeave((e,t,s)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:s})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,r){let i=this.cloneDeep(e),n=this.transformState(t),a={},o={};return this.map(i,(e,t)=>{n[e]||(o[e]=t)}),this.map(n,(e,t)=>{let s=i[e];if(s){let r=t.map(e=>e.presence_ref),i=s.map(e=>e.presence_ref),n=t.filter(e=>0>i.indexOf(e.presence_ref)),l=s.filter(e=>0>r.indexOf(e.presence_ref));n.length>0&&(a[e]=n),l.length>0&&(o[e]=l)}else a[e]=t}),this.syncDiff(i,{joins:a,leaves:o},s,r)}static syncDiff(e,t,s,r){let{joins:i,leaves:n}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),r||(r=()=>{}),this.map(i,(t,r)=>{var i;let n=null!==(i=e[t])&&void 0!==i?i:[];if(e[t]=this.cloneDeep(r),n.length>0){let s=e[t].map(e=>e.presence_ref),r=n.filter(e=>0>s.indexOf(e.presence_ref));e[t].unshift(...r)}s(t,n,r)}),this.map(n,(t,s)=>{let i=e[t];if(!i)return;let n=s.map(e=>e.presence_ref);i=i.filter(e=>0>n.indexOf(e.presence_ref)),e[t]=i,r(t,i,s),0===i.length&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return Object.getOwnPropertyNames(e=this.cloneDeep(e)).reduce((t,s)=>{let r=e[s];return"metas"in r?t[s]=r.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):t[s]=r,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}(u=T||(T={})).abstime="abstime",u.bool="bool",u.date="date",u.daterange="daterange",u.float4="float4",u.float8="float8",u.int2="int2",u.int4="int4",u.int4range="int4range",u.int8="int8",u.int8range="int8range",u.json="json",u.jsonb="jsonb",u.money="money",u.numeric="numeric",u.oid="oid",u.reltime="reltime",u.text="text",u.time="time",u.timestamp="timestamp",u.timestamptz="timestamptz",u.timetz="timetz",u.tsrange="tsrange",u.tstzrange="tstzrange";let G=(e,t,s={})=>{var r;let i=null!==(r=s.skipTypes)&&void 0!==r?r:[];return Object.keys(t).reduce((s,r)=>(s[r]=V(r,e,t,i),s),{})},V=(e,t,s,r)=>{let i=t.find(t=>t.name===e),n=null==i?void 0:i.type,a=s[e];return n&&!r.includes(n)?W(n,a):Y(a)},W=(e,t)=>{if("_"===e.charAt(0)){let s=e.slice(1,e.length);return es(t,s)}switch(e){case T.bool:return Q(t);case T.float4:case T.float8:case T.int2:case T.int4:case T.int8:case T.numeric:case T.oid:return ee(t);case T.json:case T.jsonb:return et(t);case T.timestamp:return er(t);case T.abstime:case T.date:case T.daterange:case T.int4range:case T.int8range:case T.money:case T.reltime:case T.text:case T.time:case T.timestamptz:case T.timetz:case T.tsrange:case T.tstzrange:default:return Y(t)}},Y=e=>e,Q=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},ee=e=>{if("string"==typeof e){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},et=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(e){console.log(`JSON parse error: ${e}`)}return e},es=(e,t)=>{if("string"!=typeof e)return e;let s=e.length-1,r=e[s],i=e[0];if("{"===i&&"}"===r){let r;let i=e.slice(1,s);try{r=JSON.parse("["+i+"]")}catch(e){r=i?i.split(","):[]}return r.map(e=>W(t,e))}return e},er=e=>"string"==typeof e?e.replace(" ","T"):e;(d=O||(O={})).ALL="*",d.INSERT="INSERT",d.UPDATE="UPDATE",d.DELETE="DELETE",(f=C||(C={})).BROADCAST="broadcast",f.PRESENCE="presence",f.POSTGRES_CHANGES="postgres_changes",(p=j||(j={})).SUBSCRIBED="SUBSCRIBED",p.TIMED_OUT="TIMED_OUT",p.CLOSED="CLOSED",p.CHANNEL_ERROR="CHANNEL_ERROR";class ei{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=w.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""}},t.config),this.timeout=this.socket.timeout,this.joinPush=new Z(this,b.join,this.params,this.timeout),this.rejoinTimer=new K(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=w.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=w.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=w.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=w.errored,this.rejoinTimer.scheduleTimeout())}),this._on(b.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new H(this),this.broadcastEndpointURL=this._broadcastEndpointURL()}subscribe(e,t=this.timeout){var s,r;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:i,presence:n}}=this.params;this._onError(t=>e&&e("CHANNEL_ERROR",t)),this._onClose(()=>e&&e("CLOSED"));let a={},o={broadcast:i,presence:n,postgres_changes:null!==(r=null===(s=this.bindings.postgres_changes)||void 0===s?void 0:s.map(e=>e.filter))&&void 0!==r?r:[]};this.socket.accessToken&&(a.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:o},a)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:t})=>{var s;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),void 0===t){e&&e("SUBSCRIBED");return}{let r=this.bindings.postgres_changes,i=null!==(s=null==r?void 0:r.length)&&void 0!==s?s:0,n=[];for(let s=0;s<i;s++){let i=r[s],{filter:{event:a,schema:o,table:l,filter:h}}=i,c=t&&t[s];if(c&&c.event===a&&c.schema===o&&c.table===l&&c.filter===h)n.push(Object.assign(Object.assign({},i),{id:c.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=n,e&&e("SUBSCRIBED");return}}).receive("error",t=>{e&&e("CHANNEL_ERROR",Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,r;if(this._canPush()||"broadcast"!==e.type)return new Promise(s=>{var r,i,n;let a=this._push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null===(n=null===(i=null===(r=this.params)||void 0===r?void 0:r.config)||void 0===i?void 0:i.broadcast)||void 0===n?void 0:n.ack)||s("ok"),a.receive("ok",()=>s("ok")),a.receive("error",()=>s("error")),a.receive("timeout",()=>s("timed out"))});{let{event:i,payload:n}=e,a={method:"POST",headers:{apikey:null!==(s=this.socket.apiKey)&&void 0!==s?s:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:n}]})};try{let e=await this._fetchWithTimeout(this.broadcastEndpointURL,a,null!==(r=t.timeout)&&void 0!==r?r:this.timeout);if(e.ok)return"ok";return"error"}catch(e){if("AbortError"===e.name)return"timed out";return"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=w.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(b.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let r=new Z(this,b.leave,{},e);r.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})})}_broadcastEndpointURL(){let e=this.socket.endPoint;return(e=(e=e.replace(/^ws/i,"http")).replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,"")).replace(/\/+$/,"")+"/api/broadcast"}async _fetchWithTimeout(e,t,s){let r=new AbortController,i=setTimeout(()=>r.abort(),s),n=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(i),n}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let r=new Z(this,e,t,s);return this._canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var r,i;let n=e.toLocaleLowerCase(),{close:a,error:o,leave:l,join:h}=b;if(s&&[a,o,l,h].indexOf(n)>=0&&s!==this._joinRef())return;let c=this._onMessage(n,t,s);if(t&&!c)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(n)?null===(r=this.bindings.postgres_changes)||void 0===r||r.filter(e=>{var t,s,r;return(null===(t=e.filter)||void 0===t?void 0:t.event)==="*"||(null===(r=null===(s=e.filter)||void 0===s?void 0:s.event)||void 0===r?void 0:r.toLocaleLowerCase())===n}).map(e=>e.callback(c,s)):null===(i=this.bindings[n])||void 0===i||i.filter(e=>{var s,r,i,a,o,l;if(!["broadcast","presence","postgres_changes"].includes(n))return e.type.toLocaleLowerCase()===n;if("id"in e){let n=e.id,a=null===(s=e.filter)||void 0===s?void 0:s.event;return n&&(null===(r=t.ids)||void 0===r?void 0:r.includes(n))&&("*"===a||(null==a?void 0:a.toLocaleLowerCase())===(null===(i=t.data)||void 0===i?void 0:i.type.toLocaleLowerCase()))}{let s=null===(o=null===(a=null==e?void 0:e.filter)||void 0===a?void 0:a.event)||void 0===o?void 0:o.toLocaleLowerCase();return"*"===s||s===(null===(l=null==t?void 0:t.event)||void 0===l?void 0:l.toLocaleLowerCase())}}).map(e=>{if("object"==typeof c&&"ids"in c){let e=c.data,{schema:t,table:s,commit_timestamp:r,type:i,errors:n}=e;c=Object.assign(Object.assign({},{schema:t,table:s,commit_timestamp:r,eventType:i,new:{},old:{},errors:n}),this._getPayloadRecords(e))}e.callback(c,s)})}_isClosed(){return this.state===w.closed}_isJoined(){return this.state===w.joined}_isJoining(){return this.state===w.joining}_isLeaving(){return this.state===w.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){let r=e.toLocaleLowerCase(),i={type:r,filter:t,callback:s};return this.bindings[r]?this.bindings[r].push(i):this.bindings[r]=[i],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(e=>{var r;return!((null===(r=e.type)||void 0===r?void 0:r.toLocaleLowerCase())===s&&ei.isEqual(e.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(b.close,{},e)}_onError(e){this._on(b.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=w.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return("INSERT"===e.type||"UPDATE"===e.type)&&(t.new=G(e.columns,e.record)),("UPDATE"===e.type||"DELETE"===e.type)&&(t.old=G(e.columns,e.old_record)),t}}let en=()=>{},ea="undefined"!=typeof WebSocket;class eo{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.headers=q,this.params={},this.timeout=1e4,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=en,this.conn=null,this.sendBuffer=[],this.serializer=new X,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>Promise.resolve().then(s.bind(s,87407)).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},this.endPoint=`${e}/${_.websocket}`,(null==t?void 0:t.transport)?this.transport=t.transport:this.transport=null,(null==t?void 0:t.params)&&(this.params=t.params),(null==t?void 0:t.headers)&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),(null==t?void 0:t.timeout)&&(this.timeout=t.timeout),(null==t?void 0:t.logger)&&(this.logger=t.logger),(null==t?void 0:t.heartbeatIntervalMs)&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let i=null===(r=null==t?void 0:t.params)||void 0===r?void 0:r.apikey;i&&(this.accessToken=i,this.apiKey=i),this.reconnectAfterMs=(null==t?void 0:t.reconnectAfterMs)?t.reconnectAfterMs:e=>[1e3,2e3,5e3,1e4][e-1]||1e4,this.encode=(null==t?void 0:t.encode)?t.encode:(e,t)=>t(JSON.stringify(e)),this.decode=(null==t?void 0:t.decode)?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new K(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(ea){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new el(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),s.e(407).then(s.t.bind(s,39407,23)).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,null!=t?t:""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case v.connecting:return k.Connecting;case v.open:return k.Open;case v.closing:return k.Closing;default:return k.Closed}}isConnected(){return this.connectionState()===k.Open}channel(e,t={config:{}}){let s=new ei(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,payload:r,ref:i}=e,n=()=>{this.encode(e,e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)})};this.log("push",`${t} ${s} (${i})`,r),this.isConnected()?n():this.sendBuffer.push(n)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(b.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:"1.0.0"}))}_onConnMessage(e){this.decode(e.data,e=>{let{topic:t,event:s,payload:r,ref:i}=e;(i&&i===this.pendingHeartbeatRef||s===(null==r?void 0:r.type))&&(this.pendingHeartbeatRef=null),this.log("receive",`${r.status||""} ${t} ${s} ${i&&"("+i+")"||""}`,r),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(s,r,i)),this.stateChangeCallbacks.message.forEach(t=>t(e))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(b.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;let s=e.match(/\?/)?"&":"?",r=new URLSearchParams(t);return`${e}${s}${r}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),null===(e=this.conn)||void 0===e||e.close(1e3,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}}class el{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=v.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}}class eh extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function ec(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}class eu extends eh{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class ed extends eh{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}let ef=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>Promise.resolve().then(s.bind(s,87407)).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},ep=()=>{var e,t,r,i;return e=void 0,t=void 0,r=void 0,i=function*(){return"undefined"==typeof Response?(yield Promise.resolve().then(s.bind(s,87407))).Response:Response},new(r||(r=Promise))(function(s,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})};var eg=function(e,t,s,r){return new(s||(s=Promise))(function(i,n){function a(e){try{l(r.next(e))}catch(e){n(e)}}function o(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((r=r.apply(e,t||[])).next())})};let ey=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),em=(e,t)=>eg(void 0,void 0,void 0,function*(){let s=yield ep();e instanceof s?e.json().then(s=>{t(new eu(ey(s),e.status||500))}).catch(e=>{t(new ed(ey(e),e))}):t(new ed(ey(e),e))}),ev=(e,t,s,r)=>{let i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?i:(i.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),s))};function ew(e,t,s,r,i,n){return eg(this,void 0,void 0,function*(){return new Promise((a,o)=>{e(s,ev(t,r,i,n)).then(e=>{if(!e.ok)throw e;return(null==r?void 0:r.noResolveJson)?e:e.json()}).then(e=>a(e)).catch(e=>em(e,o))})})}function eb(e,t,s,r){return eg(this,void 0,void 0,function*(){return ew(e,"GET",t,s,r)})}function e_(e,t,s,r,i){return eg(this,void 0,void 0,function*(){return ew(e,"POST",t,r,i,s)})}function ek(e,t,s,r,i){return eg(this,void 0,void 0,function*(){return ew(e,"DELETE",t,r,i,s)})}var eS=function(e,t,s,r){return new(s||(s=Promise))(function(i,n){function a(e){try{l(r.next(e))}catch(e){n(e)}}function o(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((r=r.apply(e,t||[])).next())})};let eT={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},eO={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class eC{constructor(e,t={},s,r){this.url=e,this.headers=t,this.bucketId=s,this.fetch=ef(r)}uploadOrUpdate(e,t,s,r){return eS(this,void 0,void 0,function*(){try{let i;let n=Object.assign(Object.assign({},eO),r),a=Object.assign(Object.assign({},this.headers),"POST"===e&&{"x-upsert":String(n.upsert)});"undefined"!=typeof Blob&&s instanceof Blob?((i=new FormData).append("cacheControl",n.cacheControl),i.append("",s)):"undefined"!=typeof FormData&&s instanceof FormData?(i=s).append("cacheControl",n.cacheControl):(i=s,a["cache-control"]=`max-age=${n.cacheControl}`,a["content-type"]=n.contentType);let o=this._removeEmptyFolders(t),l=this._getFinalPath(o),h=yield this.fetch(`${this.url}/object/${l}`,Object.assign({method:e,body:i,headers:a},(null==n?void 0:n.duplex)?{duplex:n.duplex}:{})),c=yield h.json();if(h.ok)return{data:{path:o,id:c.Id,fullPath:c.Key},error:null};return{data:null,error:c}}catch(e){if(ec(e))return{data:null,error:e};throw e}})}upload(e,t,s){return eS(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,r){return eS(this,void 0,void 0,function*(){let i=this._removeEmptyFolders(e),n=this._getFinalPath(i),a=new URL(this.url+`/object/upload/sign/${n}`);a.searchParams.set("token",t);try{let e;let t=Object.assign({upsert:eO.upsert},r),n=Object.assign(Object.assign({},this.headers),{"x-upsert":String(t.upsert)});"undefined"!=typeof Blob&&s instanceof Blob?((e=new FormData).append("cacheControl",t.cacheControl),e.append("",s)):"undefined"!=typeof FormData&&s instanceof FormData?(e=s).append("cacheControl",t.cacheControl):(e=s,n["cache-control"]=`max-age=${t.cacheControl}`,n["content-type"]=t.contentType);let o=yield this.fetch(a.toString(),{method:"PUT",body:e,headers:n}),l=yield o.json();if(o.ok)return{data:{path:i,fullPath:l.Key},error:null};return{data:null,error:l}}catch(e){if(ec(e))return{data:null,error:e};throw e}})}createSignedUploadUrl(e){return eS(this,void 0,void 0,function*(){try{let t=this._getFinalPath(e),s=yield e_(this.fetch,`${this.url}/object/upload/sign/${t}`,{},{headers:this.headers}),r=new URL(this.url+s.url),i=r.searchParams.get("token");if(!i)throw new eh("No token returned by API");return{data:{signedUrl:r.toString(),path:e,token:i},error:null}}catch(e){if(ec(e))return{data:null,error:e};throw e}})}update(e,t,s){return eS(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t){return eS(this,void 0,void 0,function*(){try{let s=yield e_(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers});return{data:s,error:null}}catch(e){if(ec(e))return{data:null,error:e};throw e}})}copy(e,t){return eS(this,void 0,void 0,function*(){try{let s=yield e_(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers});return{data:{path:s.Key},error:null}}catch(e){if(ec(e))return{data:null,error:e};throw e}})}createSignedUrl(e,t,s){return eS(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=yield e_(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},(null==s?void 0:s.transform)?{transform:s.transform}:{}),{headers:this.headers}),n=(null==s?void 0:s.download)?`&download=${!0===s.download?"":s.download}`:"",a=encodeURI(`${this.url}${i.signedURL}${n}`);return{data:i={signedUrl:a},error:null}}catch(e){if(ec(e))return{data:null,error:e};throw e}})}createSignedUrls(e,t,s){return eS(this,void 0,void 0,function*(){try{let r=yield e_(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=(null==s?void 0:s.download)?`&download=${!0===s.download?"":s.download}`:"";return{data:r.map(e=>Object.assign(Object.assign({},e),{signedUrl:e.signedURL?encodeURI(`${this.url}${e.signedURL}${i}`):null})),error:null}}catch(e){if(ec(e))return{data:null,error:e};throw e}})}download(e,t){return eS(this,void 0,void 0,function*(){let s=void 0!==(null==t?void 0:t.transform),r=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),i=r?`?${r}`:"";try{let t=this._getFinalPath(e),r=yield eb(this.fetch,`${this.url}/${s?"render/image/authenticated":"object"}/${t}${i}`,{headers:this.headers,noResolveJson:!0}),n=yield r.blob();return{data:n,error:null}}catch(e){if(ec(e))return{data:null,error:e};throw e}})}getPublicUrl(e,t){let s=this._getFinalPath(e),r=[],i=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==i&&r.push(i);let n=void 0!==(null==t?void 0:t.transform),a=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==a&&r.push(a);let o=r.join("&");return""!==o&&(o=`?${o}`),{data:{publicUrl:encodeURI(`${this.url}/${n?"render/image":"object"}/public/${s}${o}`)}}}remove(e){return eS(this,void 0,void 0,function*(){try{let t=yield ek(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers});return{data:t,error:null}}catch(e){if(ec(e))return{data:null,error:e};throw e}})}list(e,t,s){return eS(this,void 0,void 0,function*(){try{let r=Object.assign(Object.assign(Object.assign({},eT),t),{prefix:e||""}),i=yield e_(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s);return{data:i,error:null}}catch(e){if(ec(e))return{data:null,error:e};throw e}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}let ej={"X-Client-Info":"storage-js/2.5.5"};var eI=function(e,t,s,r){return new(s||(s=Promise))(function(i,n){function a(e){try{l(r.next(e))}catch(e){n(e)}}function o(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((r=r.apply(e,t||[])).next())})};class eE{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},ej),t),this.fetch=ef(s)}listBuckets(){return eI(this,void 0,void 0,function*(){try{let e=yield eb(this.fetch,`${this.url}/bucket`,{headers:this.headers});return{data:e,error:null}}catch(e){if(ec(e))return{data:null,error:e};throw e}})}getBucket(e){return eI(this,void 0,void 0,function*(){try{let t=yield eb(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers});return{data:t,error:null}}catch(e){if(ec(e))return{data:null,error:e};throw e}})}createBucket(e,t={public:!1}){return eI(this,void 0,void 0,function*(){try{let s=yield e_(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers});return{data:s,error:null}}catch(e){if(ec(e))return{data:null,error:e};throw e}})}updateBucket(e,t){return eI(this,void 0,void 0,function*(){try{let s=yield function(e,t,s,r,i){return eg(this,void 0,void 0,function*(){return ew(e,"PUT",t,r,void 0,s)})}(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers});return{data:s,error:null}}catch(e){if(ec(e))return{data:null,error:e};throw e}})}emptyBucket(e){return eI(this,void 0,void 0,function*(){try{let t=yield e_(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers});return{data:t,error:null}}catch(e){if(ec(e))return{data:null,error:e};throw e}})}deleteBucket(e){return eI(this,void 0,void 0,function*(){try{let t=yield ek(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers});return{data:t,error:null}}catch(e){if(ec(e))return{data:null,error:e};throw e}})}}class eA extends eE{constructor(e,t={},s){super(e,t,s)}from(e){return new eC(this.url,this.headers,e,this.fetch)}}let eP="";eP="undefined"!=typeof Deno?"deno":"undefined"!=typeof document?"web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";let ex={"X-Client-Info":`supabase-js-${eP}/2.43.4`},e$={headers:ex},eR={schema:"public"},eU={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},eL={},eN=e=>{let t;return t=e||("undefined"==typeof fetch?L.default:fetch),(...e)=>t(...e)},eD=()=>"undefined"==typeof Headers?L.Headers:Headers,eJ=(e,t,s)=>{let r=eN(s),i=eD();return(s,n)=>{var a,o,l,h;return a=void 0,o=void 0,l=void 0,h=function*(){var a;let o=null!==(a=yield t())&&void 0!==a?a:e,l=new i(null==n?void 0:n.headers);return l.has("apikey")||l.set("apikey",e),l.has("Authorization")||l.set("Authorization",`Bearer ${o}`),r(s,Object.assign(Object.assign({},n),{headers:l}))},new(l||(l=Promise))(function(e,t){function s(e){try{i(h.next(e))}catch(e){t(e)}}function r(e){try{i(h.throw(e))}catch(e){t(e)}}function i(t){var i;t.done?e(t.value):((i=t.value)instanceof l?i:new l(function(e){e(i)})).then(s,r)}i((h=h.apply(a,o||[])).next())})}},ez="2.64.2",eF={"X-Client-Info":`gotrue-js/${ez}`},eB="X-Supabase-Api-Version",eM={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},eq=()=>"undefined"!=typeof document,eK={tested:!1,writable:!1},eX=()=>{if(!eq())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(eK.tested)return eK.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),eK.tested=!0,eK.writable=!0}catch(e){eK.tested=!0,eK.writable=!1}return eK.writable};function eZ(e){let t={},s=new URL(e);if(s.hash&&"#"===s.hash[0])try{let e=new URLSearchParams(s.hash.substring(1));e.forEach((e,s)=>{t[s]=e})}catch(e){}return s.searchParams.forEach((e,s)=>{t[s]=e}),t}let eH=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>Promise.resolve().then(s.bind(s,87407)).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},eG=e=>"object"==typeof e&&null!==e&&"status"in e&&"ok"in e&&"json"in e&&"function"==typeof e.json,eV=async(e,t,s)=>{await e.setItem(t,JSON.stringify(s))},eW=async(e,t)=>{let s=await e.getItem(t);if(!s)return null;try{return JSON.parse(s)}catch(e){return s}},eY=async(e,t)=>{await e.removeItem(t)};class eQ{constructor(){this.promise=new eQ.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function e0(e){let t=e.split(".");if(3!==t.length)throw Error("JWT is not valid: not a JWT structure");if(!/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i.test(t[1]))throw Error("JWT is not valid: payload is not in base64url format");let s=t[1];return JSON.parse(function(e){let t,s,r,i,n,a,o;let l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h="",c=0;for(e=e.replace("-","+").replace("_","/");c<e.length;)i=l.indexOf(e.charAt(c++)),n=l.indexOf(e.charAt(c++)),a=l.indexOf(e.charAt(c++)),o=l.indexOf(e.charAt(c++)),t=i<<2|n>>4,s=(15&n)<<4|a>>2,r=(3&a)<<6|o,h+=String.fromCharCode(t),64!=a&&0!=s&&(h+=String.fromCharCode(s)),64!=o&&0!=r&&(h+=String.fromCharCode(r));return h}(s))}async function e1(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function e2(e){return("0"+e.toString(16)).substr(-2)}async function e4(e){let t=new TextEncoder,s=t.encode(e),r=await crypto.subtle.digest("SHA-256",s),i=new Uint8Array(r);return Array.from(i).map(e=>String.fromCharCode(e)).join("")}async function e6(e){let t="undefined"!=typeof crypto&&void 0!==crypto.subtle&&"undefined"!=typeof TextEncoder;if(!t)return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;let s=await e4(e);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function e3(e,t,s=!1){let r=function(){let e=new Uint32Array(56);if("undefined"==typeof crypto){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length,s="";for(let r=0;r<56;r++)s+=e.charAt(Math.floor(Math.random()*t));return s}return crypto.getRandomValues(e),Array.from(e,e2).join("")}(),i=r;s&&(i+="/PASSWORD_RECOVERY"),await eV(e,`${t}-code-verifier`,i);let n=await e6(r),a=r===n?"plain":"s256";return[n,a]}eQ.promiseConstructor=Promise;let e5=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;class e9 extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}}function e7(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class e8 extends e9{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}}class te extends e9{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class tt extends e9{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}}class ts extends tt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}class tr extends tt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class ti extends tt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class tn extends tt{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class ta extends tt{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class to extends tt{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function tl(e){return e7(e)&&"AuthRetryableFetchError"===e.name}class th extends tt{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}}var tc=function(e,t){var s={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(s[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)0>t.indexOf(r[i])&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(s[r[i]]=e[r[i]]);return s};let tu=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),td=[502,503,504];async function tf(e){var t;let s,r;if(!eG(e))throw new to(tu(e),0);if(td.includes(e.status))throw new to(tu(e),e.status);try{s=await e.json()}catch(e){throw new te(tu(e),e)}let i=function(e){let t=e.headers.get(eB);if(!t||!t.match(e5))return null;try{let e=new Date(`${t}T00:00:00.0Z`);return e}catch(e){return null}}(e);if(i&&i.getTime()>=eM["2024-01-01"].timestamp&&"object"==typeof s&&s&&"string"==typeof s.code?r=s.code:"object"==typeof s&&s&&"string"==typeof s.error_code&&(r=s.error_code),r){if("weak_password"===r)throw new th(tu(s),e.status,(null===(t=s.weak_password)||void 0===t?void 0:t.reasons)||[])}else if("object"==typeof s&&s&&"object"==typeof s.weak_password&&s.weak_password&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new th(tu(s),e.status,s.weak_password.reasons);throw new e8(tu(s),e.status||500,r)}let tp=(e,t,s,r)=>{let i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),s))};async function tg(e,t,s,r){var i;let n=Object.assign({},null==r?void 0:r.headers);n[eB]||(n[eB]=eM["2024-01-01"].name),(null==r?void 0:r.jwt)&&(n.Authorization=`Bearer ${r.jwt}`);let a=null!==(i=null==r?void 0:r.query)&&void 0!==i?i:{};(null==r?void 0:r.redirectTo)&&(a.redirect_to=r.redirectTo);let o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await ty(e,t,s+o,{headers:n,noResolveJson:null==r?void 0:r.noResolveJson},{},null==r?void 0:r.body);return(null==r?void 0:r.xform)?null==r?void 0:r.xform(l):{data:Object.assign({},l),error:null}}async function ty(e,t,s,r,i,n){let a;let o=tp(t,r,i,n);try{a=await e(s,Object.assign({},o))}catch(e){throw console.error(e),new to(tu(e),0)}if(a.ok||await tf(a),null==r?void 0:r.noResolveJson)return a;try{return await a.json()}catch(e){await tf(e)}}function tm(e){var t;let s=null;e.access_token&&e.refresh_token&&e.expires_in&&(s=Object.assign({},e),e.expires_at||(s.expires_at=function(e){let t=Math.round(Date.now()/1e3);return t+e}(e.expires_in)));let r=null!==(t=e.user)&&void 0!==t?t:e;return{data:{session:s,user:r},error:null}}function tv(e){let t=tm(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function tw(e){var t;let s=null!==(t=e.user)&&void 0!==t?t:e;return{data:{user:s},error:null}}function tb(e){return{data:e,error:null}}function t_(e){let{action_link:t,email_otp:s,hashed_token:r,redirect_to:i,verification_type:n}=e,a=tc(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o=Object.assign({},a);return{data:{properties:{action_link:t,email_otp:s,hashed_token:r,redirect_to:i,verification_type:n},user:o},error:null}}function tk(e){return e}var tS=function(e,t){var s={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(s[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)0>t.indexOf(r[i])&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(s[r[i]]=e[r[i]]);return s};class tT{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=eH(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await tg(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(e7(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await tg(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:tw})}catch(e){if(e7(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:t}=e,s=tS(e,["options"]),r=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(r.new_email=null==s?void 0:s.newEmail,delete r.newEmail),await tg(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:t_,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(e7(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await tg(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:tw})}catch(e){if(e7(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,s,r,i,n,a,o;try{let l={nextPage:null,lastPage:0,total:0},h=await tg(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(s=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==s?s:"",per_page:null!==(i=null===(r=null==e?void 0:e.perPage)||void 0===r?void 0:r.toString())&&void 0!==i?i:""},xform:tk});if(h.error)throw h.error;let c=await h.json(),u=null!==(n=h.headers.get("x-total-count"))&&void 0!==n?n:0,d=null!==(o=null===(a=h.headers.get("link"))||void 0===a?void 0:a.split(","))&&void 0!==o?o:[];return d.length>0&&(d.forEach(e=>{let t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),s=JSON.parse(e.split(";")[1].split("=")[1]);l[`${s}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},c),l),error:null}}catch(e){if(e7(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){try{return await tg(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:tw})}catch(e){if(e7(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){try{return await tg(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:tw})}catch(e){if(e7(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){try{return await tg(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:tw})}catch(e){if(e7(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){try{let{data:t,error:s}=await tg(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:s}}catch(e){if(e7(e))return{data:null,error:e};throw e}}async _deleteFactor(e){try{let t=await tg(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers});return{data:t,error:null}}catch(e){if(e7(e))return{data:null,error:e};throw e}}}let tO={getItem:e=>eX()?globalThis.localStorage.getItem(e):null,setItem:(e,t)=>{eX()&&globalThis.localStorage.setItem(e,t)},removeItem:e=>{eX()&&globalThis.localStorage.removeItem(e)}};function tC(e={}){return{getItem:t=>e[t]||null,setItem:(t,s)=>{e[t]=s},removeItem:t=>{delete e[t]}}}let tj={debug:!!(globalThis&&eX()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"))};class tI extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class tE extends tI{}async function tA(e,t,s){tj.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);let r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),tj.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async r=>{if(r){tj.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,r.name);try{return await s()}finally{tj.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,r.name)}}else{if(0===t)throw tj.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new tE(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(tj.debug)try{let e=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(e,null," "))}catch(e){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",e)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await s()}})}!function(){if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"undefined"!=typeof self&&(self.globalThis=self)}}();let tP={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:eF,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function tx(e,t,s){return await s()}class t${constructor(e){var t,s;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=t$.nextInstanceID,t$.nextInstanceID+=1,this.instanceID>0&&eq()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let r=Object.assign(Object.assign({},tP),e);if(this.logDebugMessages=!!r.debug,"function"==typeof r.debug&&(this.logger=r.debug),this.persistSession=r.persistSession,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.admin=new tT({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=eH(r.fetch),this.lock=r.lock||tx,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:eq()&&(null===(t=null==globalThis?void 0:globalThis.navigator)||void 0===t?void 0:t.locks)?this.lock=tA:this.lock=tx,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?r.storage?this.storage=r.storage:eX()?this.storage=tO:(this.memoryStorage={},this.storage=tC(this.memoryStorage)):(this.memoryStorage={},this.storage=tC(this.memoryStorage)),eq()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null===(s=this.broadcastChannel)||void 0===s||s.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${ez}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){try{let e=!!eq()&&await this._isPKCEFlow();if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:s}=await this._getSessionFromURL(e);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),(null==s?void 0:s.message)==="Identity is already linked"||(null==s?void 0:s.message)==="Identity is already linked to another user")return{error:s};return await this._removeSession(),{error:s}}let{session:r,redirectType:i}=t;return this._debug("#_initialize()","detected session in URL",r,"redirect type",i),await this._saveSession(r),setTimeout(async()=>{"recovery"===i?await this._notifyAllSubscribers("PASSWORD_RECOVERY",r):await this._notifyAllSubscribers("SIGNED_IN",r)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){if(e7(e))return{error:e};return{error:new te("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{await this._removeSession();let i=await tg(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(s=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==s?s:{},gotrue_meta_security:{captcha_token:null===(r=null==e?void 0:e.options)||void 0===r?void 0:r.captchaToken}},xform:tm}),{data:n,error:a}=i;if(a||!n)return{data:{user:null,session:null},error:a};let o=n.session,l=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",o)),{data:{user:l,session:o},error:null}}catch(e){if(e7(e))return{data:{user:null,session:null},error:e};throw e}}async signUp(e){var t,s,r;try{let i;if(await this._removeSession(),"email"in e){let{email:s,password:r,options:n}=e,a=null,o=null;"pkce"===this.flowType&&([a,o]=await e3(this.storage,this.storageKey)),i=await tg(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==n?void 0:n.emailRedirectTo,body:{email:s,password:r,data:null!==(t=null==n?void 0:n.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:a,code_challenge_method:o},xform:tm})}else if("phone"in e){let{phone:t,password:n,options:a}=e;i=await tg(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:n,data:null!==(s=null==a?void 0:a.data)&&void 0!==s?s:{},channel:null!==(r=null==a?void 0:a.channel)&&void 0!==r?r:"sms",gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}},xform:tm})}else throw new ti("You must provide either an email or phone number and a password");let{data:n,error:a}=i;if(a||!n)return{data:{user:null,session:null},error:a};let o=n.session,l=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",o)),{data:{user:l,session:o},error:null}}catch(e){if(e7(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithPassword(e){try{let t;if(await this._removeSession(),"email"in e){let{email:s,password:r,options:i}=e;t=await tg(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:tv})}else if("phone"in e){let{phone:s,password:r,options:i}=e;t=await tg(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:tv})}else throw new ti("You must provide either an email or phone number and a password");let{data:s,error:r}=t;if(r)return{data:{user:null,session:null},error:r};if(!s||!s.session||!s.user)return{data:{user:null,session:null},error:new tr};return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:r}}catch(e){if(e7(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOAuth(e){var t,s,r,i;return await this._removeSession(),await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(s=e.options)||void 0===s?void 0:s.scopes,queryParams:null===(r=e.options)||void 0===r?void 0:r.queryParams,skipBrowserRedirect:null===(i=e.options)||void 0===i?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await eW(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(null!=t?t:"").split("/"),{data:i,error:n}=await tg(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:tm});return(await eY(this.storage,`${this.storageKey}-code-verifier`),n)?{data:{user:null,session:null,redirectType:null},error:n}:i&&i.session&&i.user?(i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),{data:Object.assign(Object.assign({},i),{redirectType:null!=r?r:null}),error:n}):{data:{user:null,session:null,redirectType:null},error:new tr}}async signInWithIdToken(e){await this._removeSession();try{let{options:t,provider:s,token:r,access_token:i,nonce:n}=e,a=await tg(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:r,access_token:i,nonce:n,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:tm}),{data:o,error:l}=a;if(l)return{data:{user:null,session:null},error:l};if(!o||!o.session||!o.user)return{data:{user:null,session:null},error:new tr};return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),{data:o,error:l}}catch(e){if(e7(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOtp(e){var t,s,r,i,n;try{if(await this._removeSession(),"email"in e){let{email:r,options:i}=e,n=null,a=null;"pkce"===this.flowType&&([n,a]=await e3(this.storage,this.storageKey));let{error:o}=await tg(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:r,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},create_user:null===(s=null==i?void 0:i.shouldCreateUser)||void 0===s||s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:n,code_challenge_method:a},redirectTo:null==i?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:o}}if("phone"in e){let{phone:t,options:s}=e,{data:a,error:o}=await tg(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(r=null==s?void 0:s.data)&&void 0!==r?r:{},create_user:null===(i=null==s?void 0:s.shouldCreateUser)||void 0===i||i,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken},channel:null!==(n=null==s?void 0:s.channel)&&void 0!==n?n:"sms"}});return{data:{user:null,session:null,messageId:null==a?void 0:a.message_id},error:o}}throw new ti("You must provide either an email or phone number.")}catch(e){if(e7(e))return{data:{user:null,session:null},error:e};throw e}}async verifyOtp(e){var t,s;try{let r,i;"email_change"!==e.type&&"phone_change"!==e.type&&await this._removeSession(),"options"in e&&(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo,i=null===(s=e.options)||void 0===s?void 0:s.captchaToken);let{data:n,error:a}=await tg(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:r,xform:tm});if(a)throw a;if(!n)throw Error("An error occurred on token verification.");let o=n.session,l=n.user;return(null==o?void 0:o.access_token)&&(await this._saveSession(o),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",o)),{data:{user:l,session:o},error:null}}catch(e){if(e7(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithSSO(e){var t,s,r;try{await this._removeSession();let i=null,n=null;return"pkce"===this.flowType&&([i,n]=await e3(this.storage,this.storageKey)),await tg(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:null!==(s=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==s?s:void 0}),(null===(r=null==e?void 0:e.options)||void 0===r?void 0:r.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:n}),headers:this.headers,xform:tb})}catch(e){if(e7(e))return{data:null,error:e};throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new ts;let{error:r}=await tg(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}})}catch(e){if(e7(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{"email_change"!=e.type&&"phone_change"!=e.type&&await this._removeSession();let t=`${this.url}/resend`;if("email"in e){let{email:s,type:r,options:i}=e,{error:n}=await tg(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},redirectTo:null==i?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:n}}if("phone"in e){let{phone:s,type:r,options:i}=e,{data:n,error:a}=await tg(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:null==n?void 0:n.message_id},error:a}}throw new ti("You must provide either an email or phone number and a type")}catch(e){if(e7(e))return{data:{user:null,session:null},error:e};throw e}}async getSession(){await this.initializePromise;let e=await this._acquireLock(-1,async()=>this._useSession(async e=>e));return e}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch(e){}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){let e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",Error().stack);try{let e=null,t=await eW(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let s=!!e.expires_at&&e.expires_at<=Date.now()/1e3;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let t=this.suppressGetSessionWarning,s=new Proxy(e,{get:(e,s,r)=>(t||"user"!==s||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 many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),Reflect.get(e,s,r))});e=s}return{data:{session:e},error:null}}let{session:r,error:i}=await this._callRefreshToken(e.refresh_token);if(i)return{data:{session:null},error:i};return{data:{session:r},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t=await this._acquireLock(-1,async()=>await this._getUser());return t}async _getUser(e){try{if(e)return await tg(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:tw});return await this._useSession(async e=>{var t,s,r;let{data:i,error:n}=e;if(n)throw n;return(null===(t=i.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await tg(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(r=null===(s=i.session)||void 0===s?void 0:s.access_token)&&void 0!==r?r:void 0,xform:tw}):{data:{user:null},error:new ts}})}catch(e){if(e7(e))return{data:{user:null},error:e};throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{let{data:r,error:i}=s;if(i)throw i;if(!r.session)throw new ts;let n=r.session,a=null,o=null;"pkce"===this.flowType&&null!=e.email&&([a,o]=await e3(this.storage,this.storageKey));let{data:l,error:h}=await tg(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:o}),jwt:n.access_token,xform:tw});if(h)throw h;return n.user=l.user,await this._saveSession(n),await this._notifyAllSubscribers("USER_UPDATED",n),{data:{user:n.user},error:null}})}catch(e){if(e7(e))return{data:{user:null},error:e};throw e}}_decodeJWT(e){return e0(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new ts;let t=Date.now()/1e3,s=t,r=!0,i=null,n=e0(e.access_token);if(n.exp&&(r=(s=n.exp)<=t),r){let{session:t,error:s}=await this._callRefreshToken(e.refresh_token);if(s)return{data:{user:null,session:null},error:s};if(!t)return{data:{user:null,session:null},error:null};i=t}else{let{data:r,error:n}=await this._getUser(e.access_token);if(n)throw n;i={access_token:e.access_token,refresh_token:e.refresh_token,user:r.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(e){if(e7(e))return{data:{session:null,user:null},error:e};throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){let{data:r,error:i}=t;if(i)throw i;e=null!==(s=r.session)&&void 0!==s?s:void 0}if(!(null==e?void 0:e.refresh_token))throw new ts;let{session:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:r?{data:{user:r.user,session:r},error:null}:{data:{user:null,session:null},error:null}})}catch(e){if(e7(e))return{data:{user:null,session:null},error:e};throw e}}async _getSessionFromURL(e){try{if(!eq())throw new tn("No browser detected.");if("implicit"!==this.flowType||this._isImplicitGrantFlow()){if("pkce"==this.flowType&&!e)throw new ta("Not a valid PKCE flow url.")}else throw new tn("Not a valid implicit grant flow url.");let t=eZ(window.location.href);if(e){if(!t.code)throw new ta("No code detected.");let{data:e,error:s}=await this._exchangeCodeForSession(t.code);if(s)throw s;let r=new URL(window.location.href);return r.searchParams.delete("code"),window.history.replaceState(window.history.state,"",r.toString()),{data:{session:e.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new tn(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:s,provider_refresh_token:r,access_token:i,refresh_token:n,expires_in:a,expires_at:o,token_type:l}=t;if(!i||!a||!n||!l)throw new tn("No session defined in URL");let h=Math.round(Date.now()/1e3),c=parseInt(a),u=h+c;o&&(u=parseInt(o));let d=u-h;1e3*d<=3e4&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${d}s, should have been closer to ${c}s`);let f=u-c;h-f>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,u,h):h-f<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",f,u,h);let{data:p,error:g}=await this._getUser(i);if(g)throw g;let y={provider_token:s,provider_refresh_token:r,access_token:i,expires_in:c,expires_at:u,refresh_token:n,token_type:l,user:p.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:y,redirectType:t.type},error:null}}catch(e){if(e7(e))return{data:{session:null,redirectType:null},error:e};throw e}}_isImplicitGrantFlow(){let e=eZ(window.location.href);return!!(eq()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=eZ(window.location.href),t=await eW(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;let{data:r,error:i}=t;if(i)return{error:i};let n=null===(s=r.session)||void 0===s?void 0:s.access_token;if(n){let{error:t}=await this.admin.signOut(n,e);if(t&&!(e7(t)&&"AuthApiError"===t.name&&(404===t.status||401===t.status||403===t.status)))return{error:t}}return"others"!==e&&(await this._removeSession(),await eY(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>{await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,r;try{let{data:{session:r},error:i}=t;if(i)throw i;await (null===(s=this.stateChangeEmitters.get(e))||void 0===s?void 0:s.callback("INITIAL_SESSION",r)),this._debug("INITIAL_SESSION","callback id",e,"session",r)}catch(t){await (null===(r=this.stateChangeEmitters.get(e))||void 0===r?void 0:r.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let s=null,r=null;"pkce"===this.flowType&&([s,r]=await e3(this.storage,this.storageKey,!0));try{return await tg(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(e7(e))return{data:null,error:e};throw e}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:null!==(e=t.user.identities)&&void 0!==e?e:[]},error:null}}catch(e){if(e7(e))return{data:null,error:e};throw e}}async linkIdentity(e){var t;try{let{data:s,error:r}=await this._useSession(async t=>{var s,r,i,n,a;let{data:o,error:l}=t;if(l)throw l;let h=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null===(s=e.options)||void 0===s?void 0:s.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(i=e.options)||void 0===i?void 0:i.queryParams,skipBrowserRedirect:!0});return await tg(this.fetch,"GET",h,{headers:this.headers,jwt:null!==(a=null===(n=o.session)||void 0===n?void 0:n.access_token)&&void 0!==a?a:void 0})});if(r)throw r;return!eq()||(null===(t=e.options)||void 0===t?void 0:t.skipBrowserRedirect)||window.location.assign(null==s?void 0:s.url),{data:{provider:e.provider,url:null==s?void 0:s.url},error:null}}catch(t){if(e7(t))return{data:{provider:e.provider,url:null},error:t};throw t}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,r;let{data:i,error:n}=t;if(n)throw n;return await tg(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!==(r=null===(s=i.session)||void 0===s?void 0:s.access_token)&&void 0!==r?r:void 0})})}catch(e){if(e7(e))return{data:null,error:e};throw e}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let s=Date.now();return await function(e,t){let s=new Promise((s,r)=>{(async()=>{for(let i=0;i<1/0;i++)try{let r=await e(i);if(!t(i,null,r)){s(r);return}}catch(e){if(!t(i,e)){r(e);return}}})()});return s}(async s=>(s>0&&await e1(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await tg(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:tm})),(e,t)=>t&&tl(t)&&Date.now()+200*Math.pow(2,e)-s<3e4)}catch(e){if(this._debug(t,"error",e),e7(e))return{data:{session:null,user:null},error:e};throw e}finally{this._debug(t,"end")}}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),eq()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let s=await eW(this.storage,this.storageKey);if(this._debug(t,"session from storage",s),!this._isValidSession(s)){this._debug(t,"session is not valid"),null!==s&&await this._removeSession();return}let r=Math.round(Date.now()/1e3),i=(null!==(e=s.expires_at)&&void 0!==e?e:1/0)<r+10;if(this._debug(t,`session has${i?"":" not"} expired with margin of 10s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:e}=await this._callRefreshToken(s.refresh_token);e&&(console.error(e),tl(e)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(e){this._debug(t,"error",e),console.error(e);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new ts;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new eQ;let{data:t,error:s}=await this._refreshAccessToken(e);if(s)throw s;if(!t.session)throw new ts;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);let r={session:t.session,error:null};return this.refreshingDeferred.resolve(r),r}catch(e){if(this._debug(r,"error",e),e7(e)){let s={session:null,error:e};return tl(e)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),null===(t=this.refreshingDeferred)||void 0===t||t.resolve(s),s}throw null===(s=this.refreshingDeferred)||void 0===s||s.reject(e),e}finally{this.refreshingDeferred=null,this._debug(r,"end")}}async _notifyAllSubscribers(e,t,s=!0){let r=`#_notifyAllSubscribers(${e})`;this._debug(r,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});let r=[],i=Array.from(this.stateChangeEmitters.values()).map(async s=>{try{await s.callback(e,t)}catch(e){r.push(e)}});if(await Promise.all(i),r.length>0){for(let e=0;e<r.length;e+=1)console.error(r[e]);throw r[0]}}finally{this._debug(r,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await eV(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await eY(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&eq()&&(null==window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),3e4);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let r=Math.floor((1e3*s.expires_at-e)/3e4);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),r<=3&&await this._callRefreshToken(s.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof tI)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!eq()||!(null==window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null==window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if("visible"!==document.visibilityState){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){let r=[`provider=${encodeURIComponent(t)}`];if((null==s?void 0:s.redirectTo)&&r.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),(null==s?void 0:s.scopes)&&r.push(`scopes=${encodeURIComponent(s.scopes)}`),"pkce"===this.flowType){let[e,t]=await e3(this.storage,this.storageKey),s=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});r.push(s.toString())}if(null==s?void 0:s.queryParams){let e=new URLSearchParams(s.queryParams);r.push(e.toString())}return(null==s?void 0:s.skipBrowserRedirect)&&r.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:r,error:i}=t;return i?{data:null,error:i}:await tg(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(s=null==r?void 0:r.session)||void 0===s?void 0:s.access_token})})}catch(e){if(e7(e))return{data:null,error:e};throw e}}async _enroll(e){try{return await this._useSession(async t=>{var s,r;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:a,error:o}=await tg(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:null===(s=null==i?void 0:i.session)||void 0===s?void 0:s.access_token});return o?{data:null,error:o}:((null===(r=null==a?void 0:a.totp)||void 0===r?void 0:r.qr_code)&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(e){if(e7(e))return{data:null,error:e};throw e}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:r,error:i}=t;if(i)return{data:null,error:i};let{data:n,error:a}=await tg(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:null===(s=null==r?void 0:r.session)||void 0===s?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+n.expires_in},n)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",n),{data:n,error:a})})}catch(e){if(e7(e))return{data:null,error:e};throw e}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:r,error:i}=t;return i?{data:null,error:i}:await tg(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:null===(s=null==r?void 0:r.session)||void 0===s?void 0:s.access_token})})}catch(e){if(e7(e))return{data:null,error:e};throw e}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=(null==e?void 0:e.factors)||[],r=s.filter(e=>"totp"===e.factor_type&&"verified"===e.status);return{data:{all:s,totp:r},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;let{data:{session:r},error:i}=e;if(i)return{data:null,error:i};if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let n=this._decodeJWT(r.access_token),a=null;n.aal&&(a=n.aal);let o=a,l=null!==(s=null===(t=r.user.factors)||void 0===t?void 0:t.filter(e=>"verified"===e.status))&&void 0!==s?s:[];l.length>0&&(o="aal2");let h=n.amr||[];return{data:{currentLevel:a,nextLevel:o,currentAuthenticationMethods:h},error:null}}))}}t$.nextInstanceID=0;var tR=t$;class tU extends tR{constructor(e){super(e)}}class tL{constructor(e,t,s){var r,i,n;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw Error("supabaseUrl is required.");if(!t)throw Error("supabaseKey is required.");let a=e.replace(/\/$/,"");this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let o=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,l={db:eR,realtime:eL,auth:Object.assign(Object.assign({},eU),{storageKey:o}),global:e$},h=function(e,t){let{db:s,auth:r,realtime:i,global:n}=e,{db:a,auth:o,realtime:l,global:h}=t;return{db:Object.assign(Object.assign({},a),s),auth:Object.assign(Object.assign({},o),r),realtime:Object.assign(Object.assign({},l),i),global:Object.assign(Object.assign({},h),n)}}(null!=s?s:{},l);this.storageKey=null!==(r=h.auth.storageKey)&&void 0!==r?r:"",this.headers=null!==(i=h.global.headers)&&void 0!==i?i:{},this.auth=this._initSupabaseAuthClient(null!==(n=h.auth)&&void 0!==n?n:{},this.headers,h.global.fetch),this.fetch=eJ(t,this._getAccessToken.bind(this),h.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},h.realtime)),this.rest=new M(`${a}/rest/v1`,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new U(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new eA(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t,s,r,i,n;return s=this,r=void 0,i=void 0,n=function*(){let{data:s}=yield this.auth.getSession();return null!==(t=null===(e=s.session)||void 0===e?void 0:e.access_token)&&void 0!==t?t:null},new(i||(i=Promise))(function(e,t){function a(e){try{l(n.next(e))}catch(e){t(e)}}function o(e){try{l(n.throw(e))}catch(e){t(e)}}function l(t){var s;t.done?e(t.value):((s=t.value)instanceof i?s:new i(function(e){e(s)})).then(a,o)}l((n=n.apply(s,r||[])).next())})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,storageKey:i,flowType:n,debug:a},o,l){var h;let c={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new tU({url:this.authUrl,headers:Object.assign(Object.assign({},c),o),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,flowType:n,debug:a,fetch:l,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new eo(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,s){("TOKEN_REFRESHED"===e||"SIGNED_IN"===e)&&this.changedAccessToken!==s?(this.realtime.setAuth(null!=s?s:null),this.changedAccessToken=s):"SIGNED_OUT"===e&&(this.realtime.setAuth(this.supabaseKey),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0)}}let tN=(e,t,s)=>new tL(e,t,s);var tD=Object.create,tJ=Object.defineProperty,tz=Object.getOwnPropertyDescriptor,tF=Object.getOwnPropertyNames,tB=Object.getPrototypeOf,tM=Object.prototype.hasOwnProperty,tq=(e,t,s,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of tF(t))tM.call(e,i)||i===s||tJ(e,i,{get:()=>t[i],enumerable:!(r=tz(t,i))||r.enumerable});return e},tK=(e,t,s)=>(s=null!=e?tD(tB(e)):{},tq(!t&&e&&e.__esModule?s:tJ(s,"default",{value:e,enumerable:!0}),e)),tX=(g={"../../node_modules/.pnpm/cookie@0.5.0/node_modules/cookie/index.js"(e){e.parse=function(e,t){if("string"!=typeof e)throw TypeError("argument str must be a string");for(var s={},i=(t||{}).decode||r,n=0;n<e.length;){var a=e.indexOf("=",n);if(-1===a)break;var o=e.indexOf(";",n);if(-1===o)o=e.length;else if(o<a){n=e.lastIndexOf(";",a-1)+1;continue}var l=e.slice(n,a).trim();if(void 0===s[l]){var h=e.slice(a+1,o).trim();34===h.charCodeAt(0)&&(h=h.slice(1,-1)),s[l]=function(e,t){try{return t(e)}catch(t){return e}}(h,i)}n=o+1}return s},e.serialize=function(e,r,n){var a=n||{},o=a.encode||i;if("function"!=typeof o)throw TypeError("option encode is invalid");if(!s.test(e))throw TypeError("argument name is invalid");var l=o(r);if(l&&!s.test(l))throw TypeError("argument val is invalid");var h=e+"="+l;if(null!=a.maxAge){var c=a.maxAge-0;if(isNaN(c)||!isFinite(c))throw TypeError("option maxAge is invalid");h+="; Max-Age="+Math.floor(c)}if(a.domain){if(!s.test(a.domain))throw TypeError("option domain is invalid");h+="; Domain="+a.domain}if(a.path){if(!s.test(a.path))throw TypeError("option path is invalid");h+="; Path="+a.path}if(a.expires){var u=a.expires;if("[object Date]"!==t.call(u)&&!(u instanceof Date)||isNaN(u.valueOf()))throw TypeError("option expires is invalid");h+="; Expires="+u.toUTCString()}if(a.httpOnly&&(h+="; HttpOnly"),a.secure&&(h+="; Secure"),a.priority)switch("string"==typeof a.priority?a.priority.toLowerCase():a.priority){case"low":h+="; Priority=Low";break;case"medium":h+="; Priority=Medium";break;case"high":h+="; Priority=High";break;default:throw TypeError("option priority is invalid")}if(a.sameSite)switch("string"==typeof a.sameSite?a.sameSite.toLowerCase():a.sameSite){case!0:case"strict":h+="; SameSite=Strict";break;case"lax":h+="; SameSite=Lax";break;case"none":h+="; SameSite=None";break;default:throw TypeError("option sameSite is invalid")}return h};var t=Object.prototype.toString,s=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function r(e){return -1!==e.indexOf("%")?decodeURIComponent(e):e}function i(e){return encodeURIComponent(e)}}},function(){return y||(0,g[tF(g)[0]])((y={exports:{}}).exports,y),y.exports}),tZ=tK(tX()),tH=tK(tX());function tG(e){if(!e)return null;try{let t=JSON.parse(e);if(!t)return null;if("Object"===t.constructor.name)return t;if("Array"!==t.constructor.name)throw Error(`Unexpected format: ${t.constructor.name}`);let[s,r,i]=t[0].split("."),n=E(r),a=new TextDecoder,{exp:o,sub:l,...h}=JSON.parse(a.decode(n));return{expires_at:o,expires_in:o-Math.round(Date.now()/1e3),token_type:"bearer",access_token:t[0],refresh_token:t[1],provider_token:t[2],provider_refresh_token:t[3],user:{id:l,factors:t[4],...h}}}catch(e){return console.warn("Failed to parse cookie string:",e),null}}function tV(e){var t;return JSON.stringify([e.access_token,e.refresh_token,e.provider_token,e.provider_refresh_token,(null==(t=e.user)?void 0:t.factors)??null])}function tW(){return"undefined"!=typeof window&&void 0!==window.document}var tY={path:"/",maxAge:31536e6},tQ=class{constructor(e){this.cookieOptions={...tY,...e}}getItem(e){let t=this.getCookie(e);return t?e.endsWith("-code-verifier")?t:JSON.stringify(tG(t)):null}setItem(e,t){if(e.endsWith("-code-verifier")){this.setCookie(e,t);return}let s=JSON.parse(t),r=tV(s);this.setCookie(e,r)}removeItem(e){this.deleteCookie(e)}},t0=class extends tQ{constructor(e){super(e)}getCookie(e){if(!tW())return null;let t=(0,tZ.parse)(document.cookie);return t[e]}setCookie(e,t){if(!tW())return null;document.cookie=(0,tZ.serialize)(e,t,{...this.cookieOptions,httpOnly:!1})}deleteCookie(e){if(!tW())return null;document.cookie=(0,tZ.serialize)(e,"",{...this.cookieOptions,maxAge:0,httpOnly:!1})}};function t1(e,t,s){var r;let i=tW();return tN(e,t,{...s,auth:{flowType:"pkce",autoRefreshToken:i,detectSessionInUrl:i,persistSession:!0,storage:s.auth.storage,...(null==(r=s.auth)?void 0:r.storageKey)?{storageKey:s.auth.storageKey}:{}}})}var t2=tH.parse,t4=tH.serialize;/*!
2
- * cookie
3
- * Copyright(c) 2012-2014 Roman Shtylman
4
- * Copyright(c) 2015 Douglas Christopher Wilson
5
- * MIT Licensed
6
- */}}]);
@@ -1 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[958],{21445:function(e,t,s){Promise.resolve().then(s.bind(s,41400))},49532:function(e,t,s){"use strict";let n,i;async function r(){if(n||(i||(i=fetch("/api/config").then(e=>e.json()).then(e=>n=e.apiBaseUrl)),await i),void 0===n)throw Error("API base URL is undefined");return n}s.d(t,{b:function(){return r}})},41400:function(e,t,s){"use strict";s.r(t),s.d(t,{default:function(){return S}});var n=s(24004),i=s(14978),r=s(49532),l=s(49567),c=s(30469),a=s(65068),d=s(70417),o=s(21303),h=s(26485),u=s(30021),p=s(19708),x=s(65969),j=s(38640),v=s.n(j),m=s(28891),Z=s(40982),f=s(29794),w=s(22701),C=s(51956),y=s(82669),g=s(613),I=s(63147),k=s(34235);function P(e){var t,s,r,l;let{openDialog:p,handleClose:x,testCase:j}=e,[m,P]=(0,i.useState)(1);return(0,n.jsxs)(f.Z,{open:p,onClose:x,fullWidth:!0,maxWidth:"lg",children:[(0,n.jsxs)(y.Z,{children:["Dataset ",j.id.slice(0,6)]}),(0,n.jsxs)(C.Z,{children:[(0,n.jsx)(I.Z,{variant:"h6",style:{marginTop:"1rem"},children:"Test cases"}),(0,n.jsx)(g.u,{readOnly:!0,value:j&&k.default.dump(j.testCases),style:{width:"100%",padding:"0.75rem"},maxRows:15}),(0,n.jsx)(I.Z,{variant:"h6",style:{marginTop:"1rem"},children:"Used in..."}),(0,n.jsxs)(a.Z,{children:[(0,n.jsx)(h.Z,{children:(0,n.jsxs)(u.Z,{children:[(0,n.jsx)(o.Z,{children:"Eval ID"}),(0,n.jsx)(o.Z,{children:"Prompt ID"}),(0,n.jsx)(o.Z,{children:"Raw score"}),(0,n.jsx)(o.Z,{children:"Pass rate"}),(0,n.jsx)(o.Z,{children:"Pass count"}),(0,n.jsx)(o.Z,{children:"Fail count"}),(0,n.jsx)(o.Z,{children:"Prompt"})]})}),(0,n.jsx)(d.Z,{children:null==j?void 0:null===(t=j.prompts)||void 0===t?void 0:t.slice((m-1)*10,10*m).sort((e,t)=>t.evalId.localeCompare(e.evalId)).map((e,t)=>{var s,i,c,a,d;return(0,n.jsxs)(u.Z,{hover:!0,children:[(0,n.jsx)(o.Z,{children:(0,n.jsx)(v(),{href:"/eval/?evalId=".concat(e.evalId),children:e.evalId})}),(0,n.jsx)(o.Z,{style:{minWidth:"8em"},children:(0,n.jsx)(v(),{href:"/prompts/?id=".concat(e.id),children:e.id.slice(0,6)})}),(0,n.jsx)(o.Z,{children:"number"==typeof(null===(s=e.prompt.metrics)||void 0===s?void 0:s.score)?e.prompt.metrics.score.toFixed(2):"-"}),(0,n.jsx)(o.Z,{children:"number"==typeof(null===(i=e.prompt.metrics)||void 0===i?void 0:i.testPassCount)&&"number"==typeof(null===(c=e.prompt.metrics)||void 0===c?void 0:c.testFailCount)&&e.prompt.metrics.testPassCount+e.prompt.metrics.testFailCount>0?(e.prompt.metrics.testPassCount/(e.prompt.metrics.testPassCount+e.prompt.metrics.testFailCount)*100).toFixed(2)+"%":"-"}),(0,n.jsx)(o.Z,{children:null!==(r=null===(a=e.prompt.metrics)||void 0===a?void 0:a.testPassCount)&&void 0!==r?r:"-"}),(0,n.jsx)(o.Z,{children:null!==(l=null===(d=e.prompt.metrics)||void 0===d?void 0:d.testFailCount)&&void 0!==l?l:"-"}),(0,n.jsx)(o.Z,{children:e.prompt.raw.length>250?e.prompt.raw.slice(0,250)+"...":e.prompt.raw})]},t)})})]}),Math.ceil(((null==j?void 0:null===(s=j.prompts)||void 0===s?void 0:s.length)||0)/10)>1&&(0,n.jsx)(c.Z,{count:Math.ceil(j.prompts.length/10),page:m,onChange:(e,t)=>{P(t)}})]}),(0,n.jsx)(w.Z,{children:(0,n.jsx)(Z.Z,{onClick:x,children:"Close"})})]})}function S(){let e=(0,m.useSearchParams)(),[t,s]=(0,i.useState)([]),[j,Z]=(0,i.useState)("date"),[f,w]=(0,i.useState)("desc"),[C,y]=(0,i.useState)(1),[g,I]=(0,i.useState)(10),[k,S]=(0,i.useState)(!1),[b,E]=(0,i.useState)(0),D=e=>{let t=j===e&&"asc"===f?"desc":"asc";Z(e),w(t)};(0,i.useEffect)(()=>{(async()=>{fetch("".concat(await (0,r.b)(),"/api/datasets")).then(e=>e.json()).then(e=>{let t=[...e.data].sort((e,t)=>null===j?0:"asc"===f?e[j]>t[j]?1:-1:e[j]<t[j]?1:-1);s(t)})})()},[j,f,C,g]);let F=e=>{E(e),S(!0)};return(0,i.useEffect)(()=>{let s=null==e?void 0:e.get("id");if(s){let e=t.findIndex(e=>e.id.startsWith(s));-1!==e&&F(e)}},[t,e]),(0,n.jsxs)(l.Z,{paddingX:2,children:[(0,n.jsxs)(a.Z,{children:[(0,n.jsx)(h.Z,{children:(0,n.jsxs)(u.Z,{children:[(0,n.jsx)(o.Z,{style:{width:"10%"},children:"ID"}),(0,n.jsx)(o.Z,{style:{width:"20%"},children:(0,n.jsx)(p.Z,{active:"raw"===j,direction:"raw"===j?f:"asc",onClick:()=>D("raw"),children:"Info"})}),(0,n.jsx)(o.Z,{style:{width:"20%"},children:"Variables"}),(0,n.jsx)(o.Z,{style:{width:"10%"},children:(0,n.jsx)(p.Z,{active:"count"===j,direction:"count"===j?f:"asc",onClick:()=>D("count"),children:"Total # evals"})}),(0,n.jsx)(o.Z,{style:{width:"20%"},children:(0,n.jsx)(x.Z,{title:"The date of the most recent eval for this set of test cases",children:(0,n.jsx)(p.Z,{active:"date"===j,direction:"date"===j?f:"asc",onClick:()=>D("date"),children:"Most recent eval date"})})}),(0,n.jsx)(o.Z,{style:{width:"20%"},children:(0,n.jsx)(x.Z,{title:"The ID of the most recent eval for this set of test cases",children:(0,n.jsx)(p.Z,{active:"evalId"===j,direction:"evalId"===j?f:"asc",onClick:()=>D("evalId"),children:"Most recent eval ID"})})})]})}),(0,n.jsx)(d.Z,{children:t.slice((C-1)*g,C*g).map((e,t)=>(0,n.jsxs)(u.Z,{hover:!0,onClick:()=>F(t),style:{cursor:"pointer"},children:[(0,n.jsx)(o.Z,{children:e.id.slice(0,6)}),(0,n.jsxs)(o.Z,{style:{width:"20%",whiteSpace:"pre-wrap"},children:[e.testCases.length," test cases"]}),(0,n.jsx)(o.Z,{style:{width:"20%",whiteSpace:"pre-wrap"},children:(()=>{if(!Array.isArray(e.testCases)||"string"==typeof e.testCases[0])return"";let t=(e.testCases||[]).flatMap(e=>Object.keys(e.vars||{})),s=Array.from(new Set(t));return s.length>0?s.join(", "):"None"})()}),(0,n.jsx)(o.Z,{style:{width:"10%"},children:e.count}),(0,n.jsx)(o.Z,{style:{width:"20%"},children:e.recentEvalDate||"Unknown"}),(0,n.jsx)(o.Z,{style:{width:"20%"},children:e.recentEvalId?(0,n.jsx)(v(),{href:"/eval?evalId=".concat(e.recentEvalId),children:e.recentEvalId}):"Unknown"})]},t))})]}),Math.ceil(t.length/g)>1&&(0,n.jsx)(c.Z,{count:Math.ceil(t.length/g),page:C,onChange:(e,t)=>y(t)}),t[b]&&(0,n.jsx)(P,{openDialog:k,handleClose:()=>{S(!1)},testCase:t[b]})]})}}},function(e){e.O(0,[540,640,215,770,995,374,235,322,470,730,744],function(){return e(e.s=21445)}),_N_E=e.O()}]);
@@ -1 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[466],{57802:function(n,e,u){Promise.resolve().then(u.t.bind(u,29820,23))},29820:function(){}},function(n){n.O(0,[470,730,744],function(){return n(n.s=57802)}),_N_E=n.O()}]);
@@ -1 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[11],{61377:function(e,n,s){Promise.resolve().then(s.t.bind(s,63512,23)),Promise.resolve().then(s.bind(s,72002))}},function(e){e.O(0,[583,540,640,215,620,770,304,339,995,954,378,374,235,873,631,106,897,2,470,730,744],function(){return e(e.s=61377)}),_N_E=e.O()}]);
@@ -1 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[92],{48931:function(e,t,a){"use strict";var i=a(71851);t.Z=void 0;var r=i(a(99570)),n=a(24004);t.Z=(0,r.default)((0,n.jsx)("path",{d:"M5 20h14v-2H5zM19 9h-4V3H9v6H5l7 7z"}),"Download")},96212:function(e,t,a){"use strict";a.d(t,{f:function(){return n}});var i=a(25800),r=a(46213);function n(e){return(0,r.ZP)("MuiListItemIcon",e)}let s=(0,i.Z)("MuiListItemIcon",["root","alignItemsFlexStart"]);t.Z=s},53975:function(e,t,a){"use strict";a.d(t,{L:function(){return n}});var i=a(25800),r=a(46213);function n(e){return(0,r.ZP)("MuiListItemText",e)}let s=(0,i.Z)("MuiListItemText",["root","multiline","dense","inset","primary","secondary"]);t.Z=s},96976:function(e,t,a){"use strict";a.d(t,{Z:function(){return M}});var i=a(94312),r=a(79042),n=a(14978),s=a(53468),o=a(3982),l=a(13477),d=a(31608),c=a(11874),u=a(89020),p=a(11112),v=a(30151),m=a(16656),h=a(41776),x=a(25800);let Z=(0,x.Z)("MuiDivider",["root","absolute","fullWidth","inset","middle","flexItem","light","vertical","withChildren","withChildrenVertical","textAlignRight","textAlignLeft","wrapper","wrapperVertical"]);var f=a(96212),g=a(53975),C=a(46213);function I(e){return(0,C.ZP)("MuiMenuItem",e)}let j=(0,x.Z)("MuiMenuItem",["root","focusVisible","dense","disabled","divider","gutters","selected"]);var b=a(24004);let y=["autoFocus","component","dense","divider","disableGutters","focusVisibleClassName","role","tabIndex","className"],P=e=>{let{disabled:t,dense:a,divider:i,disableGutters:n,selected:s,classes:l}=e,d=(0,o.Z)({root:["root",a&&"dense",t&&"disabled",!n&&"gutters",i&&"divider",s&&"selected"]},I,l);return(0,r.Z)({},l,d)},w=(0,d.ZP)(v.Z,{shouldForwardProp:e=>(0,c.Z)(e)||"classes"===e,name:"MuiMenuItem",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:a}=e;return[t.root,a.dense&&t.dense,a.divider&&t.divider,!a.disableGutters&&t.gutters]}})(({theme:e,ownerState:t})=>(0,r.Z)({},e.typography.body1,{display:"flex",justifyContent:"flex-start",alignItems:"center",position:"relative",textDecoration:"none",minHeight:48,paddingTop:6,paddingBottom:6,boxSizing:"border-box",whiteSpace:"nowrap"},!t.disableGutters&&{paddingLeft:16,paddingRight:16},t.divider&&{borderBottom:`1px solid ${(e.vars||e).palette.divider}`,backgroundClip:"padding-box"},{"&:hover":{textDecoration:"none",backgroundColor:(e.vars||e).palette.action.hover,"@media (hover: none)":{backgroundColor:"transparent"}},[`&.${j.selected}`]:{backgroundColor:e.vars?`rgba(${e.vars.palette.primary.mainChannel} / ${e.vars.palette.action.selectedOpacity})`:(0,l.Fq)(e.palette.primary.main,e.palette.action.selectedOpacity),[`&.${j.focusVisible}`]:{backgroundColor:e.vars?`rgba(${e.vars.palette.primary.mainChannel} / calc(${e.vars.palette.action.selectedOpacity} + ${e.vars.palette.action.focusOpacity}))`:(0,l.Fq)(e.palette.primary.main,e.palette.action.selectedOpacity+e.palette.action.focusOpacity)}},[`&.${j.selected}:hover`]:{backgroundColor:e.vars?`rgba(${e.vars.palette.primary.mainChannel} / calc(${e.vars.palette.action.selectedOpacity} + ${e.vars.palette.action.hoverOpacity}))`:(0,l.Fq)(e.palette.primary.main,e.palette.action.selectedOpacity+e.palette.action.hoverOpacity),"@media (hover: none)":{backgroundColor:e.vars?`rgba(${e.vars.palette.primary.mainChannel} / ${e.vars.palette.action.selectedOpacity})`:(0,l.Fq)(e.palette.primary.main,e.palette.action.selectedOpacity)}},[`&.${j.focusVisible}`]:{backgroundColor:(e.vars||e).palette.action.focus},[`&.${j.disabled}`]:{opacity:(e.vars||e).palette.action.disabledOpacity},[`& + .${Z.root}`]:{marginTop:e.spacing(1),marginBottom:e.spacing(1)},[`& + .${Z.inset}`]:{marginLeft:52},[`& .${g.Z.root}`]:{marginTop:0,marginBottom:0},[`& .${g.Z.inset}`]:{paddingLeft:36},[`& .${f.Z.root}`]:{minWidth:36}},!t.dense&&{[e.breakpoints.up("sm")]:{minHeight:"auto"}},t.dense&&(0,r.Z)({minHeight:32,paddingTop:4,paddingBottom:4},e.typography.body2,{[`& .${f.Z.root} svg`]:{fontSize:"1.25rem"}}))),k=n.forwardRef(function(e,t){let a;let o=(0,u.Z)({props:e,name:"MuiMenuItem"}),{autoFocus:l=!1,component:d="li",dense:c=!1,divider:v=!1,disableGutters:x=!1,focusVisibleClassName:Z,role:f="menuitem",tabIndex:g,className:C}=o,I=(0,i.Z)(o,y),j=n.useContext(p.Z),k=n.useMemo(()=>({dense:c||j.dense||!1,disableGutters:x}),[j.dense,c,x]),M=n.useRef(null);(0,m.Z)(()=>{l&&M.current&&M.current.focus()},[l]);let F=(0,r.Z)({},o,{dense:k.dense,divider:v,disableGutters:x}),S=P(o),$=(0,h.Z)(M,t);return o.disabled||(a=void 0!==g?g:-1),(0,b.jsx)(p.Z.Provider,{value:k,children:(0,b.jsx)(w,(0,r.Z)({ref:$,role:f,tabIndex:a,component:d,focusVisibleClassName:(0,s.Z)(S.focusVisible,Z),className:(0,s.Z)(S.root,C)},I,{ownerState:F,classes:S}))})});var M=k},9147:function(e,t,a){Promise.resolve().then(a.bind(a,19259))},19259:function(e,t,a){"use strict";a.r(t),a.d(t,{default:function(){return I}});var i=a(24004),r=a(14978),n=a(48931),s=a(68873),o=a(49567),l=a(40982),d=a(36273),c=a(96976),u=a(30469),p=a(65068),v=a(70417),m=a(21303),h=a(26485),x=a(30021),Z=a(19708),f=a(67339),g=a(38640),C=a.n(g);function I(){let[e,t]=(0,r.useState)([]),[a,g]=(0,r.useState)(null),[I,j]=(0,r.useState)("asc"),[b,y]=(0,r.useState)(null),[P,w]=r.useState(1),[k,M]=(0,r.useState)({evalId:"",datasetId:"",provider:"",promptId:""}),F=!!b;(0,r.useEffect)(()=>{(async()=>{let e=await fetch("/api/progress"),a=await e.json();a&&a.data&&t(a.data)})()},[]);let S=e=>{let t=a===e&&"asc"===I;g(e),j(t?"desc":"asc")},$=e=>(null==e?void 0:e.testPassCount)!=null&&(null==e?void 0:e.testFailCount)!=null?(e.testPassCount/(e.testPassCount+e.testFailCount)*100).toFixed(2):"-",O=e=>{var t,a,i,r,n;let s=e.map(e=>{var s,o,l,d,c;return[null!==(t=e.evalId)&&void 0!==t?t:"",null!==(a=null===(s=e.datasetId)||void 0===s?void 0:s.slice(0,6))&&void 0!==a?a:"",null!==(i=e.provider)&&void 0!==i?i:"",(null!==(r=null===(o=e.promptId)||void 0===o?void 0:o.slice(0,6))&&void 0!==r?r:"")+" "+(null!==(n=e.raw)&&void 0!==n?n:""),$(e.metrics),(null===(l=e.metrics)||void 0===l?void 0:l.testPassCount)==null?"-":"".concat(e.metrics.testPassCount),(null===(d=e.metrics)||void 0===d?void 0:d.testFailCount)==null?"-":"".concat(e.metrics.testFailCount),(null===(c=e.metrics)||void 0===c?void 0:c.score)==null?"-":e.metrics.score.toFixed(2)]});return[["Eval","Dataset","Provider","Prompt","Pass Rate %","Pass Count","Fail Count","Raw score"]].concat(s).map(e=>e.map(e=>null!=e?e:"").join(",")).join("\n")},R=t=>{let a="json"===t?JSON.stringify(e):O(e),i=new Blob([a],{type:"text/".concat(t,";charset=utf-8;")}),r=document.createElement("a");r.href=URL.createObjectURL(i),r.download="cols_export.".concat(t),r.click(),URL.revokeObjectURL(r.href),y(null)},L=r.useMemo(()=>e.filter(e=>{var t,a,i,r;return(!k.evalId||(null===(t=e.evalId)||void 0===t?void 0:t.includes(k.evalId)))&&(!k.datasetId||(null===(a=e.datasetId)||void 0===a?void 0:a.startsWith(k.datasetId)))&&(!k.provider||(null===(i=e.provider)||void 0===i?void 0:i.includes(k.provider)))&&(!k.promptId||(null===(r=e.promptId)||void 0===r?void 0:r.startsWith(k.promptId)))}),[e,k]),D=r.useMemo(()=>L.sort((e,t)=>{if(!a)return 0;if("passRate"===a){let a=parseFloat($(e.metrics)),i=parseFloat($(t.metrics));return"asc"===I?a-i:i-a}if(a in e&&a in t){let i=e[a]||"",r=t[a]||"";return"asc"===I?i.toString().localeCompare(r.toString()):r.toString().localeCompare(i.toString())}return 0}),[L,a,I]),E=r.useMemo(()=>Array.from(new Set(e.map(e=>e.evalId))),[e]),V=r.useMemo(()=>Array.from(new Set(e.map(e=>e.datasetId))),[e]),N=r.useMemo(()=>Array.from(new Set(e.map(e=>e.provider))),[e]),z=r.useMemo(()=>Array.from(new Set(e.map(e=>e.promptId))),[e]);return(0,i.jsxs)(o.Z,{paddingX:2,children:[(0,i.jsxs)(o.Z,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[(0,i.jsx)("h2",{children:"Progress summary"}),(0,i.jsxs)("div",{children:[(0,i.jsx)(l.Z,{id:"export-button","aria-controls":F?"export-menu":void 0,"aria-haspopup":"true","aria-expanded":F?"true":void 0,onClick:e=>{y(e.currentTarget)},startIcon:(0,i.jsx)(n.Z,{}),children:"Export"}),(0,i.jsxs)(d.Z,{id:"export-menu",anchorEl:b,open:F,onClose:()=>{y(null)},MenuListProps:{"aria-labelledby":"export-button"},children:[(0,i.jsx)(c.Z,{onClick:()=>R("csv"),children:"CSV"}),(0,i.jsx)(c.Z,{onClick:()=>R("json"),children:"JSON"})]})]})]}),(0,i.jsx)(o.Z,{children:"This page shows performance metrics for recent evals."}),(0,i.jsxs)(o.Z,{display:"flex",flexDirection:"row",gap:2,mt:2,children:[(0,i.jsx)(s.Z,{options:E,value:k.evalId,onChange:(e,t)=>{M({...k,evalId:t||""})},renderInput:e=>(0,i.jsx)(f.Z,{...e,label:"Eval ID",variant:"outlined",size:"small",fullWidth:!0}),sx:{width:220}}),(0,i.jsx)(s.Z,{options:V,value:k.datasetId,onChange:(e,t)=>{M({...k,datasetId:t||""})},renderInput:e=>(0,i.jsx)(f.Z,{...e,label:"Dataset ID",variant:"outlined",size:"small",fullWidth:!0}),sx:{width:220}}),(0,i.jsx)(s.Z,{options:N,value:k.provider,onChange:(e,t)=>{M({...k,provider:t||""})},renderInput:e=>(0,i.jsx)(f.Z,{...e,label:"Provider",variant:"outlined",size:"small",fullWidth:!0}),sx:{width:220}}),(0,i.jsx)(s.Z,{options:z,value:k.promptId,onChange:(e,t)=>{M({...k,promptId:t||""})},renderInput:e=>(0,i.jsx)(f.Z,{...e,label:"Prompt ID",variant:"outlined",size:"small",fullWidth:!0}),sx:{width:220}})]}),(0,i.jsxs)(p.Z,{children:[(0,i.jsx)(h.Z,{children:(0,i.jsxs)(x.Z,{children:[(0,i.jsx)(m.Z,{children:(0,i.jsx)(Z.Z,{active:"evalId"===a,direction:"evalId"===a?I:"asc",onClick:()=>S("evalId"),children:"Eval"})}),(0,i.jsx)(m.Z,{children:"Dataset"}),(0,i.jsx)(m.Z,{children:"Provider"}),(0,i.jsx)(m.Z,{children:"Prompt"}),(0,i.jsx)(m.Z,{children:(0,i.jsx)(Z.Z,{active:"passRate"===a,direction:"passRate"===a?I:"asc",onClick:()=>S("passRate"),children:"Pass Rate %"})}),(0,i.jsx)(m.Z,{children:(0,i.jsx)(Z.Z,{active:"testPassCount"===a,direction:"testPassCount"===a?I:"asc",onClick:()=>S("testPassCount"),children:"Pass Count"})}),(0,i.jsx)(m.Z,{children:(0,i.jsx)(Z.Z,{active:"testFailCount"===a,direction:"testFailCount"===a?I:"asc",onClick:()=>S("testFailCount"),children:"Fail Count"})}),(0,i.jsx)(m.Z,{children:(0,i.jsx)(Z.Z,{active:"score"===a,direction:"score"===a?I:"asc",onClick:()=>S("score"),children:"Raw score"})})]})}),(0,i.jsx)(v.Z,{children:D.slice((P-1)*25,25*P).map((e,t)=>{var a,r,n,s,o;return(0,i.jsxs)(x.Z,{hover:!0,onClick:()=>M({...k,evalId:e.evalId,datasetId:e.datasetId||"",promptId:e.promptId||"",provider:e.provider}),children:[(0,i.jsx)(m.Z,{children:(0,i.jsx)(C(),{href:"/eval?evalId=".concat(e.evalId),onClick:e=>e.stopPropagation(),children:e.evalId})}),(0,i.jsx)(m.Z,{children:(0,i.jsx)(C(),{href:"/datasets?id=".concat(e.datasetId),onClick:e=>e.stopPropagation(),children:null===(a=e.datasetId)||void 0===a?void 0:a.slice(0,6)})}),(0,i.jsx)(m.Z,{children:e.provider}),(0,i.jsxs)(m.Z,{children:[(0,i.jsxs)(C(),{href:"/prompts?id=".concat(e.promptId),onClick:e=>e.stopPropagation(),children:["[",null===(r=e.promptId)||void 0===r?void 0:r.slice(0,6),"]"]})," ",e.raw]}),(0,i.jsx)(m.Z,{children:$(e.metrics)}),(0,i.jsx)(m.Z,{children:(null===(n=e.metrics)||void 0===n?void 0:n.testPassCount)==null?"-":"".concat(e.metrics.testPassCount)}),(0,i.jsx)(m.Z,{children:(null===(s=e.metrics)||void 0===s?void 0:s.testFailCount)==null?"-":"".concat(e.metrics.testFailCount)}),(0,i.jsx)(m.Z,{children:(null===(o=e.metrics)||void 0===o?void 0:o.score)==null?"-":e.metrics.score.toFixed(2)})]},t)})})]}),Math.ceil(L.length/25)>1&&(0,i.jsx)(u.Z,{count:Math.ceil(D.length/25),page:P,onChange:(e,t)=>w(t),sx:{pt:2,pb:4,display:"flex",justifyContent:"center"}})]})}}},function(e){e.O(0,[540,640,215,620,770,304,339,378,873,322,470,730,744],function(){return e(e.s=9147)}),_N_E=e.O()}]);
@@ -1 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[413],{72846:function(e,t,n){Promise.resolve().then(n.bind(n,83013))},83013:function(e,t,n){"use strict";n.r(t),n.d(t,{default:function(){return ed}});var a=n(24004),i=n(14978),r=n(69179),l=n(47887),s=n(49567),o=n(40982),c=n(11520),d=n(29794),p=n(22701),u=n(51956),h=n(8541),x=n(82669),m=n(32414),f=n(63147),g=n(75307),j=n(63346),v=n(89235),Z=n(4078),b=n(67339),y=()=>{let{env:e,setEnv:t}=(0,l.o)(),[n,r]=(0,i.useState)(!1),[s,c]=(0,i.useState)(e),h=()=>{r(!1)};return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(o.Z,{variant:"outlined",startIcon:(0,a.jsx)(g.Z,{}),onClick:()=>{r(!0)},children:"API keys"}),(0,a.jsxs)(d.Z,{open:n,onClose:h,fullWidth:!0,maxWidth:"md",children:[(0,a.jsx)(x.Z,{children:"Provider settings"}),(0,a.jsxs)(u.Z,{children:[(0,a.jsxs)(j.Z,{defaultExpanded:!0,children:[(0,a.jsx)(Z.Z,{children:"OpenAI"}),(0,a.jsxs)(v.Z,{children:[(0,a.jsx)(b.Z,{label:"OpenAI API key",fullWidth:!0,margin:"normal",value:s.OPENAI_API_KEY,onChange:e=>c({...s,OPENAI_API_KEY:e.target.value})}),(0,a.jsx)(b.Z,{label:"OpenAI API host",fullWidth:!0,margin:"normal",value:s.OPENAI_API_HOST,onChange:e=>c({...s,OPENAI_API_HOST:e.target.value})}),(0,a.jsx)(b.Z,{label:"OpenAI organization",fullWidth:!0,margin:"normal",value:s.OPENAI_ORGANIZATION,onChange:e=>c({...s,OPENAI_ORGANIZATION:e.target.value})})]})]}),(0,a.jsxs)(j.Z,{children:[(0,a.jsx)(Z.Z,{children:"Azure"}),(0,a.jsx)(v.Z,{children:(0,a.jsx)(b.Z,{label:"Azure API key",fullWidth:!0,margin:"normal",value:s.AZURE_OPENAI_API_KEY,onChange:e=>c({...s,AZURE_OPENAI_API_KEY:e.target.value})})})]}),(0,a.jsxs)(j.Z,{children:[(0,a.jsx)(Z.Z,{children:"Amazon Bedrock"}),(0,a.jsx)(v.Z,{children:(0,a.jsx)(b.Z,{label:"Bedrock Region",fullWidth:!0,margin:"normal",value:s.AWS_BEDROCK_REGION,onChange:e=>c({...s,AWS_BEDROCK_REGION:e.target.value})})})]}),(0,a.jsxs)(j.Z,{children:[(0,a.jsx)(Z.Z,{children:"Anthropic"}),(0,a.jsx)(v.Z,{children:(0,a.jsx)(b.Z,{label:"Anthropic API key",fullWidth:!0,margin:"normal",value:s.ANTHROPIC_API_KEY,onChange:e=>c({...s,ANTHROPIC_API_KEY:e.target.value})})})]}),(0,a.jsxs)(j.Z,{children:[(0,a.jsx)(Z.Z,{children:"Google Vertex AI"}),(0,a.jsx)(v.Z,{children:(0,a.jsx)(b.Z,{label:"Vertex API Key",fullWidth:!0,margin:"normal",value:s.VERTEX_API_KEY,onChange:e=>c({...s,VERTEX_API_KEY:e.target.value})})}),(0,a.jsx)(v.Z,{children:(0,a.jsx)(b.Z,{label:"Vertex Project ID",fullWidth:!0,margin:"normal",value:s.VERTEX_PROJECT_ID,onChange:e=>c({...s,VERTEX_PROJECT_ID:e.target.value})})}),(0,a.jsx)(v.Z,{children:(0,a.jsx)(b.Z,{label:"Vertex Region",fullWidth:!0,margin:"normal",value:s.VERTEX_REGION,onChange:e=>c({...s,VERTEX_REGION:e.target.value})})})]}),(0,a.jsxs)(j.Z,{children:[(0,a.jsx)(Z.Z,{children:"Replicate"}),(0,a.jsx)(v.Z,{children:(0,a.jsx)(b.Z,{label:"Replicate API key",fullWidth:!0,margin:"normal",value:s.REPLICATE_API_KEY,onChange:e=>c({...s,REPLICATE_API_KEY:e.target.value})})})]})]}),(0,a.jsxs)(p.Z,{children:[(0,a.jsx)(o.Z,{onClick:h,color:"primary",children:"Cancel"}),(0,a.jsx)(o.Z,{onClick:()=>{t(s),h()},color:"primary",variant:"contained",children:"Save"})]})]})]})},_=n(35185),C=n(5592),k=n(14931),A=n(2185),E=n(77656),I=n(65068),O=n(70417),P=n(21303),S=n(61451),T=n(30021),w=n(65969),R=e=>{let{open:t,prompt:n,index:r,onAdd:l,onCancel:s}=e,[c,h]=i.useState(n),m=i.useRef(null);i.useEffect(()=>{h(n)},[n]);let f=e=>{l(c),h(""),e?s():m.current&&m.current.focus()};return(0,a.jsxs)(d.Z,{open:t,onClose:s,fullWidth:!0,maxWidth:"md",children:[(0,a.jsx)(x.Z,{children:"Edit Prompt ".concat(r+1)}),(0,a.jsx)(u.Z,{children:(0,a.jsx)(b.Z,{value:c,onChange:e=>h(e.target.value),fullWidth:!0,margin:"normal",multiline:!0,placeholder:"The quick brown {{animal1}} jumps over the lazy {{animal2}}.",helperText:"Tip: use the {{varname}} syntax to add variables to your prompt.",inputRef:m})}),(0,a.jsxs)(p.Z,{children:[(0,a.jsx)(o.Z,{onClick:f.bind(null,!0),color:"primary",variant:"contained",disabled:!c.length,children:"Add"}),(0,a.jsx)(o.Z,{onClick:f.bind(null,!1),color:"primary",variant:"contained",disabled:!c.length,children:"Add Another"}),(0,a.jsx)(o.Z,{onClick:s,color:"secondary",children:"Cancel"})]})]})};n(94499);var W=()=>{let[e,t]=(0,i.useState)(!1),[n,r]=(0,i.useState)(null),{prompts:s,setPrompts:c}=(0,l.o)(),d=(0,i.useRef)(null);(0,i.useEffect)(()=>{null!==n&&n>0&&d.current&&d.current.focus()},[n]);let p=e=>{r(e),t(!0)},u=(e,t)=>{e.stopPropagation();let n=s[t];c([...s,n])},h=(e,t)=>{c(s.map((n,a)=>a===e?t:n))},x=(e,t)=>{e.stopPropagation(),confirm("Are you sure you want to remove this prompt?")&&c(s.filter((e,n)=>n!==t))};return(0,a.jsxs)("div",{children:[(0,a.jsxs)(m.Z,{direction:"row",spacing:2,justifyContent:"space-between",children:[(0,a.jsx)(f.Z,{variant:"h5",children:"Prompts"}),(0,a.jsxs)("div",{children:[(0,a.jsx)("label",{htmlFor:"file-input-add-prompt",children:(0,a.jsx)(w.Z,{title:"Upload prompt from file",children:(0,a.jsxs)("span",{children:[(0,a.jsx)(E.Z,{component:"span",children:(0,a.jsx)(A.Z,{})}),(0,a.jsx)("input",{id:"file-input-add-prompt",type:"file",accept:".txt,.md",onChange:e=>{var t;e.stopPropagation(),e.preventDefault();let n=null===(t=e.target.files)||void 0===t?void 0:t[0];if(n){let e=new FileReader;e.onload=e=>{var t,n;let a=null===(n=e.target)||void 0===n?void 0:null===(t=n.result)||void 0===t?void 0:t.toString();a&&c([...s,a])},e.readAsText(n)}},style:{display:"none"}})]})})}),(0,a.jsx)(o.Z,{color:"primary",onClick:()=>{t(!0)},variant:"contained",children:"Add Prompt"})]})]}),(0,a.jsx)(S.Z,{children:(0,a.jsx)(I.Z,{children:(0,a.jsx)(O.Z,{children:0===s.length?(0,a.jsx)(T.Z,{children:(0,a.jsx)(P.Z,{colSpan:2,align:"center",children:"No prompts added yet."})}):s.map((e,t)=>(0,a.jsxs)(T.Z,{sx:{"&:hover":{backgroundColor:"rgba(0, 0, 0, 0.04)",cursor:"pointer"}},onClick:()=>p(t),children:[(0,a.jsx)(P.Z,{children:(0,a.jsxs)(f.Z,{variant:"body2",children:["Prompt #".concat(t+1,": "),(e.length>250?e.slice(0,250)+" ...":e).split(/({{\w+}})/g).map((e,t)=>/{{\s*(\w+)\s*}}/g.test(e)?(0,a.jsx)("span",{className:"prompt-var-highlight",children:e},t):e)]})}),(0,a.jsxs)(P.Z,{align:"right",sx:{minWidth:150},children:[(0,a.jsx)(E.Z,{onClick:()=>p(t),size:"small",children:(0,a.jsx)(k.Z,{})}),(0,a.jsx)(E.Z,{onClick:e=>u(e,t),size:"small",children:(0,a.jsx)(_.Z,{})}),(0,a.jsx)(E.Z,{onClick:e=>x(e,t),size:"small",children:(0,a.jsx)(C.Z,{})})]})]},t))})})}),(0,a.jsx)(R,{open:e,prompt:null!==n?s[n]:"",index:null!==n?n:0,onAdd:e=>{null!==n?h(n,e):c([...s,e]),r(null)},onCancel:()=>{r(null),t(!1)}})]})},N=n(68873),z=n(885),F=e=>{let{onChange:t,...n}=e,[r,l]=i.useState(""),[s,o]=i.useState(!1);return(0,a.jsx)(b.Z,{...n,error:s,helperText:s?"Invalid JSON":"",value:r,onChange:e=>{let n=e.target.value;try{let e=JSON.parse(n);l(n),o(!1),t&&t(e)}catch(e){l(n),o(!0)}}})},V=e=>{let{open:t,providerId:n,config:r,onClose:l,onSave:c}=e,[h,m]=i.useState(r);return i.useEffect(()=>{m(r)},[r]),(0,a.jsxs)(d.Z,{open:t,onClose:l,fullWidth:!0,maxWidth:"md",children:[(0,a.jsxs)(x.Z,{children:["Edit ",n.length>50?n.slice(0,50)+"...":n]}),(0,a.jsx)(u.Z,{children:Object.keys(h).map(e=>{let t;let n=h[e];return"number"==typeof n||"boolean"==typeof n||"string"==typeof n?(t="number"==typeof n?t=>m({...h,[e]:parseFloat(t.target.value)}):"boolean"==typeof n?t=>m({...h,[e]:"true"===t.target.value}):t=>{let n=t.target.value.trim();if(n.startsWith("{")||n.startsWith("["))try{m({...h,[e]:JSON.parse(n)})}catch(t){m({...h,[e]:n})}else"null"===n?m({...h,[e]:null}):"undefined"===n?m({...h,[e]:void 0}):m({...h,[e]:n})},(0,a.jsx)(s.Z,{my:2,children:(0,a.jsx)(b.Z,{label:e,value:n,onChange:t,fullWidth:!0,InputLabelProps:{shrink:!0},type:"number"==typeof n?"number":"text"})},e)):(0,a.jsx)(s.Z,{my:2,children:(0,a.jsx)(F,{label:e,defaultValue:JSON.stringify(n),onChange:t=>{m({...h,[e]:t})},fullWidth:!0,multiline:!0,minRows:2,InputLabelProps:{shrink:!0}})},e)})}),(0,a.jsxs)(p.Z,{children:[(0,a.jsx)(o.Z,{onClick:l,children:"Cancel"}),(0,a.jsx)(o.Z,{onClick:()=>{c(h)},children:"Save"})]})]})};let L=[].concat(["replicate:replicate/flan-t5-small:69716ad8c34274043bf4a135b7315c7c569ec931d8f23d6826e249e1c142a264"].map(e=>({id:e,config:{temperature:.5,max_length:1024,repetition_penality:1}}))).concat(["replicate:replicate/codellama-7b-instruct:0103579e86fc75ba0d65912890fa19ef03c84a68554635319accf2e0ba93d3ae","replicate:replicate/codellama-13b-instruct:da5676342de1a5a335b848383af297f592b816b950a43d251a0a9edd0113604b","replicate:replicate/llama-2-70b-chat:2796ee9483c3fd7aa2e171d38f4ca12251a30609463dcfd4cd76703f22e96cdf"].map(e=>({id:e,config:{system_prompt:"",temperature:.75,top_p:.9,top_k:50,max_new_tokens:128,min_new_tokens:-1}}))).concat(["replicate:replicate/codellama-7b:6880b103613a9cd23950c5fd6c140197e519905bd0dd00e448c4858bdd06090a","replicate:replicate/codellama-13b-python:09b87c02dfa403e0c3289166dece62286b3bce49bae39a9c9204713cf94b8b7d","replicate:replicate/codellama-13b:1c914d844307b0588599b8393480a3ba917b660c7e9dfae681542b5325f228db","replicate:replicate/codellama-34b-python:9048743d22a7b19cd0abb018066809ea6af4f2b4717bef9aad3c5ae21ceac00d","replicate:replicate/codellama-34b:0666717e5ead8557dff55ee8f11924b5c0309f5f1ca52f64bb8eec405fdb38a7"].map(e=>({id:e,config:{temperature:.75,top_p:.9,top_k:50,max_new_tokens:128,min_new_tokens:-1}}))).concat(["replicate:a16z-infra/llama-2-7b-chat:7b0bfc9aff140d5b75bacbed23e91fd3c34b01a1e958d32132de6e0a19796e2c","replicate:a16z-infra/llama-2-13b-chat:2a7f981751ec7fdf87b5b91ad4db53683a98082e9ff7bfd12c8cd5ea85980a52"].map(e=>({id:e,config:{temperature:.95,top_p:.95,top_k:250,max_new_tokens:500,min_new_tokens:-1,repetition_penalty:1,system_prompt:""}}))).concat(["replicate:mistralai/mistral-7b-v0.1","replicate:mistralai/mistral-7b-instruct-v0.2","replicate:mistralai/mixtral-8x7b-instruct-v0.1"].map(e=>({id:e,config:{temperature:.7,top_p:.9,top_k:-1,max_new_tokens:128,min_new_tokens:-1,repetition_penalty:1.15,prompt_template:"{prompt}"}}))).concat(["anthropic:claude-1","anthropic:claude-1-100k","anthropic:claude-instant-1","anthropic:claude-instant-1-100k"].map(e=>({id:e,config:{max_tokens_to_sample:256,temperature:.5}}))).concat(["anthropic:messages:claude-instant-1.2","anthropic:messages:claude-2.0","anthropic:messages:claude-2.1","anthropic:messages:claude-3-haiku-20240307","anthropic:messages:claude-3-sonnet-20240229","anthropic:messages:claude-3-opus-20240229"].map(e=>({id:e,config:{max_tokens:1024,temperature:.5}}))).concat(["bedrock:anthropic.claude-instant-v1","bedrock:anthropic.claude-v1","bedrock:anthropic.claude-v2"].map(e=>({id:e,config:{max_tokens_to_sample:256,temperature:.5}}))).concat(["openai:gpt-3.5-turbo","openai:gpt-3.5-turbo-0301","openai:gpt-3.5-turbo-0613","openai:gpt-3.5-turbo-16k","openai:gpt-3.5-turbo-16k-0613","openai:gpt-4","openai:gpt-4-0314","openai:gpt-4-0613","openai:gpt-4-32k","openai:gpt-4-32k-0314"].map(e=>({id:e,config:{organization:"",temperature:.5,max_tokens:1024,top_p:1,frequency_penalty:0,presence_penalty:0,function_call:void 0,functions:void 0,stop:void 0}}))).concat(["azureopenai:gpt-3.5-turbo","azureopenai:gpt-3.5-turbo-0301","azureopenai:gpt-3.5-turbo-0613","azureopenai:gpt-3.5-turbo-16k","azureopenai:gpt-3.5-turbo-16k-0613","azureopenai:gpt-4","azureopenai:gpt-4-0314","azureopenai:gpt-4-0613","azureopenai:gpt-4-32k","azureopenai:gpt-4-32k-0314"].map(e=>({id:e,config:{temperature:.5,max_tokens:1024,top_p:1,frequency_penalty:0,presence_penalty:0,function_call:void 0,functions:void 0,stop:void 0}}))).concat(["vertex:chat-bison@001","vertex:chat-bison","vertex:chat-bison-32k","vertex:chat-bison-32k@001"].map(e=>({id:e,config:{context:void 0,examples:void 0,temperature:0,maxOutputTokens:1024,topP:.95,topK:40,safetySettings:void 0,stopSequence:void 0}}))).sort((e,t)=>e.id.localeCompare(t.id)),U={anthropic:"Anthropic",bedrock:"Amazon Web Services",azureopenai:"Azure",openai:"OpenAI",replicate:"Replicate"};var q=e=>{let{providers:t,onChange:n}=e,[r,l]=i.useState(null),o=e=>"string"==typeof e?e:e.id||"Unknown provider",c=(e,t)=>"string"==typeof e?e:e.id||t,d=e=>{"string"==typeof e?alert("Cannot edit custom providers"):e.config?l(e):alert("There is no config for this provider")};return(0,a.jsxs)(s.Z,{mt:2,children:[(0,a.jsx)(N.Z,{multiple:!0,freeSolo:!0,options:L,value:t,groupBy:e=>(function(e){if(!e)return"Other";let t=e.split(":")[0];return U[t]||t})(e.id),onChange:(e,t)=>{n(t.map(e=>"string"==typeof e?{id:e}:e))},getOptionLabel:e=>{if(!e)return"";let t="";"string"==typeof e&&(t=e),e.id&&"string"==typeof e.id&&(t=e.id);let n=t.split(":");return n.length>1?n.length>2&&"anthropic"===n[0]?n[2]:n[1]:"Unknown provider"},renderTags:(e,t)=>e.map((e,n)=>{let a=o(e),r=c(e,n);return(0,i.createElement)(z.Z,{variant:"outlined",label:a,...t({index:n}),key:r,onClick:()=>d(e)})}),renderInput:e=>(0,a.jsx)(b.Z,{...e,variant:"outlined",placeholder:"Select LLM providers",helperText:t.length>0?"Click a provider to configure its settings.":null})}),r&&r.id&&(0,a.jsx)(V,{open:!!r,providerId:r.id,config:r.config,onClose:()=>l(null),onSave:e=>{if(r){let a=t.map(t=>t.id===r.id?{...t,config:e}:t);n(a),l(null)}}})]})},B=n(52428),K=n(11615),D=n(28891),Y=()=>{let e=(0,D.useRouter)(),{env:t,description:n,providers:r,prompts:s,testCases:c,defaultTest:d,evaluateOptions:p}=(0,l.o)(),[u,h]=(0,i.useState)(!1),[x,m]=(0,i.useState)(0),f=async()=>{h(!0);try{let a=await fetch("".concat(B.eA,"/api/eval/job/"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({env:t,description:n,providers:r,prompts:s,tests:c,defaultTest:d,evaluateOptions:p})});if(!a.ok)throw Error("HTTP error! status: ".concat(a.status));let i=await a.json(),l=setInterval(async()=>{let t=await fetch("".concat(B.eA,"/api/eval/job/").concat(i.id,"/"));if(!t.ok)throw clearInterval(l),Error("HTTP error! status: ".concat(t.status));let n=await t.json();if("complete"===n.status)clearInterval(l),h(!1),B.Ox?e.push("/eval/remote:".concat(encodeURIComponent(i.id))):e.push("/eval");else if("failed"===n.status)throw clearInterval(l),h(!1),Error("Job failed");else{let e=0===n.total?0:Math.round(n.progress/n.total*100);m(e)}},1e3)}catch(e){console.error(e),h(!1),alert("An error occurred: ".concat(e.message))}};return(0,a.jsx)(o.Z,{variant:"contained",color:"primary",onClick:f,disabled:u,children:u?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(K.Z,{size:24,sx:{marginRight:2}}),x.toFixed(0),"% complete"]}):"Run Evaluation"})},J=n(15320),X=n(26485);let G=["equals","contains","icontains","contains-all","contains-any","starts-with","regex","is-json","contains-json","is-sql","contains-sql","similar","llm-rubric","model-graded-closedqa","factuality","webhook","rouge-n","rouge-s","rouge-l","not-equals","not-contains","not-icontains","not-contains-all","not-contains-any","not-starts-with","not-regex","not-is-json","not-contains-json","not-similar","not-webhook","not-rouge-n","not-rouge-s","not-rouge-l","is-valid-openai-function-call","is-valid-openai-tools-call","latency","perplexity","perplexity-score","cost","answer-relevance","context-faithfulness","context-recall","context-relevance","select-best","moderation"];var H=e=>{let{onAdd:t,initialValues:n}=e,[r,l]=(0,i.useState)(n||[]),c=e=>{let n=r.filter((t,n)=>n!==e);l(n),t(n)};return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(f.Z,{variant:"h6",children:"Asserts"}),(0,a.jsx)(s.Z,{my:r.length>0?2:0,children:(0,a.jsx)(m.Z,{direction:"column",spacing:2,children:r.map((e,n)=>(0,a.jsxs)(m.Z,{direction:"row",spacing:2,alignItems:"center",children:[(0,a.jsx)(N.Z,{value:e.type,options:G,sx:{minWidth:200},onChange:(e,a)=>{let i=r.map((e,t)=>t===n?{...e,type:a}:e);l(i),t(i)},renderInput:e=>(0,a.jsx)(b.Z,{...e,label:"Type"})}),(0,a.jsx)(b.Z,{label:"Value",value:e.value,fullWidth:!0,onChange:e=>{let a=e.target.value,i=r.map((e,t)=>t===n?{...e,value:a}:e);l(i),t(i)}}),(0,a.jsx)(E.Z,{onClick:()=>c(n),size:"small",children:(0,a.jsx)(C.Z,{})})]},n))})}),(0,a.jsx)(o.Z,{color:"primary",onClick:()=>{let e=[...r,{type:"equals",value:""}];l(e),t(e)},children:"Add Assert"})]})},M=e=>{let{onAdd:t,varsList:n,initialValues:r}=e,[l,o]=i.useState(r||{});return(0,i.useEffect)(()=>{let e={};n.forEach(t=>{e[t]=(null==r?void 0:r[t])||""}),o(e)},[n,r]),(0,a.jsxs)(s.Z,{my:2,children:[(0,a.jsx)(f.Z,{variant:"h6",mb:2,children:"Vars"}),n.length>0?(0,a.jsx)(m.Z,{direction:"row",spacing:2,alignItems:"center",children:Object.keys(l).map((e,n)=>(0,a.jsx)(m.Z,{direction:"row",spacing:2,alignItems:"center",children:(0,a.jsx)(b.Z,{placeholder:e,label:e,value:l[e],fullWidth:!0,onChange:n=>{let a=n.target.value,i={...l,[e]:a};o(i),t(i)}})},n))}):(0,a.jsxs)(f.Z,{variant:"subtitle1",gutterBottom:!0,children:["Add variables to your prompt using the ","{{varname}}"," syntax."]})]})},$=e=>{let{open:t,onAdd:n,varsList:r,initialValues:l,onCancel:c}=e,[h,m]=(0,i.useState)((null==l?void 0:l.description)||""),[f,g]=(0,i.useState)((null==l?void 0:l.vars)||{}),[j,v]=(0,i.useState)((null==l?void 0:l.assert)||[]),[Z,b]=(0,i.useState)(0);i.useEffect(()=>{l?(m(l.description||""),g(l.vars||{}),v(l.assert||[])):(m(""),g({}),v([]))},[l]);let y=e=>{n({description:h,vars:f,assert:j},e),e&&c(),m(""),g({}),v([]),b(e=>e+1)};return(0,a.jsxs)(d.Z,{open:t,onClose:c,fullWidth:!0,maxWidth:"md",children:[(0,a.jsx)(x.Z,{children:l?"Edit Test Case":"Add Test Case"}),(0,a.jsx)(u.Z,{children:(0,a.jsxs)(s.Z,{children:[(0,a.jsx)(M,{onAdd:e=>g(e),varsList:r,initialValues:null==l?void 0:l.vars}),(0,a.jsx)(H,{onAdd:e=>v(e),initialValues:((null==l?void 0:l.assert)||[]).filter(e=>"assert-set"!==e.type)||[]},Z)]})}),(0,a.jsxs)(p.Z,{children:[(0,a.jsx)(o.Z,{onClick:y.bind(void 0,!0),color:"primary",variant:"contained",children:l?"Update Test Case":"Add Test Case"}),!l&&(0,a.jsx)(o.Z,{onClick:y.bind(void 0,!1),color:"primary",variant:"contained",children:"Add Another"}),(0,a.jsx)(o.Z,{onClick:c,color:"secondary",children:"Cancel"})]})]})},Q=e=>{let{varsList:t}=e,{testCases:r,setTestCases:s}=(0,l.o)(),[c,d]=i.useState(null),[p,u]=i.useState(!1),h=(e,t)=>{e.stopPropagation(),confirm("Are you sure you want to delete this test case?")&&s(r.filter((e,n)=>n!==t))},x=(e,t)=>{e.stopPropagation();let n=JSON.parse(JSON.stringify(r[t]));s([...r,n])};return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(m.Z,{direction:"row",spacing:2,justifyContent:"space-between",children:[(0,a.jsx)(f.Z,{variant:"h5",children:"Test Cases"}),(0,a.jsxs)("div",{children:[(0,a.jsx)("label",{htmlFor:"file-input-add-test-case",children:(0,a.jsx)(w.Z,{title:"Upload test cases from csv",children:(0,a.jsxs)("span",{children:[(0,a.jsx)(E.Z,{component:"span",children:(0,a.jsx)(A.Z,{})}),(0,a.jsx)("input",{id:"file-input-add-test-case",type:"file",accept:".csv",onChange:e=>{var t;e.stopPropagation(),e.preventDefault();let a=null===(t=e.target.files)||void 0===t?void 0:t[0];if(a){let e=new FileReader;e.onload=async e=>{var t,a;let i=null===(a=e.target)||void 0===a?void 0:null===(t=a.result)||void 0===t?void 0:t.toString();if(i){let{parse:e}=await Promise.all([n.e(631),n.e(887)]).then(n.bind(n,83887)),t=e(i,{columns:!0});s([...r,...t.map(e=>(0,J.It)(e))])}},e.readAsText(a)}},style:{display:"none"}})]})})}),(0,a.jsx)(o.Z,{color:"primary",onClick:()=>u(!0),variant:"contained",children:"Add Test Case"})]})]}),(0,a.jsx)(S.Z,{children:(0,a.jsxs)(I.Z,{children:[(0,a.jsx)(X.Z,{children:(0,a.jsxs)(T.Z,{children:[(0,a.jsx)(P.Z,{children:"Description"}),(0,a.jsx)(P.Z,{children:"Assertions"}),(0,a.jsx)(P.Z,{children:"Variables"}),(0,a.jsx)(P.Z,{align:"right"})]})}),(0,a.jsx)(O.Z,{children:0===r.length?(0,a.jsx)(T.Z,{children:(0,a.jsx)(P.Z,{colSpan:4,align:"center",children:"No test cases added yet."})}):r.map((e,t)=>{var n;return(0,a.jsxs)(T.Z,{sx:{"&:hover":{backgroundColor:"rgba(0, 0, 0, 0.04)",cursor:"pointer"}},onClick:()=>{d(t),u(!0)},children:[(0,a.jsx)(P.Z,{children:(0,a.jsx)(f.Z,{variant:"body2",children:e.description||"Test Case #".concat(t+1)})}),(0,a.jsxs)(P.Z,{children:[(null===(n=e.assert)||void 0===n?void 0:n.length)||0," assertions"]}),(0,a.jsx)(P.Z,{children:Object.entries(e.vars||{}).map(e=>{let[t,n]=e;return t+"="+n}).join(", ")}),(0,a.jsxs)(P.Z,{align:"right",sx:{minWidth:150},children:[(0,a.jsx)(E.Z,{onClick:()=>{d(t),u(!0)},size:"small",children:(0,a.jsx)(k.Z,{})}),(0,a.jsx)(E.Z,{onClick:e=>x(e,t),size:"small",children:(0,a.jsx)(_.Z,{})}),(0,a.jsx)(E.Z,{onClick:e=>h(e,t),size:"small",children:(0,a.jsx)(C.Z,{})})]})]},t)})})]})}),(0,a.jsx)($,{open:p,onAdd:(e,t)=>{if(null===c)s([...r,e]);else{let t=r.map((t,n)=>n===c?e:t);s(t),d(null)}t&&u(!1)},varsList:t,initialValues:null!==c?r[c]:void 0,onCancel:()=>{d(null),u(!1)}})]})},ee=n(71911),et=n.n(ee),en=n(93522),ea=n(34235),ei=n(38640),er=n.n(ei),el=n(29270);n(54492),n(55096),n(93486);var es=()=>{let{env:e,setEnv:t,description:n,setDescription:r,providers:c,setProviders:d,prompts:p,setPrompts:u,testCases:h,setTestCases:x,defaultTest:m,setDefaultTest:g,evaluateOptions:j,setEvaluateOptions:v}=(0,l.o)(),[Z,b]=i.useState(""),[y,_]=i.useState(!0),C=e=>{t(e.env||{}),r(e.description||""),d(e.providers||[]),u(e.prompts||[]),x(e.tests||[]),g(e.defaultTest||{}),v(e.evaluateOptions||{})};return i.useEffect(()=>{b(ea.default.dump({env:e,description:n,providers:c,prompts:p,tests:h,defaultTest:m,evaluateOptions:j}))},[e,n,c,p,h,m,j]),(0,a.jsxs)(s.Z,{mt:4,children:[(0,a.jsx)(f.Z,{variant:"h5",gutterBottom:!0,children:"Configuration"}),(0,a.jsxs)(f.Z,{variant:"body1",gutterBottom:!0,children:["This is the YAML config that defines the evaluation and is processed by promptfoo. See"," ",(0,a.jsx)(er(),{target:"_blank",href:"https://promptfoo.dev/docs/configuration/guide",children:"configuration docs"})," ","to learn more."]}),(0,a.jsx)(o.Z,{variant:"text",color:"primary",startIcon:y?(0,a.jsx)(k.Z,{}):(0,a.jsx)(en.Z,{}),onClick:()=>{if(!y)try{let e=ea.default.load(Z,{json:!0});C(e)}catch(e){}_(!y)},children:y?"Edit YAML":"Save"}),(0,a.jsx)(et(),{autoCapitalize:"off",value:Z,onValueChange:e=>{y||b(e)},highlight:e=>(0,el.highlight)(e,el.languages.yaml),padding:10,style:{fontFamily:'"Fira code", "Fira Mono", monospace',fontSize:14},disabled:y,className:y?"":"glowing-border"})]})};n(7517);var eo=n(77580);function ec(e){let{error:t,resetErrorBoundary:n}=e;return(0,a.jsxs)("div",{role:"alert",children:[(0,a.jsx)("p",{children:"Something went wrong:"}),(0,a.jsx)("pre",{children:t.message}),(0,a.jsx)("button",{onClick:n,children:"Try again"})]})}var ed=()=>{let[e,t]=(0,i.useState)(!1),{description:n,setDescription:g,providers:j,setProviders:v,prompts:Z,setPrompts:b,testCases:_,setTestCases:C}=(0,l.o)();if((0,i.useEffect)(()=>{l.o.persist.rehydrate()},[]),eo.env.NEXT_PUBLIC_NO_BROWSING)return null;let k=(e=>{let t=/{{\s*(\w+)\s*}}/g,n=new Set;return e.forEach(e=>{let a;for(;null!==(a=t.exec(e));)n.add(a[1])}),Array.from(n)})(Z);return(0,a.jsxs)(c.Z,{maxWidth:"lg",sx:{marginTop:"2rem"},children:[(0,a.jsxs)(m.Z,{direction:"row",spacing:2,justifyContent:"space-between",children:[(0,a.jsx)(f.Z,{variant:"h4",children:"Set up an evaluation"}),(0,a.jsxs)(m.Z,{direction:"row",spacing:2,children:[(0,a.jsx)(Y,{}),(0,a.jsx)(y,{}),(0,a.jsx)(o.Z,{variant:"outlined",color:"primary",onClick:()=>t(!0),children:"Reset"})]})]}),(0,a.jsx)(s.Z,{mt:4}),(0,a.jsx)(s.Z,{mt:2,children:(0,a.jsx)(r.SV,{FallbackComponent:ec,onReset:()=>{v([])},children:(0,a.jsxs)(m.Z,{direction:"column",spacing:2,justifyContent:"space-between",children:[(0,a.jsx)(f.Z,{variant:"h5",children:"Providers"}),(0,a.jsx)(q,{providers:j,onChange:v})]})})}),(0,a.jsx)(s.Z,{mt:4}),(0,a.jsx)(r.SV,{FallbackComponent:ec,onReset:()=>{b([])},children:(0,a.jsx)(W,{})}),(0,a.jsx)(s.Z,{mt:6}),(0,a.jsx)(r.SV,{FallbackComponent:ec,onReset:()=>{C([])},children:(0,a.jsx)(Q,{varsList:k})}),(0,a.jsx)(es,{}),(0,a.jsxs)(d.Z,{open:e,onClose:()=>t(!1),"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[(0,a.jsx)(x.Z,{id:"alert-dialog-title",children:"Confirm Reset"}),(0,a.jsx)(u.Z,{children:(0,a.jsx)(h.Z,{id:"alert-dialog-description",children:"Are you sure you want to reset all the fields? This action cannot be undone."})}),(0,a.jsxs)(p.Z,{children:[(0,a.jsx)(o.Z,{onClick:()=>t(!1),children:"Cancel"}),(0,a.jsx)(o.Z,{onClick:()=>{g(""),v([]),b([]),C([]),t(!1)},autoFocus:!0,children:"Reset"})]})]})]})}},52428:function(e,t,n){"use strict";n.d(t,{Ox:function(){return r},T8:function(){return i},eA:function(){return l}});var a=n(77580);let i=!a.env.NEXT_PUBLIC_PROMPTFOO_BUILD_STANDALONE_SERVER,r=!!a.env.NEXT_PUBLIC_PROMPTFOO_USE_SUPABASE,l=""},47887:function(e,t,n){"use strict";n.d(t,{o:function(){return r}});var a=n(79685),i=n(74595);let r=(0,a.Ue)()((0,i.tJ)((e,t)=>({env:{},testCases:[],description:"",providers:[],prompts:[],defaultTest:{},evaluateOptions:{},setEnv:t=>e({env:t}),setTestCases:t=>e({testCases:t}),setDescription:t=>e({description:t}),setProviders:t=>e({providers:t}),setPrompts:t=>e({prompts:t}),setDefaultTest:t=>e({defaultTest:t}),setEvaluateOptions:t=>e({evaluateOptions:t}),setStateFromConfig:t=>{let n={};t.description&&(n.description=t.description||""),t.tests&&(n.testCases=t.tests),t.providers&&(n.providers=t.providers),t.prompts&&("string"==typeof t.prompts?n.prompts=[t.prompts]:Array.isArray(t.prompts)?n.prompts=t.prompts.filter(e=>"string"==typeof e&&!e.endsWith(".txt")&&!e.endsWith(".json")&&!e.endsWith(".yaml")):console.warn("Invalid prompts config",t.prompts)),t.defaultTest&&(n.defaultTest=t.defaultTest),t.evaluateOptions&&(n.evaluateOptions=t.evaluateOptions),e(n)},getTestSuite:()=>{let{description:e,testCases:n,providers:a,prompts:i,env:r}=t();return{env:r,description:e,providers:a,prompts:i,tests:n}}}),{name:"promptfoo",skipHydration:!0}))},94499:function(){},55096:function(){},7517:function(){},15320:function(e,t){"use strict";t.It=void 0,t.It=function(e){let t,n,a,i;let r={},l=[],s={};for(let[o,c]of Object.entries(e))o.startsWith("__expected")?""!==c.trim()&&l.push(function(e){if(e.startsWith("javascript:")||e.startsWith("fn:")||e.startsWith("eval:")){let t;e.startsWith("javascript:")&&(t=11),e.startsWith("fn:")&&(t=3),e.startsWith("eval:")&&(t=5);let n=e.slice(t).trim();return{type:"javascript",value:n}}if(e.startsWith("grade:")||e.startsWith("llm-rubric:"))return{type:"llm-rubric",value:e.slice(6)};if(e.startsWith("python:")){let t=e.slice(7).trim();return{type:"python",value:t}}let t=e.match(/^(not-)?(equals|contains-any|contains-all|icontains-any|icontains-all|contains-json|is-json|is-sql|regex|icontains|contains|webhook|rouge-n|similar|starts-with|levenshtein|classifier|model-graded-factuality|factuality|model-graded-closedqa|answer-relevance|context-recall|context-relevance|context-faithfulness|is-valid-openai-function-call|is-valid-openai-tools-call|latency|perplexity|perplexity-score|cost)(?:\((\d+(?:\.\d+)?)\))?(?::([\s\S]*))?$/);if(t){let[e,n,a,i,r]=t,l=n?`not-${a}`:a,s=parseFloat(i);return"contains-any"===a||"contains-all"===a||"icontains-any"===a||"icontains-all"===a?{type:l,value:r.split(",").map(e=>e.trim())}:"contains-json"===a||"is-json"===a?{type:l,value:r}:"rouge-n"===a||"similar"===a||"starts-with"===a||"levenshtein"===a||"classifier"===a||"answer-relevance"===a||"context-recall"===a||"context-relevance"===a||"context-faithfulness"===a||"latency"===a||"perplexity"===a||"perplexity-score"===a||"cost"===a?{type:l,value:r,threshold:s||("similar"===a?.8:.75)}:{type:l,value:r}}return{type:"equals",value:e}}(c)):"__prefix"===o?s.prefix=c:"__suffix"===o?s.suffix=c:"__description"===o?n=c:"__providerOutput"===o?t=c:"__metric"===o?a=c:"__threshold"===o?i=parseFloat(c):r[o]=c;for(let e of l)e.metric=a;return{vars:r,assert:l,options:s,...n?{description:n}:{},...t?{providerOutput:t}:{},...i?{threshold:i}:{}}}}},function(e){e.O(0,[540,640,215,620,770,304,339,995,378,374,235,873,106,258,470,730,744],function(){return e(e.s=72846)}),_N_E=e.O()}]);