@fudrouter/fsrouter 0.6.105 → 0.6.107

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 (49) hide show
  1. package/dist/lib/db/restoreRunner.js +136 -0
  2. package/dist/routes/db/raw/route.js +40 -0
  3. package/dist/routes/db/restore-path/route.js +28 -0
  4. package/dist/routes/db/route.js +4 -171
  5. package/package.json +1 -1
  6. package/public/.vite/manifest.json +86 -86
  7. package/public/assets/EndpointPageClient.Y4DlHkTu.js +6 -0
  8. package/public/assets/Loading.DFQ28pFE.js +1 -0
  9. package/public/assets/NoAuthProxyCard.CZTUlj4t.js +89 -0
  10. package/public/assets/index.AIBoioDI.js +89 -0
  11. package/public/assets/index.C--zNQ3O.css +1 -0
  12. package/public/assets/page.4cDBHbw-.js +6 -0
  13. package/public/assets/page.BKEq519M.js +4 -0
  14. package/public/assets/page.BP6GAYzJ.js +1 -0
  15. package/public/assets/page.BSn6cIN6.js +1 -0
  16. package/public/assets/page.BZ_cZfHH.js +1 -0
  17. package/public/assets/page.B_eGnZ87.js +1 -0
  18. package/public/assets/page.BeKSN8d5.js +1 -0
  19. package/public/assets/page.BrKiDQss.js +1 -0
  20. package/public/assets/page.C5AiGRKH.js +1 -0
  21. package/public/assets/page.C8zACKBM.js +1 -0
  22. package/public/assets/page.CJLP_zJ7.js +1 -0
  23. package/public/assets/page.CSrGxSfO.js +1 -0
  24. package/public/assets/page.CZDbQNsn.js +1 -0
  25. package/public/assets/page.CdAUv8An.js +2 -0
  26. package/public/assets/page.Ce-kykhG.js +1 -0
  27. package/public/assets/page.Cff3z2jC.js +1 -0
  28. package/public/assets/page.CinUcqhI.js +23 -0
  29. package/public/assets/page.Cl4BXH-q.js +6 -0
  30. package/public/assets/page.Cq_2LsWB.js +2 -0
  31. package/public/assets/page.CudzOdqp.js +1 -0
  32. package/public/assets/page.CyElgSss.js +5 -0
  33. package/public/assets/page.D9BzRCo6.js +1 -0
  34. package/public/assets/page.DCn1Ir9m.js +1 -0
  35. package/public/assets/page.DE5z4wT0.js +7 -0
  36. package/public/assets/page.DOB5QnMp.js +1 -0
  37. package/public/assets/page.DPthpQJn.js +1 -0
  38. package/public/assets/page.DReP7jhx.js +1 -0
  39. package/public/assets/page.Dd_cOSCu.js +1 -0
  40. package/public/assets/page.DsT3YjTA.js +31 -0
  41. package/public/assets/page.Dw5UwTfS.js +1 -0
  42. package/public/assets/page.F2ClRfJd.js +1 -0
  43. package/public/assets/page.NPv76Z9i.js +64 -0
  44. package/public/assets/page.SGPaUlyq.js +1 -0
  45. package/public/assets/page.hoGohFe7.js +1 -0
  46. package/public/assets/page.mbHhHec7.js +5 -0
  47. package/public/assets/page.q9OWaAVY.js +1 -0
  48. package/public/assets/page.zM1PvG2b.js +1 -0
  49. package/public/index.html +4 -4
@@ -0,0 +1 @@
1
+ import{j as e}from"./index.AIBoioDI.js";import{b as t,d as H}from"./router.Cjj1--8t.js";import"./zustand.akaTi5uX.js";function z(){const[x,N]=t.useState(""),[m,c]=t.useState(""),[W,b]=t.useState(""),[r,f]=t.useState(0),[g,w]=t.useState(!1),[y,u]=t.useState(null),[n,k]=t.useState("password"),[i,L]=t.useState(!1),[S,C]=t.useState("Sign in with OIDC"),[h,M]=t.useState(!1),l=H();t.useEffect(()=>{if(r<=0)return;const a=setInterval(()=>f(s=>s>0?s-1:0),1e3);return()=>clearInterval(a)},[r]),t.useEffect(()=>{async function a(){const s=new AbortController,o=setTimeout(()=>s.abort(),5e3),R=typeof window<"u"?window.location.origin:"";try{const v=await fetch(`${R}/api/auth/status`,{signal:s.signal});if(clearTimeout(o),v.ok){const d=await v.json(),j=new URLSearchParams(window.location.search),E=j.get("force")==="true"||j.get("force")==="1";if(d.requireLogin===!1&&!E){localStorage.setItem("9r_authed","1"),l("/dashboard"),l(0);return}u(!!d.hasPassword),k(d.authMode||"password"),L(d.oidcConfigured===!0),C(d.oidcLoginLabel||"Sign in with OIDC")}else u(!0)}catch{clearTimeout(o),u(!0)}}a()},[l]);const P=async a=>{a.preventDefault(),w(!0),c(""),b("");try{const s=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:x})});if(s.ok)localStorage.setItem("9r_authed","1"),l("/dashboard"),l(0);else{const o=await s.json();c(o.error||"Invalid password"),o.resetHint&&b(o.resetHint),o.retryAfter&&f(Number(o.retryAfter))}}catch{c("An error occurred. Please try again.")}finally{w(!1)}},I=()=>{window.location.href="/api/auth/oidc/start"},A=i&&["oidc","both"].includes(n),p=n!=="oidc"||!i,O=n==="oidc"&&!i||n==="both"&&!i,D=n==="both"&&i;return y===null?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-slate-400"})}):e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-slate-100 p-4",children:[e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute -top-40 -right-40 w-80 h-80 bg-violet-200/30 rounded-full blur-3xl"}),e.jsx("div",{className:"absolute -bottom-40 -left-40 w-80 h-80 bg-blue-200/30 rounded-full blur-3xl"})]}),e.jsxs("div",{className:"relative w-full max-w-sm",children:[e.jsxs("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-200/60 p-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-xl bg-gradient-to-br from-violet-500 to-blue-500 mb-4 shadow-lg shadow-violet-500/25",children:e.jsx("svg",{className:"w-6 h-6 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M13 10V3L4 14h7v7l9-11h-7z"})})}),e.jsx("h1",{className:"text-2xl font-bold text-slate-900 tracking-tight",children:"FSRouter"}),e.jsx("p",{className:"text-sm text-slate-500 mt-1",children:n==="oidc"&&i?"Sign in with your OIDC provider":"Enter your password to continue"})]}),O&&e.jsx("div",{className:"mb-4 p-3 rounded-lg bg-amber-50 border border-amber-200 text-xs text-amber-700",children:"OIDC not configured yet. Password login is available."}),D&&e.jsx("div",{className:"mb-4 p-3 rounded-lg bg-violet-50 border border-violet-200 text-xs text-violet-700 text-center",children:"Password and OIDC login are both enabled."}),p&&e.jsxs("form",{onSubmit:P,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-slate-600 block mb-1.5",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{name:"password",type:h?"text":"password",placeholder:"••••••••",value:x,onChange:a=>N(a.target.value),required:!0,autoFocus:!0,className:"w-full bg-slate-50 border border-slate-200 text-slate-900 text-sm p-3 pr-10 rounded-xl focus:outline-none focus:border-violet-400 focus:ring-2 focus:ring-violet-100 placeholder-slate-400 transition-all"}),e.jsx("button",{type:"button",onClick:()=>M(!h),className:"absolute inset-y-0 right-3 flex items-center text-slate-400 hover:text-slate-600",children:h?e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878l4.242 4.242M21 21l-3.122-3.122"})}):e.jsxs("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:[e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})]})})]}),m&&e.jsx("p",{className:"text-xs text-red-500 mt-1.5",children:m}),r>0&&e.jsxs("p",{className:"text-xs text-amber-600 mt-1.5",children:["Locked. Retry in ",r,"s."]})]}),e.jsx("button",{type:"submit",disabled:g||r>0,className:"w-full bg-gradient-to-r from-violet-500 to-blue-500 hover:from-violet-600 hover:to-blue-600 text-white font-medium text-sm py-3 rounded-xl transition-all shadow-lg shadow-violet-500/25 disabled:opacity-50 cursor-pointer",children:g?"Logging in...":r>0?`Wait ${r}s`:"Login"}),e.jsxs("p",{className:"text-center text-xs text-slate-400",children:["Default password is ",e.jsx("code",{className:"bg-slate-100 px-1.5 py-0.5 rounded text-slate-500 font-mono",children:"123456"})]})]}),A&&e.jsxs(e.Fragment,{children:[p&&e.jsxs("div",{className:"relative flex items-center justify-center py-4",children:[e.jsx("span",{className:"w-full border-t border-slate-200"}),e.jsx("span",{className:"px-3 text-xs text-slate-400 bg-white absolute",children:"or"})]}),e.jsxs("button",{onClick:I,type:"button",className:"w-full flex items-center justify-center gap-2 border border-slate-200 rounded-xl py-3 hover:bg-slate-50 transition-colors text-slate-600 text-sm cursor-pointer",children:[e.jsx("svg",{className:"w-4 h-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M15 3h4a2 2 0 012 2v14a2 2 0 01-2 2h-4M10 17l5-5-5-5M15 12H3"})}),S]})]})]}),e.jsx("p",{className:"text-center text-xs text-slate-400 mt-6",children:"Powered by FSRouter"})]})]})}export{z as default};
@@ -0,0 +1,64 @@
1
+ import{j as e,B as be,C as $t,g as Ae,M as gt,f as w,u as ve,i as Be,h as pe,N as bt,Q as yt,P as Pt,R as pt,S as Tt,V as _t}from"./index.AIBoioDI.js";import{b as s,h as Lt,d as It,L as Dt}from"./router.Cjj1--8t.js";import{C as we,T as Ue,E as Ut,B as Oe,S as Ot,N as Bt,A as Kt}from"./NoAuthProxyCard.CZTUlj4t.js";import"./zustand.akaTi5uX.js";const Ft={mode:{label:"Mode",format:t=>t},defaultModel:{label:"Model",format:t=>t,mono:!0},baseUrl:{label:"Endpoint",format:t=>t,isLink:!0,mono:!0},costPerQuery:{label:"Cost / call",format:t=>t===0?"Free":`$${t.toFixed(4)}`},pricingUrl:{label:"Pricing",format:()=>"View pricing",isLink:!0},freeTier:{label:"Free tier",format:t=>t},freeMonthlyQuota:{label:"Free quota",format:t=>t===0?"—":t>=999999?"Unlimited":`${t.toLocaleString()} / mo`},searchTypes:{label:"Types",format:t=>t.join(", ")},formats:{label:"Formats",format:t=>t.join(", ")},maxMaxResults:{label:"Max results",format:t=>t},maxCharacters:{label:"Max chars",format:t=>t.toLocaleString()}};function Vt({config:t,provider:r,title:i="Provider Info"}){var d,p;if(!t)return null;const S=Object.entries(Ft).filter(([h])=>t[h]!==void 0&&t[h]!==null&&t[h]!=="").map(([h,y])=>({key:h,label:y.label,value:y.format(t[h]),isLink:y.isLink,mono:y.mono,raw:t[h]})),c=((d=r==null?void 0:r.notice)==null?void 0:d.apiKeyUrl)||(r==null?void 0:r.website),M=(p=r==null?void 0:r.notice)==null?void 0:p.text;return e.jsxs(we,{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h2",{className:"text-lg font-semibold",children:i}),c&&e.jsxs("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline inline-flex items-center gap-1",children:[e.jsx("span",{className:"material-symbols-outlined text-sm",children:"open_in_new"}),"Get API Key"]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-2",children:[S.map(h=>e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:"text-xs text-text-muted w-28 shrink-0",children:h.label}),h.isLink?e.jsx("a",{href:h.raw,target:"_blank",rel:"noopener noreferrer",className:`text-sm text-primary hover:underline truncate ${h.mono?"font-mono":""}`,children:h.value}):e.jsx("span",{className:`text-sm text-text-main truncate ${h.mono?"font-mono":""}`,children:h.value})]},h.key)),M&&e.jsxs("div",{className:"flex items-start gap-3 min-w-0 sm:col-span-2",children:[e.jsx("span",{className:"text-xs text-text-muted w-28 shrink-0 mt-0.5",children:"Notice"}),e.jsx("span",{className:"text-sm text-text-main leading-relaxed",children:M})]})]})]})}function jt({until:t}){const[r,i]=s.useState("");return s.useEffect(()=>{const S=()=>{const M=new Date(t).getTime()-Date.now();if(M<=0){i("");return}const d=Math.floor(M/1e3);d<60?i(`${d}s`):d<3600?i(`${Math.floor(d/60)}m ${d%60}s`):i(`${Math.floor(d/3600)}h ${Math.floor(d%3600/60)}m`)};S();const c=setInterval(S,1e3);return()=>clearInterval(c)},[t]),r?e.jsxs("span",{className:"text-xs text-orange-500 font-mono",children:["⏱ ",r]}):null}jt.propTypes={until:w.string.isRequired};function vt({connection:t,proxyPools:r,isOAuth:i,isFirst:S,isLast:c,onMoveUp:M,onMoveDown:d,onToggleActive:p,onUpdateProxy:h,onEdit:y,onDelete:$}){var a,g,P,K,f,D;const[R,A]=s.useState(!1),[u,v]=s.useState(!1),[U,O]=s.useState(!1),L=s.useRef(null),I=new Map((r||[]).map(b=>[b.id,b])),j=((a=t.providerSpecificData)==null?void 0:a.proxyPoolId)||null,x=j?I.get(j):null,N=((g=t.providerSpecificData)==null?void 0:g.connectionProxyEnabled)===!0&&!!((P=t.providerSpecificData)!=null&&P.connectionProxyUrl),B=!!j||N,X=x?`Pool: ${x.name}`:j?`Pool: ${j} (inactive/missing)`:N?`Legacy: ${(K=t.providerSpecificData)==null?void 0:K.connectionProxyUrl}`:"";let Q="";const V=(x==null?void 0:x.proxyUrl)||((f=t.providerSpecificData)==null?void 0:f.connectionProxyUrl);if(V)try{const b=new URL(V);Q=`${b.protocol}//${b.hostname}${b.port?`:${b.port}`:""}`}catch{Q=V}const re=(x==null?void 0:x.noProxy)||((D=t.providerSpecificData)==null?void 0:D.connectionNoProxy)||"",ae=(x==null?void 0:x.isActive)===!0?"success":j||N?"error":"default",H=Object.entries(t).filter(([b])=>b.startsWith("modelLock_")).map(([,b])=>b).filter(Boolean).sort()[0]||null;s.useEffect(()=>{const b=()=>{const ne=Object.entries(t).filter(([G])=>G.startsWith("modelLock_")).map(([,G])=>G).filter(G=>G&&new Date(G).getTime()>Date.now()).sort()[0]||null;O(!!ne)};b();const Z=H?setInterval(b,1e3):null;return()=>{Z&&clearInterval(Z)}},[H]),s.useEffect(()=>{if(!R)return;const b=Z=>{L.current&&!L.current.contains(Z.target)&&A(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[R]);const W=t.testStatus==="unavailable"&&!U?"active":t.testStatus,le=()=>t.isActive===!1?"default":W==="active"||W==="success"?"success":W==="error"||W==="expired"||W==="unavailable"?"error":"default",m=i?t.name||t.email||t.displayName||"OAuth Account":t.name,o=async b=>{v(!0);try{await h(b==="__none__"?null:b)}finally{v(!1),A(!1)}};return e.jsxs("div",{className:`group flex flex-col gap-3 p-2 rounded-lg sm:flex-row sm:items-center sm:justify-between hover:bg-black/[0.02] dark:hover:bg-white/[0.02] transition-colors ${t.isActive===!1?"opacity-60":""}`,children:[e.jsxs("div",{className:"flex w-full min-w-0 flex-1 items-start gap-3 sm:items-center",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("button",{onClick:M,disabled:S,className:`p-0.5 rounded ${S?"text-text-muted/30 cursor-not-allowed":"hover:bg-sidebar text-text-muted hover:text-primary"}`,children:e.jsx("span",{className:"material-symbols-outlined text-sm",children:"keyboard_arrow_up"})}),e.jsx("button",{onClick:d,disabled:c,className:`p-0.5 rounded ${c?"text-text-muted/30 cursor-not-allowed":"hover:bg-sidebar text-text-muted hover:text-primary"}`,children:e.jsx("span",{className:"material-symbols-outlined text-sm",children:"keyboard_arrow_down"})})]}),e.jsx("span",{className:"material-symbols-outlined text-base text-text-muted",children:i?"lock":"key"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:m}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-1",children:[e.jsx(Oe,{variant:le(),size:"sm",dot:!0,children:t.isActive===!1?"disabled":W||"Unknown"}),B&&e.jsx(Oe,{variant:ae,size:"sm",children:"Proxy"}),U&&t.isActive!==!1&&e.jsx(jt,{until:H}),t.lastError&&t.isActive!==!1&&e.jsx("span",{className:"text-xs text-red-500 truncate max-w-[300px]",title:t.lastError,children:t.lastError}),e.jsxs("span",{className:"text-xs text-text-muted",children:["#",t.priority]})]}),B&&e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[11px] text-text-muted truncate max-w-[420px]",title:X,children:X}),Q&&e.jsx("code",{className:"text-[10px] font-mono bg-black/5 dark:bg-white/5 px-1 py-0.5 rounded text-text-muted",children:Q}),re&&e.jsxs("span",{className:"text-[11px] text-text-muted truncate max-w-[320px]",title:re,children:["no_proxy: ",re]})]})]})]}),e.jsxs("div",{className:"flex w-full flex-wrap items-center justify-between gap-2 sm:w-auto sm:justify-end",children:[e.jsxs("div",{className:"flex flex-wrap gap-1",children:[(r||[]).length>0&&e.jsxs("div",{className:"relative",ref:L,children:[e.jsxs("button",{onClick:()=>A(b=>!b),className:`flex flex-col items-center px-2 py-1 rounded hover:bg-black/5 dark:hover:bg-white/5 transition-colors ${B?"text-primary":"text-text-muted hover:text-primary"}`,disabled:u,children:[e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:u?"progress_activity":"lan"}),e.jsx("span",{className:"text-[10px] leading-tight",children:"Proxy"})]}),R&&e.jsxs("div",{className:"absolute right-0 top-full mt-1 z-50 bg-bg border border-border rounded-lg shadow-lg py-1 min-w-[160px]",children:[e.jsx("button",{onClick:()=>o("__none__"),className:`w-full text-left px-3 py-1.5 text-sm hover:bg-black/5 dark:hover:bg-white/5 ${j?"text-text-main":"text-primary font-medium"}`,children:"None"}),(r||[]).map(b=>e.jsx("button",{onClick:()=>o(b.id),className:`w-full text-left px-3 py-1.5 text-sm hover:bg-black/5 dark:hover:bg-white/5 ${j===b.id?"text-primary font-medium":"text-text-main"}`,children:b.name},b.id))]})]}),e.jsxs("button",{onClick:y,className:"flex flex-col items-center px-2 py-1 rounded hover:bg-black/5 dark:hover:bg-white/5 text-text-muted hover:text-primary",children:[e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"edit"}),e.jsx("span",{className:"text-[10px] leading-tight",children:"Edit"})]}),e.jsxs("button",{onClick:$,className:"flex flex-col items-center px-2 py-1 rounded hover:bg-red-500/10 text-red-500",children:[e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"delete"}),e.jsx("span",{className:"text-[10px] leading-tight",children:"Delete"})]})]}),e.jsx(Ue,{size:"sm",checked:t.isActive??!0,onChange:p,title:t.isActive??!0?"Disable":"Enable"})]})]})}vt.propTypes={connection:w.shape({id:w.string,name:w.string,email:w.string,displayName:w.string,testStatus:w.string,isActive:w.bool,lastError:w.string,priority:w.number}).isRequired,proxyPools:w.array,isOAuth:w.bool.isRequired,isFirst:w.bool.isRequired,isLast:w.bool.isRequired,onMoveUp:w.func.isRequired,onMoveDown:w.func.isRequired,onToggleActive:w.func.isRequired,onUpdateProxy:w.func,onEdit:w.func.isRequired,onDelete:w.func.isRequired};function wt({isOpen:t,provider:r,providerName:i,proxyPools:S,onSave:c,onClose:M}){var j;const d="__none__",[p,h]=s.useState({name:"",apiKey:"",priority:1,proxyPoolId:d,supportsImageRef:!0,supportsVideoRef:!0,supportsStartEndFrame:!0}),[y,$]=s.useState(!1),[R,A]=s.useState(null),[u,v]=s.useState(!1),U=Ae[r],O=((j=U==null?void 0:U.serviceKinds)==null?void 0:j.includes("video"))||r==="leonardo"||r==="runwayml",L=async()=>{$(!0);try{const N=await(await fetch("/api/providers/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:r,apiKey:p.apiKey})})).json();A(N.valid?"success":"failed")}catch{A("failed")}finally{$(!1)}},I=async()=>{if(!(!r||!p.apiKey)){v(!0);try{let x=!1;try{$(!0),A(null),x=!!(await(await fetch("/api/providers/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:r,apiKey:p.apiKey})})).json()).valid,A(x?"success":"failed")}catch{A("failed")}finally{$(!1)}await c({name:p.name,apiKey:p.apiKey,priority:p.priority,proxyPoolId:p.proxyPoolId===d?null:p.proxyPoolId,testStatus:x?"active":"unknown",providerSpecificData:{supportsImageRef:p.supportsImageRef,supportsVideoRef:p.supportsVideoRef,supportsStartEndFrame:p.supportsStartEndFrame}})}finally{v(!1)}}};return r?e.jsx(gt,{isOpen:t,title:`Add ${i||r} API Key`,onClose:M,children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-text-muted mb-1 block",children:"Name"}),e.jsx("input",{className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",value:p.name,onChange:x=>h({...p,name:x.target.value}),placeholder:"Production Key"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"text-xs text-text-muted mb-1 block",children:"API Key"}),e.jsx("input",{type:"password",className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",value:p.apiKey,onChange:x=>h({...p,apiKey:x.target.value})})]}),e.jsx("div",{className:"pt-6",children:e.jsx(be,{onClick:L,disabled:!p.apiKey||y||u,variant:"secondary",children:y?"Checking...":"Check"})})]}),R&&e.jsx(Oe,{variant:R==="success"?"success":"error",children:R==="success"?"Valid":"Invalid"}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-text-muted mb-1 block",children:"Priority"}),e.jsx("input",{type:"number",className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",value:p.priority,onChange:x=>h({...p,priority:Number.parseInt(x.target.value)||1})})]}),e.jsx(Ot,{label:"Proxy Pool",value:p.proxyPoolId,onChange:x=>h({...p,proxyPoolId:x.target.value}),options:[{value:d,label:"None"},...(S||[]).map(x=>({value:x.id,label:x.name}))]}),O&&e.jsxs("div",{className:"bg-sidebar/30 p-4 rounded-lg border border-accent/10 flex flex-col gap-3 my-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wider text-text-muted",children:"Capabilities"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Image Reference"}),e.jsx("p",{className:"text-xs text-text-muted",children:"Supports image URL inputs as prompts"})]}),e.jsx(Ue,{checked:p.supportsImageRef??!0,onChange:x=>h({...p,supportsImageRef:x})})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-accent/5 pt-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Video Reference"}),e.jsx("p",{className:"text-xs text-text-muted",children:"Supports video URL inputs as prompts"})]}),e.jsx(Ue,{checked:p.supportsVideoRef??!0,onChange:x=>h({...p,supportsVideoRef:x})})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-accent/5 pt-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Start/End Frame"}),e.jsx("p",{className:"text-xs text-text-muted",children:"Supports specifying start/end frames"})]}),e.jsx(Ue,{checked:p.supportsStartEndFrame??!0,onChange:x=>h({...p,supportsStartEndFrame:x})})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{onClick:I,fullWidth:!0,disabled:!p.name||!p.apiKey||u,children:u?"Saving...":"Save"}),e.jsx(be,{onClick:M,variant:"ghost",fullWidth:!0,children:"Cancel"})]})]})}):null}wt.propTypes={isOpen:w.bool.isRequired,provider:w.string,providerName:w.string,proxyPools:w.array,onSave:w.func.isRequired,onClose:w.func.isRequired};function Nt({providerId:t,isOAuth:r}){const[i,S]=s.useState([]),[c,M]=s.useState([]),[d,p]=s.useState(!0),[h,y]=s.useState(!1),[$,R]=s.useState(!1),[A,u]=s.useState(null),[v,U]=s.useState(null),[O,L]=s.useState("1"),[I,j]=s.useState(null),[x,N]=s.useState(!1),B=s.useCallback(async()=>{try{const[o,a,g]=await Promise.all([fetch("/api/providers",{cache:"no-store"}),fetch("/api/proxy-pools?isActive=true",{cache:"no-store"}),fetch("/api/settings",{cache:"no-store"})]),P=await o.json(),K=await a.json(),f=g.ok?await g.json():{};o.ok&&S((P.connections||[]).filter(b=>b.provider===t)),a.ok&&M(K.proxyPools||[]);const D=(f.providerStrategies||{})[t]||{};U(D.fallbackStrategy||null),L(D.stickyRoundRobinLimit!=null?String(D.stickyRoundRobinLimit):"1")}catch(o){console.log("ConnectionsCard fetch error:",o)}finally{p(!1)}},[t]);s.useEffect(()=>{B()},[B]);const X=async(o,a)=>{try{const g=await fetch("/api/settings",{cache:"no-store"}),K=(g.ok?await g.json():{}).providerStrategies||{},f={};o&&(f.fallbackStrategy=o),o==="round-robin"&&a!==""&&(f.stickyRoundRobinLimit=Number(a)||3);const D={...K};Object.keys(f).length===0?delete D[t]:D[t]=f,await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerStrategies:D})})}catch(g){console.log("saveStrategy error:",g)}},Q=async(o,a)=>{const g=[...i];[g[o],g[a]]=[g[a],g[o]],S(g);try{await Promise.all([fetch(`/api/providers/${g[o].id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({priority:o})}),fetch(`/api/providers/${g[a].id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({priority:a})})])}catch{await B()}},V=async o=>{j({title:"Delete Connection",message:"Delete this connection?",onConfirm:async()=>{j(null);try{(await fetch(`/api/providers/${o}`,{method:"DELETE"})).ok&&S(g=>g.filter(P=>P.id!==o))}catch(a){console.log("delete error:",a)}}})},re=async(o,a)=>{try{(await fetch(`/api/providers/${o}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isActive:a})})).ok&&S(P=>P.map(K=>K.id===o?{...K,isActive:a}:K))}catch(g){console.log("toggle error:",g)}},ae=async(o,a)=>{try{(await fetch(`/api/providers/${o}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({proxyPoolId:a||null})})).ok&&S(P=>P.map(K=>K.id===o?{...K,providerSpecificData:{...K.providerSpecificData,proxyPoolId:a||null}}:K))}catch(g){console.log("proxy error:",g)}},H=async()=>{if(i.length!==0){N(!0);try{await Promise.all(i.map(o=>fetch(`/api/providers/${o.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({testStatus:"active",lastError:"",lastErrorAt:null})}))),S(o=>o.map(a=>({...a,testStatus:"active",lastError:"",lastErrorAt:null})))}catch(o){console.log("reset all status error:",o)}finally{N(!1)}}},W=async o=>{try{(await fetch("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:t,...o})})).ok&&(await B(),y(!1))}catch(a){console.log("save apikey error:",a)}},le=async o=>{try{(await fetch(`/api/providers/${A.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).ok&&(await B(),R(!1))}catch(a){console.log("update connection error:",a)}};if(d)return e.jsx(we,{children:e.jsx("div",{className:"h-20 animate-pulse bg-black/5 rounded-lg"})});const m=i.some(o=>o.lastError||o.testStatus==="error");return e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between mb-4",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Connections"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.length>0&&e.jsxs("button",{onClick:H,disabled:x,title:"Reset testStatus and lastError for all connections",className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg border border-border text-xs text-text-muted hover:text-amber-500 hover:border-amber-500/40 hover:bg-amber-500/5 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:x?"progress_activity":"restart_alt"}),x?"Resetting...":"Reset All Status",m&&!x&&e.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 rounded-full bg-red-500/15 text-red-500 text-[10px] font-bold",children:"!"})]}),e.jsx("span",{className:"text-xs text-text-muted font-medium",children:"Round Robin"}),e.jsx(Ue,{checked:v==="round-robin",onChange:o=>{const a=o?"round-robin":null;U(a),o&&!O&&L("1"),X(a,o?O||"1":O)}}),v==="round-robin"&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-text-muted",children:"Sticky:"}),e.jsx("input",{type:"number",min:1,value:O,onChange:o=>{L(o.target.value),X("round-robin",o.target.value)},className:"w-16 px-2 py-1 text-xs border border-border rounded-md bg-background focus:outline-none focus:border-primary"})]})]})]}),i.length===0?e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("p",{className:"text-sm text-text-muted",children:"No connections yet"}),e.jsx(be,{size:"sm",icon:"add",onClick:()=>y(!0),children:"Add Connection"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-col divide-y divide-black/[0.03] dark:divide-white/[0.03]",children:i.map((o,a)=>e.jsx(vt,{connection:o,proxyPools:c,isOAuth:r,isFirst:a===0,isLast:a===i.length-1,onMoveUp:()=>Q(a,a-1),onMoveDown:()=>Q(a,a+1),onToggleActive:g=>re(o.id,g),onUpdateProxy:g=>ae(o.id,g),onEdit:()=>{u(o),R(!0)},onDelete:()=>V(o.id)},o.id))}),e.jsx("div",{className:"mt-4 flex justify-stretch sm:justify-start",children:e.jsx(be,{size:"sm",icon:"add",onClick:()=>y(!0),children:"Add"})})]})]}),e.jsx(wt,{isOpen:h,provider:t,proxyPools:c,onSave:W,onClose:()=>y(!1)}),e.jsx(Ut,{isOpen:$,connection:A,proxyPools:c,onSave:le,onClose:()=>R(!1)}),e.jsx($t,{isOpen:!!I,onClose:()=>j(null),onConfirm:I==null?void 0:I.onConfirm,title:(I==null?void 0:I.title)||"Confirm",message:I==null?void 0:I.message,variant:"danger"})]})}Nt.propTypes={providerId:w.string.isRequired,isOAuth:w.bool};function Xe({model:t,fullModel:r,copied:i,onCopy:S,testStatus:c,isCustom:M,isFree:d,onDeleteAlias:p,onTest:h,isTesting:y}){const $=c==="ok"?"border-green-500/40":c==="error"?"border-red-500/40":"border-border",R=c==="ok"?"#22c55e":c==="error"?"#ef4444":void 0;return e.jsx("div",{className:`group px-3 py-2 rounded-lg border ${$} hover:bg-sidebar/50`,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-base",style:R?{color:R}:void 0,children:c==="ok"?"check_circle":c==="error"?"cancel":"smart_toy"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("code",{className:"text-xs text-text-muted font-mono bg-sidebar px-1.5 py-0.5 rounded",children:r}),t.name&&e.jsx("span",{className:"text-[9px] text-text-muted/70 italic pl-1",children:t.name})]}),h&&e.jsxs("div",{className:"relative group/btn",children:[e.jsx("button",{onClick:h,disabled:y,className:`p-0.5 hover:bg-sidebar rounded text-text-muted hover:text-primary transition-opacity ${y?"opacity-100":"opacity-0 group-hover:opacity-100"}`,children:e.jsx("span",{className:"material-symbols-outlined text-sm",style:y?{animation:"spin 1s linear infinite"}:void 0,children:y?"progress_activity":"science"})}),e.jsx("span",{className:"pointer-events-none absolute mt-1 top-5 left-1/2 -translate-x-1/2 text-[10px] text-text-muted whitespace-nowrap opacity-0 group-hover/btn:opacity-100 transition-opacity",children:y?"Testing...":"Test"})]}),e.jsxs("div",{className:"relative group/btn",children:[e.jsx("button",{onClick:()=>S(r,`model-${t.id}`),className:"p-0.5 hover:bg-sidebar rounded text-text-muted hover:text-primary",children:e.jsx("span",{className:"material-symbols-outlined text-sm",children:i===`model-${t.id}`?"check":"content_copy"})}),e.jsx("span",{className:"pointer-events-none absolute mt-1 top-5 left-1/2 -translate-x-1/2 text-[10px] text-text-muted whitespace-nowrap opacity-0 group-hover/btn:opacity-100 transition-opacity",children:i===`model-${t.id}`?"Copied!":"Copy"})]}),d&&e.jsx("span",{className:"text-[10px] font-bold text-green-500 bg-green-500/10 px-1.5 py-0.5 rounded",children:"FREE"}),M&&e.jsx("button",{onClick:p,className:"p-0.5 hover:bg-red-500/10 rounded text-text-muted hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity ml-auto",title:"Remove custom model",children:e.jsx("span",{className:"material-symbols-outlined text-sm",children:"close"})})]})})}Xe.propTypes={model:w.shape({id:w.string.isRequired}).isRequired,fullModel:w.string.isRequired,copied:w.string,onCopy:w.func.isRequired,testStatus:w.oneOf(["ok","error"]),isCustom:w.bool,isFree:w.bool,onDeleteAlias:w.func,onTest:w.func,isTesting:w.bool};function kt({isOpen:t,onSave:r,onClose:i}){const[S,c]=s.useState(""),M=()=>{S.trim()&&(r(S.trim()),c(""))};return e.jsx(gt,{isOpen:t,title:"Add Custom Model",onClose:i,children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-text-muted mb-1 block",children:"Model ID"}),e.jsx("input",{className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",value:S,onChange:d=>c(d.target.value),onKeyDown:d=>d.key==="Enter"&&M(),placeholder:"e.g. tts-1-hd",autoFocus:!0})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{onClick:M,fullWidth:!0,disabled:!S.trim(),children:"Add"}),e.jsx(be,{onClick:i,variant:"ghost",fullWidth:!0,children:"Cancel"})]})]})})}kt.propTypes={isOpen:w.bool.isRequired,onSave:w.func.isRequired,onClose:w.func.isRequired};function St({providerId:t,kindFilter:r,providerAliasOverride:i}){const{copied:S,copy:c}=ve(),[M,d]=s.useState({}),[p,h]=s.useState([]),[y,$]=s.useState({}),[R,A]=s.useState(null),[u,v]=s.useState(""),[U,O]=s.useState(!1),[L,I]=s.useState([]),j=i||Be(t),x=r||"llm",N=s.useCallback(async()=>{try{const[m,o,a]=await Promise.all([fetch("/api/models/alias"),fetch("/api/providers",{cache:"no-store"}),fetch("/api/models/custom",{cache:"no-store"})]),g=await m.json(),P=await o.json(),K=await a.json();m.ok&&d(g.aliases||{}),o.ok&&I((P.connections||[]).filter(f=>f.provider===t)),a.ok&&h(K.models||[])}catch(m){console.log("ModelsCard fetch error:",m)}},[t]);s.useEffect(()=>{N()},[N]);const B=async(m,o)=>{const a=`${j}/${m}`;try{(await fetch("/api/models/alias",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:a,alias:o})})).ok&&await N()}catch(g){console.log("set alias error:",g)}},X=async m=>{try{(await fetch(`/api/models/alias?alias=${encodeURIComponent(m)}`,{method:"DELETE"})).ok&&await N()}catch(o){console.log("delete alias error:",o)}},Q=async m=>{try{(await fetch("/api/models/custom",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerAlias:j,id:m,type:x})})).ok&&(await N(),window.dispatchEvent(new CustomEvent("customModelChanged")))}catch(o){console.log("add custom model error:",o)}},V=async m=>{try{const o=new URLSearchParams({providerAlias:j,id:m,type:x});(await fetch(`/api/models/custom?${o}`,{method:"DELETE"})).ok&&(await N(),window.dispatchEvent(new CustomEvent("customModelChanged")))}catch(o){console.log("delete custom model error:",o)}},re=async m=>{if(!R){A(m);try{const a=await(await fetch("/api/models/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:`${j}/${m}`,kind:r})})).json();$(g=>({...g,[m]:a.ok?"ok":"error"})),v(a.ok?"":a.error||"Model not reachable")}catch{$(o=>({...o,[m]:"error"})),v("Network error")}finally{A(null)}}},ae=pe(t),H=r?ae.filter(m=>m.kinds?m.kinds.includes(r):(m.type||"llm")===r):ae,W=p.filter(m=>m.providerAlias===j&&(m.type||"llm")===x&&!H.some(o=>o.id===m.id)),le=H;return e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsx("div",{className:"flex items-center justify-between mb-4",children:e.jsxs("h2",{className:"text-lg font-semibold",children:["Models",r?` — ${r.toUpperCase()}`:""]})}),u&&e.jsx("p",{className:"text-xs text-red-500 mb-3 break-words",children:u}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[le.map(m=>{var g;const o=`${j}/${m.id}`,a=(g=Object.entries(M).find(([,P])=>P===o))==null?void 0:g[0];return e.jsx(Xe,{model:m,fullModel:`${j}/${m.id}`,alias:a,copied:S,onCopy:c,onSetAlias:P=>B(m.id,P),onDeleteAlias:()=>X(a),testStatus:y[m.id],onTest:L.length>0?()=>re(m.id):void 0,isTesting:R===m.id,isFree:m.isFree},m.id)}),W.map(m=>e.jsx(Xe,{model:{id:m.id,name:m.name},fullModel:`${j}/${m.id}`,copied:S,onCopy:c,onSetAlias:()=>{},onDeleteAlias:()=>V(m.id),testStatus:y[m.id],onTest:L.length>0?()=>re(m.id):void 0,isTesting:R===m.id,isCustom:!0},`${m.id}-${m.type}`)),e.jsxs("button",{onClick:()=>O(!0),className:"flex items-center gap-1.5 px-3 py-2 rounded-lg border border-dashed border-black/15 dark:border-white/15 text-xs text-text-muted hover:text-primary hover:border-primary/40 transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-sm",children:"add"}),"Add Model"]})]})]}),e.jsx(kt,{isOpen:U,onSave:async m=>{await Q(m),O(!1)},onClose:()=>O(!1)})]})}St.propTypes={providerId:w.string.isRequired,kindFilter:w.string,providerAliasOverride:w.string};const xt={"google-tts":{hasLanguageDropdown:!1,hasModelSelector:!1,hasBrowseButton:!0,voiceSource:"hardcoded"},openai:{hasLanguageDropdown:!1,hasModelSelector:!0,hasBrowseButton:!1,voiceSource:"hardcoded",modelKey:"openai-tts-models",voiceKey:"openai-tts-voices",voicesPerModel:!0},openrouter:{hasLanguageDropdown:!1,hasModelSelector:!0,hasBrowseButton:!1,voiceSource:"hardcoded",modelKey:"openrouter-tts-models",voiceKey:"openrouter-tts-voices",voicesPerModel:!0},elevenlabs:{hasLanguageDropdown:!1,hasModelSelector:!0,hasBrowseButton:!0,hasVoiceIdInput:!0,voiceSource:"api-language",modelKey:"elevenlabs-tts-models",apiEndpoint:"/api/media-providers/tts/elevenlabs/voices"},"edge-tts":{hasLanguageDropdown:!1,hasModelSelector:!1,hasBrowseButton:!0,voiceSource:"api-language"},"local-device":{hasLanguageDropdown:!1,hasModelSelector:!1,hasBrowseButton:!0,voiceSource:"api-language"},nvidia:{hasModelSelector:!0,hasBrowseButton:!1,hasVoiceIdInput:!0,voiceSource:"config"},hyperbolic:{hasModelSelector:!0,hasBrowseButton:!1,voiceSource:"config"},deepgram:{hasModelSelector:!1,hasBrowseButton:!0,voiceSource:"api-language",apiEndpoint:"/api/media-providers/tts/deepgram/voices"},huggingface:{hasModelSelector:!0,hasBrowseButton:!1,voiceSource:"config"},cartesia:{hasModelSelector:!0,hasBrowseButton:!1,hasVoiceIdInput:!0,voiceSource:"config"},playht:{hasModelSelector:!0,hasBrowseButton:!1,hasVoiceIdInput:!0,voiceSource:"config"},coqui:{hasModelSelector:!0,hasBrowseButton:!1,hasVoiceIdInput:!0,voiceSource:"config"},tortoise:{hasModelSelector:!0,hasBrowseButton:!1,hasVoiceIdInput:!0,voiceSource:"config"},inworld:{hasModelSelector:!0,hasBrowseButton:!0,hasVoiceIdInput:!0,voiceSource:"api-language",modelKey:"inworld-tts-models",apiEndpoint:"/api/media-providers/tts/inworld/voices"},qwen:{hasModelSelector:!0,hasBrowseButton:!1,hasVoiceIdInput:!0,voiceSource:"config"},minimax:{hasModelSelector:!0,hasBrowseButton:!0,hasVoiceIdInput:!0,voiceSource:"api-language",apiEndpoint:"/api/media-providers/tts/minimax/voices",defaultVoiceId:"English_expressive_narrator"},"minimax-cn":{hasModelSelector:!0,hasBrowseButton:!0,hasVoiceIdInput:!0,voiceSource:"api-language",apiEndpoint:"/api/media-providers/tts/minimax/voices?provider=minimax-cn",defaultVoiceId:"English_expressive_narrator"},gemini:{hasLanguageDropdown:!1,hasLanguageHint:!0,hasModelSelector:!0,hasBrowseButton:!1,voiceSource:"hardcoded",modelKey:"gemini-tts-models",voiceKey:"gemini-tts-voices",voicesPerModel:!0}};function _({label:t,children:r}){return e.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5 sm:flex-row sm:items-center sm:gap-3",children:[e.jsx("span",{className:"w-full text-xs font-medium text-text-muted sm:w-20 sm:shrink-0",children:t}),e.jsx("div",{className:"w-full min-w-0 flex-1",children:r})]})}const qt=`// Audio will appear here after running.
2
+ // Example JSON response (response_format=json):
3
+ {
4
+ "format": "mp3",
5
+ "audio": "//NExAANaAIIAUAAANNNNNNNN..." // base64 encoded MP3
6
+ }`,Jt=`{
7
+ "object": "list",
8
+ "data": [{
9
+ "object": "embedding",
10
+ "index": 0,
11
+ "embedding": [0.002301, -0.019212, 0.004815, -0.031249, ...]
12
+ }],
13
+ "model": "...",
14
+ "usage": { "prompt_tokens": 9, "total_tokens": 9 }
15
+ }`,ft="https://pub-1fb693cb11cc46b2b2f656f51e015a2c.r2.dev/dog.png",zt="https://pub-1fb693cb11cc46b2b2f656f51e015a2c.r2.dev/dog-mask.png";function Ht(t,r){return t!=="cloudflare-ai"?{}:r==="@cf/runwayml/stable-diffusion-v1-5-img2img"?{image:ft}:r==="@cf/runwayml/stable-diffusion-v1-5-inpainting"?{image:ft,mask_image:zt}:{}}function ht(t){const r=typeof t=="string"?t.trim():"";return r?/^(data:image\/|https?:\/\/)/i.test(r)?r:`data:image/png;base64,${r}`:""}const Ct={webSearch:{inputLabel:"Query",inputPlaceholder:"What is the latest news about AI?",defaultInput:"What is the latest news about AI?",bodyKey:"query",defaultResponse:`{
16
+ "results": [
17
+ { "title": "...", "url": "...", "snippet": "..." }
18
+ ]
19
+ }`,extraFields:[{key:"search_type",label:"Type",type:"select",default:"web",options:["web","news"]},{key:"max_results",label:"Max results",type:"number",default:5,min:1,max:100},{key:"country",label:"Country",type:"text",default:""},{key:"language",label:"Language",type:"text",default:""}]},webFetch:{inputLabel:"URL",inputPlaceholder:"https://example.com",defaultInput:"https://example.com",bodyKey:"url",defaultResponse:`{
20
+ "content": "...",
21
+ "title": "...",
22
+ "url": "..."
23
+ }`,extraFields:[{key:"format",label:"Format",type:"select",default:"markdown",options:["markdown","text","html"]},{key:"max_characters",label:"Max chars",type:"number",default:0,min:0}]},image:{inputLabel:"Prompt",inputPlaceholder:"A cute cat wearing a hat",defaultInput:"A cute cat wearing a hat",bodyKey:"prompt",defaultResponse:`{
24
+ "data": [
25
+ { "url": "...", "b64_json": "..." }
26
+ ]
27
+ }`,extraFields:[{key:"n",label:"n",type:"number",default:1,min:1,max:4},{key:"size",label:"Size",type:"select",default:"auto",options:["auto","1024x1024","1024x1536","1536x1024","1024x1792","1792x1024"]},{key:"quality",label:"Quality",type:"select",default:"auto",options:["auto","low","medium","high","standard","hd"]},{key:"background",label:"Background",type:"select",default:"auto",options:["auto","transparent","opaque"]},{key:"style",label:"Style",type:"select",default:"",options:["","vivid","natural"]},{key:"response_format",label:"Format",type:"select",default:"",options:["","url","b64_json"]},{key:"image_detail",label:"Image Detail",type:"select",default:"high",options:["auto","low","high","original"]},{key:"output_format",label:"Codec",type:"select",default:"png",options:["png","jpeg","webp"]}]},imageToText:{inputLabel:"Image URL",inputPlaceholder:"https://example.com/image.png",defaultInput:"https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg",bodyKey:"url",extraBody:{prompt:"Describe this image in detail"},defaultResponse:`{
28
+ "text": "A cat sitting on a windowsill...",
29
+ "model": "..."
30
+ }`},video:{inputLabel:"Prompt",inputPlaceholder:"A serene lake at sunset",defaultInput:"A serene lake at sunset",bodyKey:"prompt",defaultResponse:`{
31
+ "data": [
32
+ { "url": "..." }
33
+ ]
34
+ }`,extraFields:[{key:"duration",label:"Duration (seconds)",type:"number",default:5,min:1,max:10},{key:"resolution",label:"Resolution",type:"select",default:"720",options:["480","720","1080"]},{key:"aspect_ratio",label:"Aspect Ratio",type:"select",default:"16:9",options:["16:9","9:16","1:1"]},{key:"image_url",label:"Image Reference (URL)",type:"text",default:"",placeholder:"https://example.com/image.png"},{key:"video_url",label:"Video Reference (URL)",type:"text",default:"",placeholder:"https://example.com/video.mp4"},{key:"motion_strength",label:"Motion Strength",type:"number",default:5,min:1,max:10}]},music:{inputLabel:"Prompt",inputPlaceholder:"A calm piano melody",defaultInput:"A calm piano melody",bodyKey:"prompt",defaultResponse:`{
35
+ "data": [
36
+ { "url": "...", "format": "mp3" }
37
+ ]
38
+ }`}};function Wt({providerId:t,customAlias:r}){var K;const i=yt(t),S=i?r||t:Be(t),c=i?[]:pe(t).filter(f=>f.type==="embedding"),[M,d]=s.useState(((K=c[0])==null?void 0:K.id)??""),[p,h]=s.useState("The quick brown fox jumps over the lazy dog"),[y,$]=s.useState(""),[R,A]=s.useState(""),[u,v]=s.useState(!1),[U,O]=s.useState(""),[L,I]=s.useState(""),[j,x]=s.useState(null),[N,B]=s.useState(!1),[X,Q]=s.useState(""),{copied:V,copy:re}=ve(),{copied:ae,copy:H}=ve();s.useEffect(()=>{O(window.location.origin),fetch("/api/keys").then(f=>f.json()).then(f=>{var D;A(((D=(f.keys||[]).find(b=>b.isActive!==!1))==null?void 0:D.key)||"")}).catch(()=>{}),fetch("/api/tunnel/status").then(f=>f.json()).then(f=>{f.publicUrl&&I(f.publicUrl)}).catch(()=>{})},[]);const W=u?L:U,le=M?`${S}/${M}`:"",m=()=>{const f={model:le,input:p.trim()},D=Number(y);return y&&Number.isFinite(D)&&D>0&&(f.dimensions=D),f},o=`curl -X POST ${W}/v1/embeddings \\
39
+ -H "Content-Type: application/json" \\
40
+ -H "Authorization: Bearer ${R||"YOUR_KEY"}" \\
41
+ -d '${JSON.stringify(m())}'`,a=async()=>{var D;if(!p.trim()||!le)return;B(!0),Q(""),x(null);const f=Date.now();try{const b={"Content-Type":"application/json"};R&&(b.Authorization=`Bearer ${R}`);const Z=await fetch("/api/v1/embeddings",{method:"POST",headers:b,body:JSON.stringify(m())}),ne=Date.now()-f,G=await Z.json();if(!Z.ok){Q(((D=G==null?void 0:G.error)==null?void 0:D.message)||(G==null?void 0:G.error)||`HTTP ${Z.status}`);return}x({data:G,latencyMs:ne})}catch(b){Q(b.message||"Network error")}finally{B(!1)}},g=f=>{if(!f)return Jt;const D=JSON.parse(JSON.stringify(f));return(D.data||[]).forEach(b=>{Array.isArray(b.embedding)&&b.embedding.length>4&&(b.embedding=[...b.embedding.slice(0,4).map(Z=>parseFloat(Z.toFixed(6))),`... (${b.embedding.length} dims)`])}),JSON.stringify(D,null,2)},P=j?JSON.stringify(j.data,null,2):"";return e.jsxs(we,{children:[e.jsx("h2",{className:"text-lg font-semibold mb-4",children:"Example"}),e.jsxs("div",{className:"flex flex-col gap-2.5",children:[e.jsx(_,{label:"Model",children:i?e.jsx("input",{value:M,onChange:f=>d(f.target.value),placeholder:"e.g. voyage-3, embed-english-v3.0, text-embedding-3-small",className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary font-mono"}):e.jsx("select",{value:M,onChange:f=>d(f.target.value),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:c.map(f=>e.jsx("option",{value:f.id,children:f.name||f.id},f.id))})}),e.jsx(_,{label:"Endpoint",children:e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsx("input",{value:W,onChange:f=>u?I(f.target.value):O(f.target.value),className:"w-full min-w-0 flex-1 px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary font-mono",placeholder:"http://localhost:3000"}),L&&e.jsxs("button",{onClick:()=>v(f=>!f),title:u?"Using tunnel":"Using local",className:`flex items-center gap-1 text-xs px-2 py-1.5 rounded-lg border shrink-0 transition-colors ${u?"border-primary/40 bg-primary/10 text-primary":"border-border text-text-muted hover:text-primary"}`,children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"wifi_tethering"}),"Tunnel"]})]})}),e.jsx(_,{label:"API Key",children:e.jsx("input",{type:"password",value:R,onChange:f=>A(f.target.value),placeholder:"sk-...",className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary font-mono"})}),e.jsx(_,{label:"Input",children:e.jsxs("div",{className:"relative",children:[e.jsx("input",{value:p,onChange:f=>h(f.target.value),className:"w-full px-3 py-1.5 pr-7 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"}),p&&e.jsx("button",{type:"button",onClick:()=>h(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-text-muted hover:text-primary transition-colors",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"close"})})]})}),e.jsx(_,{label:"Dimensions",children:e.jsx("input",{type:"number",min:"1",value:y,onChange:f=>$(f.target.value),placeholder:"optional, e.g. 512, 1024 (leave empty for default)",className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})}),e.jsxs("div",{className:"mt-1",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-1.5",children:[e.jsx("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:"Request"}),e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsxs("button",{onClick:()=>re(o),className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:V?"check":"content_copy"}),V?"Copied":"Copy"]}),e.jsxs("button",{onClick:a,disabled:N||!p.trim()||!le,className:"flex w-full sm:w-auto items-center justify-center gap-1.5 px-3 py-1 rounded-lg bg-primary text-white text-xs font-medium hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",style:N?{animation:"spin 1s linear infinite"}:void 0,children:"play_arrow"}),N?"Running...":"Run"]})]})]}),e.jsx("pre",{className:"bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre-wrap break-all",children:o})]}),X&&e.jsx("p",{className:"text-xs text-red-500 break-words",children:X}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-1.5",children:[e.jsxs("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:["Response ",j&&e.jsxs("span",{className:"font-normal normal-case",children:["⚡ ",j.latencyMs,"ms"]})]}),j&&e.jsxs("button",{onClick:()=>H(P),className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:ae?"check":"content_copy"}),ae?"Copied":"Copy"]})]}),e.jsx("pre",{className:"bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre-wrap break-all opacity-70",children:g(j==null?void 0:j.data)})]})]})]})}function Gt({providerId:t}){var Te,Fe,_e,Ce,Ee,Le,Ve;const r=Be(t),i=xt[t]||xt["edge-tts"],[S,c]=s.useState(i.defaultVoiceId||""),[M,d]=s.useState(""),[p,h]=s.useState(i.defaultVoiceId||""),[y,$]=s.useState([]),[R,A]=s.useState(""),[u,v]=s.useState(()=>{var Y,E,F;const n=(E=(Y=Ae[t])==null?void 0:Y.ttsConfig)==null?void 0:E.models;if(n!=null&&n.length)return n[0].id;if(i.hasModelSelector&&i.modelKey){const z=pe(i.modelKey);return((F=z==null?void 0:z[0])==null?void 0:F.id)||""}return""}),[U,O]=s.useState("Hello, this is a text to speech test."),[L,I]=s.useState(""),[j,x]=s.useState(!1),[N,B]=s.useState(""),[X,Q]=s.useState(""),[V,re]=s.useState("mp3"),[ae,H]=s.useState(""),[W,le]=s.useState(null),[m,o]=s.useState(!1),[a,g]=s.useState(""),[P,K]=s.useState(null),{copied:f,copy:D}=ve(),[b,Z]=s.useState(!1),[ne,G]=s.useState([]),[ue,ye]=s.useState(!1),[xe,C]=s.useState(""),[J,ee]=s.useState(""),[ce,fe]=s.useState({}),[Ne,de]=s.useState("");s.useEffect(()=>{var n,Y;if(B(window.location.origin),fetch("/api/keys").then(E=>E.json()).then(E=>{var F;I(((F=(E.keys||[]).find(z=>z.isActive!==!1))==null?void 0:F.key)||"")}).catch(()=>{}),fetch("/api/tunnel/status").then(E=>E.json()).then(E=>{E.publicUrl&&Q(E.publicUrl)}).catch(()=>{}),i.voiceSource==="hardcoded"){const E=i.hasModelSelector&&i.modelKey&&((Y=(n=pe(i.modelKey))==null?void 0:n[0])==null?void 0:Y.id)||"",F=i.voicesPerModel&&E?pt(t,E)||[]:pe(i.voiceKey||t).filter(z=>z.type==="tts");if(F.length)if(i.hasBrowseButton){const z=F.find(ie=>ie.id==="en")||F[0];A(z.id),c(z.id),d(z.name),$([{id:z.id,name:z.name}])}else $(F),c(F[0].id),d(F[0].name||F[0].id)}},[t]),s.useEffect(()=>{if(!i.voicesPerModel||!u)return;const n=pt(t,u)||[];$(n),n.length&&(c(n[0].id),d(n[0].name||n[0].id))},[u]);const Me=async()=>{if(Z(!0),C(""),ee(""),!ne.length){ye(!0);try{if(i.voiceSource==="hardcoded"){const n=i.voiceKey||t,Y=pe(n).filter(F=>F.type==="tts"),E={};for(const F of Y)E[F.id]||(E[F.id]={code:F.id,name:F.name,voices:[{id:F.id,name:F.name}]});fe(E),G(Object.values(E).sort((F,z)=>F.name.localeCompare(z.name)))}else{const n=i.apiEndpoint?i.apiEndpoint:`/api/media-providers/tts/voices?provider=${t==="local-device"?"local-device":"edge-tts"}`,E=await(await fetch(n)).json();if(E.error){ee(E.error);return}G(E.languages||[]),fe(E.byLang||{})}}catch(n){ee(n.message)}finally{ye(!1)}}},ze=n=>{var E;Z(!1),A(n.code);const Y=((E=ce[n.code])==null?void 0:E.voices)||[];$(Y),Y.length&&(c(Y[0].id),d(Y[0].name),i.hasVoiceIdInput&&h(Y[0].id))},$e=xe?ne.filter(n=>n.name.toLowerCase().includes(xe.toLowerCase())||n.code.toLowerCase().includes(xe.toLowerCase())):ne,Pe=j?X:N,ge=i.hasVoiceIdInput&&p||S,je=i.hasModelSelector&&u&&ge?`${r}/${u}/${ge}`:i.hasModelSelector&&u?`${r}/${u}`:ge?`${r}/${ge}`:"",ke=(()=>{const n={model:je,input:U};return i.hasLanguageHint&&Ne&&(n.language=Ne),n})(),Se=`curl -X POST ${Pe}/v1/audio/speech${V==="json"?"?response_format=json":""} \\
42
+ -H "Content-Type: application/json" \\
43
+ -H "Authorization: Bearer ${L||"YOUR_KEY"}" \\
44
+ -d '${JSON.stringify(ke)}' \\
45
+ ${V==="json"?"":"--output speech.mp3"}`,Ke=async()=>{var Y;if(!U.trim()||!je)return;o(!0),g(""),H(""),le(null);const n=Date.now();try{const E={"Content-Type":"application/json"};L&&(E.Authorization=`Bearer ${L}`);const z=await fetch(`/api/v1/audio/speech${V==="json"?"?response_format=json":""}`,{method:"POST",headers:E,body:JSON.stringify({...ke,input:U.trim()})});if(K(Date.now()-n),!z.ok){const ie=await z.json().catch(()=>({}));g(((Y=ie==null?void 0:ie.error)==null?void 0:Y.message)||(ie==null?void 0:ie.error)||`HTTP ${z.status}`);return}if(V==="json"){const ie=await z.json();le(ie);const qe=await fetch(`data:audio/mp3;base64,${ie.audio}`).then(Je=>Je.blob());H(URL.createObjectURL(qe))}else{const ie=await z.blob();H(URL.createObjectURL(ie))}}catch(E){g(E.message||"Network error")}finally{o(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsx("h2",{className:"text-lg font-semibold mb-4",children:"Example"}),e.jsxs("div",{className:"flex flex-col gap-2.5",children:[e.jsx(_,{label:"Endpoint",children:e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsxs("span",{className:"w-full min-w-0 flex-1 px-3 py-1.5 text-sm font-mono text-text-main bg-sidebar rounded-lg truncate",children:[Pe,"/v1/audio/speech"]}),X&&e.jsxs("button",{onClick:()=>x(n=>!n),title:j?"Using tunnel":"Using local",className:`flex items-center gap-1 text-xs px-2 py-1.5 rounded-lg border shrink-0 transition-colors ${j?"border-primary/40 bg-primary/10 text-primary":"border-border text-text-muted hover:text-primary"}`,children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"wifi_tethering"}),"Tunnel"]})]})}),e.jsx(_,{label:"API Key",children:e.jsx("span",{className:"px-3 py-1.5 text-sm font-mono text-text-main bg-sidebar rounded-lg truncate block",children:L?`${L.slice(0,8)}${"•".repeat(Math.min(20,L.length-8))}`:e.jsx("span",{className:"text-text-muted italic",children:"No key configured"})})}),i.hasModelSelector&&(i.modelKey||((_e=(Fe=(Te=Ae[t])==null?void 0:Te.ttsConfig)==null?void 0:Fe.models)==null?void 0:_e.length))&&e.jsx(_,{label:"Model",children:e.jsx("select",{value:u,onChange:n=>v(n.target.value),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:(((Le=(Ee=(Ce=Ae[t])==null?void 0:Ce.ttsConfig)==null?void 0:Ee.models)!=null&&Le.length?Ae[t].ttsConfig.models:pe(i.modelKey))||[]).map(n=>e.jsx("option",{value:n.id,children:n.name||n.id},n.id))})}),i.hasLanguageHint&&e.jsx(_,{label:"Language",children:e.jsxs("select",{value:Ne,onChange:n=>de(n.target.value),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[e.jsx("option",{value:"",children:"Auto-detect"}),Tt.map(n=>e.jsx("option",{value:n.name,children:n.name},n.id))]})}),i.hasBrowseButton&&e.jsx(_,{label:"Language",children:e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsx("button",{onClick:Me,className:"w-full min-w-0 flex-1 px-3 py-1.5 text-sm border border-border rounded-lg bg-background font-mono truncate text-left hover:border-primary/40 transition-colors",children:R?e.jsx("span",{className:"text-text-main",children:((Ve=ne.find(n=>n.code===R))==null?void 0:Ve.name)||R}):e.jsx("span",{className:"text-text-muted",children:"No language selected"})}),e.jsxs("button",{onClick:Me,className:"flex w-full items-center justify-center gap-1 text-xs px-2.5 py-1.5 rounded-lg border border-border text-text-muted hover:text-primary hover:border-primary/40 transition-colors sm:w-auto sm:shrink-0",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"language"}),"Select language"]})]})}),y.length>0&&e.jsx(_,{label:"Voice",children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:y.map(n=>e.jsxs("button",{onClick:()=>{c(n.id),d(n.name),i.hasVoiceIdInput&&h(n.id)},className:`px-2.5 py-1 rounded-full text-xs border transition-colors ${S===n.id?"bg-primary/15 border-primary/40 text-primary font-medium":"border-border text-text-muted hover:text-primary hover:border-primary/40"}`,children:[n.name,n.gender?` · ${n.gender[0].toUpperCase()}`:"",n.free_users_allowed===!0&&e.jsx("span",{className:"ml-1.5 px-1 py-0.5 text-[9px] font-semibold rounded bg-green-500/15 text-green-600 border border-green-500/20",children:"Free"}),n.free_users_allowed===!1&&e.jsx("span",{className:"ml-1.5 px-1 py-0.5 text-[9px] font-semibold rounded bg-amber-500/15 text-amber-600 border border-amber-500/20",children:"Paid"})]},n.id))})}),i.hasVoiceIdInput&&e.jsx(_,{label:"Voice ID",children:e.jsx("div",{className:"flex flex-col gap-1",children:e.jsxs("div",{className:"relative",children:[e.jsx("input",{value:p,onChange:n=>{h(n.target.value),c(n.target.value)},placeholder:"e.g. CwhRBWXzGAHq8TQ4Fs17",className:"w-full px-3 py-1.5 pr-7 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary font-mono"}),p&&e.jsx("button",{type:"button",onClick:()=>{h(""),c("")},className:"absolute right-2 top-1/2 -translate-y-1/2 text-text-muted hover:text-primary transition-colors",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"close"})})]})})}),i.hasLanguageDropdown&&e.jsx(_,{label:"Language",children:e.jsx("select",{value:S,onChange:n=>{const Y=pe(t).filter(E=>E.type==="tts").find(E=>E.id===n.target.value);c(n.target.value),d((Y==null?void 0:Y.name)||n.target.value)},className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:pe(t).filter(n=>n.type==="tts").map(n=>e.jsx("option",{value:n.id,children:n.name||n.id},n.id))})}),e.jsx(_,{label:"Input",children:e.jsxs("div",{className:"relative",children:[e.jsx("input",{value:U,onChange:n=>O(n.target.value),className:"w-full px-3 py-1.5 pr-7 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"}),U&&e.jsx("button",{type:"button",onClick:()=>O(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-text-muted hover:text-primary transition-colors",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"close"})})]})}),e.jsx(_,{label:"Output Format",children:e.jsxs("select",{value:V,onChange:n=>re(n.target.value),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[e.jsx("option",{value:"mp3",children:"MP3 (Binary)"}),e.jsx("option",{value:"json",children:"JSON (Base64)"})]})}),e.jsxs("div",{className:"mt-1",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-1.5",children:[e.jsx("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:"Request"}),e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsxs("button",{onClick:()=>D(Se),className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:f?"check":"content_copy"}),f?"Copied":"Copy"]}),e.jsxs("button",{onClick:Ke,disabled:m||!U.trim()||!je,className:"flex w-full sm:w-auto items-center justify-center gap-1.5 px-3 py-1 rounded-lg bg-primary text-white text-xs font-medium hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",style:m?{animation:"spin 1s linear infinite"}:void 0,children:"play_arrow"}),m?"Generating...":"Run"]})]})]}),e.jsx("pre",{className:"bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre-wrap break-all",children:Se})]}),a&&e.jsx("p",{className:"text-xs text-red-500 break-words",children:a}),ae?e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-1.5",children:[e.jsxs("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:["Response ",P&&e.jsxs("span",{className:"font-normal normal-case",children:["⚡ ",P,"ms"]})]}),e.jsxs("a",{href:ae,download:"speech.mp3",className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"download"}),"Download"]})]}),e.jsx("audio",{controls:!0,src:ae,className:"w-full"}),W&&e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-1.5",children:e.jsx("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:"JSON Response"})}),e.jsx("pre",{className:"bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre-wrap break-all",children:JSON.stringify({format:W.format,audio:W.audio?`${W.audio.substring(0,100)}...`:""},null,2)})]})]}):e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:"Response"}),e.jsx("pre",{className:"mt-1.5 bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre-wrap break-all opacity-50",children:qt})]})]})]}),b&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center sm:items-center",style:{backgroundColor:"rgba(0,0,0,0.6)",backdropFilter:"blur(2px)"},onClick:()=>Z(!1),children:e.jsxs("div",{className:"border border-border rounded-xl shadow-2xl w-full max-w-md mx-4 flex flex-col max-h-[80vh]",style:{backgroundColor:"var(--color-bg)",isolation:"isolate"},onClick:n=>n.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border shrink-0 rounded-t-xl",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Select Language"}),e.jsx("button",{onClick:()=>Z(!1),className:"text-text-muted hover:text-primary transition-colors",children:e.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"close"})})]}),e.jsx("div",{className:"px-4 py-2.5 border-b border-border shrink-0",children:e.jsx("input",{autoFocus:!0,value:xe,onChange:n=>C(n.target.value),placeholder:"Search language...",className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})}),e.jsxs("div",{className:"overflow-y-auto flex-1 p-2",children:[J&&e.jsx("p",{className:"text-xs text-red-500 px-2 py-1",children:J}),ue?e.jsx("p",{className:"text-xs text-text-muted px-2 py-3",children:"Loading..."}):e.jsxs("div",{className:"flex flex-col gap-0.5",children:[$e.map(n=>e.jsxs("button",{onClick:()=>ze(n),className:`flex items-center justify-between w-full px-3 py-2 rounded-lg text-left hover:bg-sidebar transition-colors ${R===n.code?"bg-primary/10 text-primary":""}`,children:[e.jsx("span",{className:"text-sm",children:n.name}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("span",{className:"text-xs text-text-muted",children:[n.voices.length," voices"]}),R===n.code&&e.jsx("span",{className:"material-symbols-outlined text-[16px] text-primary",children:"check"})]})]},n.code)),$e.length===0&&e.jsx("p",{className:"text-xs text-text-muted px-2 py-3",children:"No languages found."})]})]})]})})]})}function Yt({providerId:t,kind:r}){var z,ie,qe,Je,Qe,Ze,et,tt,st,at,nt,ot,rt,lt,it,ct,dt,ut,mt;const i=Be(t),c=_t(i)===t?i:t,M=bt.find(l=>l.id===r),d=Ct[r],p=d||{},h=pe(t).filter(l=>l.type===r),$=new Set(["image","video","music","imageToText"]).has(r),R=$&&h.length===0,[A,u]=s.useState(((z=h[0])==null?void 0:z.id)??""),v=h.find(l=>l.id===A),U=!!((ie=v==null?void 0:v.capabilities)!=null&&ie.includes("edit")),O=!!((qe=v==null?void 0:v.capabilities)!=null&&qe.includes("mask")),[L,I]=s.useState(p.defaultInput||""),[j,x]=s.useState(""),[N,B]=s.useState(""),[X,Q]=s.useState(()=>(p.extraFields||[]).reduce((l,k)=>(l[k.key]=k.default??"",l),{})),[V,re]=s.useState(""),[ae,H]=s.useState(!1),[W,le]=s.useState(""),[m,o]=s.useState(""),[a,g]=s.useState(null),[P,K]=s.useState(null),[f,D]=s.useState(null),[b,Z]=s.useState("json"),[ne,G]=s.useState(""),[ue,ye]=s.useState(!1),[xe,C]=s.useState(""),[J,ee]=s.useState([]),[ce,fe]=s.useState(""),{copied:Ne,copy:de}=ve(),{copied:Me,copy:ze}=ve();if(s.useEffect(()=>{le(window.location.origin),fetch("/api/keys").then(l=>l.json()).then(l=>{var k;re(((k=(l.keys||[]).find(T=>T.isActive!==!1))==null?void 0:k.key)||"")}).catch(()=>{}),fetch("/api/tunnel/status").then(l=>l.json()).then(l=>{l.publicUrl&&o(l.publicUrl)}).catch(()=>{}),fetch("/api/providers/client").then(l=>l.json()).then(l=>{const k=(l.connections||[]).filter(T=>T.provider===t&&T.isActive!==!1);ee(k)}).catch(()=>{})},[t]),s.useEffect(()=>{v&&Q(l=>{const k={...l};let T=!1;return(p.extraFields||[]).forEach(te=>{const se=Array.isArray(v==null?void 0:v.paramDefs)?v.paramDefs.find(oe=>oe.name===te.key):null,q=(se==null?void 0:se.validValues)||te.options||[],he=l[te.key];if(he&&q.length>0&&!q.includes(he)){const oe=(se==null?void 0:se.default)??q[0]??"";oe!==he&&(k[te.key]=oe,T=!0)}}),T?k:l})},[A,v,p.extraFields]),!M||!d)return null;const $e=ae?m:W,Pe=M.endpoint.path,ge=$?A?`${c}/${A}`:R?"":c:c,je=Ht(t,A),ke=j.trim()||je.image||"",Se=N.trim()||je.mask_image||"",Ke=ht(ke),Te=ht(Se),Fe=Object.entries(X).reduce((l,[k,T])=>(T===""||T===null||T===void 0||typeof T=="number"&&Number.isNaN(T)||(l[k]=T),l),{}),_e={model:ge,[d.bodyKey]:L,...d.extraBody,...Fe,...U&&ke?{image:ke}:{},...O&&Se?{mask_image:Se}:{}},Ce=r==="image"&&b==="binary",Ee=r==="image"&&t==="codex"&&!Ce,Le=`${Pe}${Ce?"?response_format=binary":""}`,Ve=`-H "Content-Type: application/json" \\
46
+ -H "Authorization: Bearer ${V||"YOUR_KEY"}"${ce?` \\
47
+ -H "x-connection-id: ${ce}"`:""}${Ee?` \\
48
+ -H "Accept: text/event-stream"`:""}`,n=`curl -X ${M.endpoint.method} ${$e}${Le} \\
49
+ ${Ve.replace(/\\\n /g,`\\
50
+ `)} \\
51
+ -d '${JSON.stringify(_e)}'${Ce?` \\
52
+ --output image.png`:""}`,Y=async()=>{var k;if(!L.trim()||!ge)return;if(ye(!0),C(""),g(null),K(null),D(null),ne){try{URL.revokeObjectURL(ne)}catch{}G("")}const l=Date.now();try{const T={"Content-Type":"application/json"};V&&(T.Authorization=`Bearer ${V}`),ce&&(T["x-connection-id"]=ce),Ee&&(T.Accept="text/event-stream");const te={..._e,model:ge},se=await fetch(`/api${Le}`,{method:M.endpoint.method,headers:T,body:JSON.stringify(te)});if(!se.ok){const oe=await se.json().catch(()=>({}));C(((k=oe==null?void 0:oe.error)==null?void 0:k.message)||(oe==null?void 0:oe.error)||`HTTP ${se.status}`);return}const q=se.headers.get("content-type")||"";if(q.startsWith("image/")){const oe=await se.blob(),Ie=URL.createObjectURL(oe);G(Ie),g({data:{binary:!0,mime:q,size:oe.size},latencyMs:Date.now()-l});return}if(q.includes("text/event-stream")&&se.body){const oe=se.body.getReader(),Ie=new TextDecoder;let De="",He=null,We=null;for(;;){const{done:Rt,value:At}=await oe.read();if(Rt)break;De+=Ie.decode(At,{stream:!0});let Ge;for(;(Ge=De.indexOf(`
53
+
54
+ `))!==-1;){const Mt=De.slice(0,Ge);De=De.slice(Ge+2);let Re=null,Ye="";for(const me of Mt.split(`
55
+ `))me.startsWith("event:")?Re=me.slice(6).trim():me.startsWith("data:")&&(Ye+=me.slice(5).trim());if(Re)try{const me=Ye?JSON.parse(Ye):{};Re==="progress"?K(me):Re==="partial_image"?D(me):Re==="done"?He=me:Re==="error"&&(We=(me==null?void 0:me.message)||"Stream error")}catch{}}}const Et=Date.now()-l;if(We){C(We);return}He&&g({data:He,latencyMs:Et})}else{const oe=await se.json(),Ie=Date.now()-l;g({data:oe,latencyMs:Ie})}}catch(T){C(T.message||"Network error")}finally{ye(!1)}},E=l=>{if(!l||typeof l!="object")return l;if(Array.isArray(l))return l.map(E);const k={};for(const[T,te]of Object.entries(l))k[T]=T==="b64_json"&&typeof te=="string"&&te.length>100?`<${te.length} chars base64>`:E(te);return k},F=a?JSON.stringify(E(a.data),null,2):"";return e.jsxs(we,{children:[e.jsx("h2",{className:"text-lg font-semibold mb-4",children:"Example"}),e.jsxs("div",{className:"flex flex-col gap-2.5",children:[h.length>0?e.jsx(_,{label:"Model",children:e.jsx("select",{value:A,onChange:l=>u(l.target.value),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:h.map(l=>e.jsx("option",{value:l.id,children:l.name||l.id},l.id))})}):R?e.jsx(_,{label:"Model",children:e.jsx("input",{value:A,onChange:l=>u(l.target.value),placeholder:"Enter model id (provider-specific)",className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary font-mono"})}):null,e.jsx(_,{label:"Endpoint",children:e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsxs("span",{className:"w-full min-w-0 flex-1 px-3 py-1.5 text-sm font-mono text-text-main bg-sidebar rounded-lg truncate",children:[$e,Pe]}),m&&e.jsxs("button",{onClick:()=>H(l=>!l),title:ae?"Using tunnel":"Using local",className:`flex items-center gap-1 text-xs px-2 py-1.5 rounded-lg border shrink-0 transition-colors ${ae?"border-primary/40 bg-primary/10 text-primary":"border-border text-text-muted hover:text-primary"}`,children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"wifi_tethering"}),"Tunnel"]})]})}),e.jsx(_,{label:"API Key",children:e.jsx("span",{className:"px-3 py-1.5 text-sm font-mono text-text-main bg-sidebar rounded-lg truncate block",children:V?`${V.slice(0,8)}${"•".repeat(Math.min(20,V.length-8))}`:e.jsx("span",{className:"text-text-muted italic",children:"No key configured"})})}),J.length>0&&e.jsx(_,{label:"Connection",children:e.jsxs("select",{value:ce,onChange:l=>fe(l.target.value),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[e.jsx("option",{value:"",children:"Auto (by priority)"}),J.map(l=>{var te;const k=(te=l.providerSpecificData)==null?void 0:te.chatgptPlanType,T=l.email||l.name||l.id.slice(0,8);return e.jsxs("option",{value:l.id,children:[T,k?` [${k}]`:""]},l.id)})]})}),e.jsx(_,{label:d.inputLabel,children:e.jsxs("div",{className:"relative",children:[e.jsx("input",{value:L,onChange:l=>I(l.target.value),placeholder:d.inputPlaceholder,className:"w-full px-3 py-1.5 pr-7 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"}),L&&e.jsx("button",{type:"button",onClick:()=>I(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-text-muted hover:text-primary transition-colors",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"close"})})]})}),U&&e.jsx(_,{label:"Ref Image (URL)",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx("input",{value:j,onChange:l=>x(l.target.value),placeholder:je.image||"https://example.com/source.png",className:"w-full px-3 py-1.5 pr-7 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"}),j&&e.jsx("button",{type:"button",onClick:()=>x(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-text-muted hover:text-primary transition-colors",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"close"})})]}),Ke&&e.jsx("img",{src:Ke,alt:"Reference",className:"max-h-40 rounded-lg border border-border object-contain bg-sidebar",onError:l=>{l.currentTarget.style.display="none"},onLoad:l=>{l.currentTarget.style.display="block"}})]})}),O&&e.jsx(_,{label:"Mask (URL)",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx("input",{value:N,onChange:l=>B(l.target.value),placeholder:je.mask_image||"https://example.com/mask.png",className:"w-full px-3 py-1.5 pr-7 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"}),N&&e.jsx("button",{type:"button",onClick:()=>B(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-text-muted hover:text-primary transition-colors",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"close"})})]}),Te&&e.jsx("img",{src:Te,alt:"Mask",className:"max-h-40 rounded-lg border border-border object-contain bg-sidebar",onError:l=>{l.currentTarget.style.display="none"},onLoad:l=>{l.currentTarget.style.display="block"}})]})}),(()=>{const l={"1:1":"1:1 Square","9:16":"9:16 Portrait","3:4":"3:4 Portrait","16:9":"16:9 Landscape","4:3":"4:3 Landscape"};return(d.extraFields||[]).filter(k=>h.length===0||Array.isArray(v==null?void 0:v.params)&&v.params.includes(k.key)).map(k=>{const T=Array.isArray(v==null?void 0:v.paramDefs)?v.paramDefs.find(q=>q.name===k.key):null,te=(T==null?void 0:T.validValues)||k.options||[],se=te.length>0&&te.every(q=>q in l);return e.jsx(_,{label:k.label,children:k.type==="select"?e.jsx("select",{value:X[k.key]??"",onChange:q=>Q(he=>({...he,[k.key]:q.target.value})),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:(te||[]).map(q=>e.jsx("option",{value:q,children:q===""?"(default)":se&&l[q]||q},q))}):k.type==="text"?e.jsx("input",{type:"text",value:X[k.key]??"",placeholder:k.placeholder,onChange:q=>Q(he=>({...he,[k.key]:q.target.value})),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"}):e.jsx("input",{type:"number",value:X[k.key]??"",min:k.min,max:k.max,onChange:q=>Q(he=>({...he,[k.key]:q.target.value===""?"":Number(q.target.value)})),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})},k.key)})})(),r==="image"&&e.jsx(_,{label:"Output Format",children:e.jsxs("select",{value:b,onChange:l=>Z(l.target.value),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[e.jsx("option",{value:"json",children:"JSON (Base64)"}),e.jsx("option",{value:"binary",children:"Binary File"})]})}),e.jsxs("div",{className:"mt-1",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-1.5",children:[e.jsx("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:"Request"}),e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsxs("button",{onClick:()=>de(n),className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:Ne?"check":"content_copy"}),Ne?"Copied":"Copy"]}),e.jsxs("button",{onClick:Y,disabled:ue||!L.trim()||!ge,className:"flex w-full sm:w-auto items-center justify-center gap-1.5 px-3 py-1 rounded-lg bg-primary text-white text-xs font-medium hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",style:ue?{animation:"spin 1s linear infinite"}:void 0,children:"play_arrow"}),ue?"Running...":"Run"]})]})]}),e.jsx("pre",{className:"bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre-wrap break-all",children:n})]}),(ue||P)&&Ee&&e.jsxs("div",{className:"flex flex-col gap-2 px-3 py-2 rounded-lg bg-sidebar border border-border sm:flex-row sm:items-center sm:gap-3",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px] text-primary",style:ue?{animation:"spin 1s linear infinite"}:void 0,children:ue?"progress_activity":"check_circle"}),e.jsxs("span",{className:"text-xs text-text-muted",children:[(P==null?void 0:P.stage)||"starting",!ue&&(P!=null&&P.bytesReceived)?` · ${(P.bytesReceived/1024).toFixed(1)} KB`:""]})]}),(f==null?void 0:f.b64_json)&&!a&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:"Partial preview"}),e.jsx("img",{src:`data:image/png;base64,${f.b64_json}`,alt:"Partial",className:"max-w-full rounded-lg border border-border mt-1.5 opacity-80"})]}),xe&&e.jsx("p",{className:"text-xs text-red-500 break-words",children:xe}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-1.5",children:[e.jsxs("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:["Response ",a&&e.jsxs("span",{className:"font-normal normal-case",children:["⚡ ",a.latencyMs,"ms"]})]}),a&&e.jsxs("button",{onClick:()=>ze(F),className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:Me?"check":"content_copy"}),Me?"Copied":"Copy"]})]}),e.jsx("pre",{className:"bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre-wrap break-all opacity-70",children:a?F:d.defaultResponse}),r==="image"&&(ne||((Qe=(Je=a==null?void 0:a.data)==null?void 0:Je.data)==null?void 0:Qe[0]))&&e.jsxs("div",{className:"mt-2",children:[e.jsx("div",{className:"flex items-center justify-end mb-1.5",children:e.jsxs("a",{href:ne||((tt=(et=(Ze=a==null?void 0:a.data)==null?void 0:Ze.data)==null?void 0:et[0])!=null&&tt.b64_json?`data:image/png;base64,${a.data.data[0].b64_json}`:((nt=(at=(st=a==null?void 0:a.data)==null?void 0:st.data)==null?void 0:at[0])==null?void 0:nt.url)||""),download:"image.png",className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"download"}),"Download"]})}),e.jsx("img",{src:ne||((lt=(rt=(ot=a==null?void 0:a.data)==null?void 0:ot.data)==null?void 0:rt[0])!=null&&lt.b64_json?`data:image/png;base64,${a.data.data[0].b64_json}`:(dt=(ct=(it=a==null?void 0:a.data)==null?void 0:it.data)==null?void 0:ct[0])==null?void 0:dt.url),alt:"Generated",className:"max-w-full rounded-lg border border-border"})]}),r==="video"&&((mt=(ut=a==null?void 0:a.data)==null?void 0:ut.data)==null?void 0:mt.length)>0&&(()=>{const l=a.data.data,k=l.find(se=>/\.mp4(\?|$)/i.test(se.url||"")||/\/video\//i.test(se.url||""))||l[l.length-1],T=k==null?void 0:k.url;if(!T)return null;const te=`/api/media-proxy?url=${encodeURIComponent(T)}`;return e.jsxs("div",{className:"mt-2",children:[e.jsx("div",{className:"flex items-center justify-end mb-1.5",children:e.jsxs("a",{href:T,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"download"}),"Download"]})}),e.jsx("video",{src:te,controls:!0,preload:"metadata",className:"max-w-full rounded-lg border border-border"})]})})()]})]})]})}function Xt({providerId:t}){var xe;const r=Be(t),i=pe(t).filter(C=>C.type==="stt"),[S,c]=s.useState([]),M=[...i,...S],[d,p]=s.useState(((xe=i[0])==null?void 0:xe.id)??""),h=M.find(C=>C.id===d),y=Array.isArray(h==null?void 0:h.params)?h.params:[],[$,R]=s.useState(null),[A,u]=s.useState(""),[v,U]=s.useState(""),[O,L]=s.useState("json"),[I,j]=s.useState(""),[x,N]=s.useState(""),[B,X]=s.useState(!1),[Q,V]=s.useState(""),[re,ae]=s.useState(""),[H,W]=s.useState(null),[le,m]=s.useState(null),[o,a]=s.useState(!1),[g,P]=s.useState(""),{copied:K,copy:f}=ve(),{copied:D,copy:b}=ve();s.useEffect(()=>{V(window.location.origin),fetch("/api/keys").then(J=>J.json()).then(J=>{var ee;N(((ee=(J.keys||[]).find(ce=>ce.isActive!==!1))==null?void 0:ee.key)||"")}).catch(()=>{}),fetch("/api/tunnel/status").then(J=>J.json()).then(J=>{J.publicUrl&&ae(J.publicUrl)}).catch(()=>{});const C=()=>{fetch("/api/models/custom",{cache:"no-store"}).then(J=>J.json()).then(J=>{const ee=(J.models||[]).filter(ce=>ce.type==="stt"&&ce.providerAlias===r);c(ee)}).catch(()=>{})};return C(),window.addEventListener("focus",C),window.addEventListener("customModelChanged",C),()=>{window.removeEventListener("focus",C),window.removeEventListener("customModelChanged",C)}},[r]);const Z=B?re:Q,ne=d?`${r}/${d}`:"",G=`curl -X POST ${Z}/v1/audio/transcriptions \\
56
+ -H "Authorization: Bearer ${x||"YOUR_KEY"}" \\
57
+ -F "file=@${($==null?void 0:$.name)||"audio.mp3"}" \\
58
+ -F "model=${ne}"${y.includes("language")&&A?` \\
59
+ -F "language=${A}"`:""}${y.includes("response_format")?` \\
60
+ -F "response_format=${O}"`:""}${y.includes("temperature")&&I?` \\
61
+ -F "temperature=${I}"`:""}${y.includes("prompt")&&v?` \\
62
+ -F "prompt=${v}"`:""}`,ue=async()=>{var J;if(!$||!ne)return;a(!0),P(""),W(null);const C=Date.now();try{const ee=new FormData;ee.append("file",$),ee.append("model",ne),y.includes("language")&&A&&ee.append("language",A),y.includes("response_format")&&ee.append("response_format",O),y.includes("temperature")&&I&&ee.append("temperature",I),y.includes("prompt")&&v&&ee.append("prompt",v);const ce={};x&&(ce.Authorization=`Bearer ${x}`);const fe=await fetch("/api/v1/audio/transcriptions",{method:"POST",headers:ce,body:ee});m(Date.now()-C);const de=(fe.headers.get("content-type")||"").includes("application/json")?await fe.json():await fe.text();if(!fe.ok){P(((J=de==null?void 0:de.error)==null?void 0:J.message)||(de==null?void 0:de.error)||de||`HTTP ${fe.status}`);return}W(de)}catch(ee){P(ee.message||"Network error")}finally{a(!1)}},ye=typeof H=="string"?H:H?JSON.stringify(H,null,2):`{
63
+ "text": "Hello world..."
64
+ }`;return e.jsxs(we,{children:[e.jsx("h2",{className:"text-lg font-semibold mb-4",children:"Example"}),e.jsxs("div",{className:"flex flex-col gap-2.5",children:[M.length>0?e.jsx(_,{label:"Model",children:e.jsx("select",{value:d,onChange:C=>p(C.target.value),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:M.map(C=>e.jsx("option",{value:C.id,children:C.name||C.id},C.id))})}):e.jsx(_,{label:"Model",children:e.jsx("input",{value:d,onChange:C=>p(C.target.value),placeholder:"Enter model id",className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary font-mono"})}),e.jsx(_,{label:"Endpoint",children:e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsxs("span",{className:"w-full min-w-0 flex-1 px-3 py-1.5 text-sm font-mono text-text-main bg-sidebar rounded-lg truncate",children:[Z,"/v1/audio/transcriptions"]}),re&&e.jsxs("button",{onClick:()=>X(C=>!C),title:B?"Using tunnel":"Using local",className:`flex items-center gap-1 text-xs px-2 py-1.5 rounded-lg border shrink-0 transition-colors ${B?"border-primary/40 bg-primary/10 text-primary":"border-border text-text-muted hover:text-primary"}`,children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"wifi_tethering"}),"Tunnel"]})]})}),e.jsx(_,{label:"API Key",children:e.jsx("span",{className:"px-3 py-1.5 text-sm font-mono text-text-main bg-sidebar rounded-lg truncate block",children:x?`${x.slice(0,8)}${"•".repeat(Math.min(20,x.length-8))}`:e.jsx("span",{className:"text-text-muted italic",children:"No key configured"})})}),e.jsx(_,{label:"Audio File",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("input",{type:"file",accept:"audio/*,video/mp4,.m4a,.mp3,.wav,.ogg,.flac,.webm,.opus",onChange:C=>{var J;return R(((J=C.target.files)==null?void 0:J[0])||null)},className:"w-full text-xs text-text-muted file:mr-2 file:py-1 file:px-2.5 file:rounded-lg file:border file:border-border file:bg-background file:text-text-main hover:file:bg-sidebar file:cursor-pointer"}),$&&e.jsxs("span",{className:"text-xs text-text-muted font-mono",children:[$.name," · ",($.size/1024).toFixed(1)," KB"]})]})}),y.includes("language")&&e.jsx(_,{label:"Language",children:e.jsx("input",{value:A,onChange:C=>u(C.target.value),placeholder:"e.g. en, vi, ja (auto-detect if empty)",className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary font-mono"})}),y.includes("prompt")&&e.jsx(_,{label:"Prompt",children:e.jsx("input",{value:v,onChange:C=>U(C.target.value),placeholder:"optional context to improve accuracy",className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})}),y.includes("temperature")&&e.jsx(_,{label:"Temperature",children:e.jsx("input",{type:"number",step:"0.1",min:"0",max:"1",value:I,onChange:C=>j(C.target.value),placeholder:"0 - 1 (default 0)",className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})}),y.includes("response_format")&&e.jsx(_,{label:"Response Format",children:e.jsxs("select",{value:O,onChange:C=>L(C.target.value),className:"w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[e.jsx("option",{value:"json",children:"json"}),e.jsx("option",{value:"text",children:"text"}),e.jsx("option",{value:"srt",children:"srt"}),e.jsx("option",{value:"verbose_json",children:"verbose_json"}),e.jsx("option",{value:"vtt",children:"vtt"})]})}),e.jsxs("div",{className:"mt-1",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-1.5",children:[e.jsx("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:"Request"}),e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsxs("button",{onClick:()=>f(G),className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:K?"check":"content_copy"}),K?"Copied":"Copy"]}),e.jsxs("button",{onClick:ue,disabled:o||!$||!ne,className:"flex w-full sm:w-auto items-center justify-center gap-1.5 px-3 py-1 rounded-lg bg-primary text-white text-xs font-medium hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",style:o?{animation:"spin 1s linear infinite"}:void 0,children:"play_arrow"}),o?"Transcribing...":"Run"]})]})]}),e.jsx("pre",{className:"bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre-wrap break-all",children:G})]}),g&&e.jsx("p",{className:"text-xs text-red-500 break-words",children:g}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-1.5",children:[e.jsxs("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:["Response ",H&&le&&e.jsxs("span",{className:"font-normal normal-case",children:["⚡ ",le,"ms"]})]}),H&&e.jsxs("button",{onClick:()=>b(ye),className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:D?"check":"content_copy"}),D?"Copied":"Copy"]})]}),e.jsx("pre",{className:"bg-sidebar rounded-lg px-3 py-2.5 text-xs font-mono text-text-main overflow-x-auto whitespace-pre-wrap break-all opacity-70",children:ye})]})]})]})}function ss(){var U,O,L,I,j,x;const{kind:t,id:r}=Lt(),i=It(),S=bt.find(N=>N.id===t),c=yt(r)&&t==="embedding",M=async()=>{if(confirm("Delete this Custom Embedding node?"))try{(await fetch(`/api/provider-nodes/${r}`,{method:"DELETE"})).ok&&i(`/dashboard/media-providers/${t}`)}catch(N){console.log("Error deleting custom embedding node:",N)}},[d,p]=s.useState(null),[h,y]=s.useState(c),[$,R]=s.useState(!1);if(s.useEffect(()=>{if(!c)return;let N=!1;return fetch("/api/provider-nodes",{cache:"no-store"}).then(B=>B.json()).then(B=>{N||(p((B.nodes||[]).find(X=>X.id===r)||null),y(!1))}).catch(()=>{N||y(!1)}),()=>{N=!0}},[r,c]),!S)return null;const A=Ae[r],u=c?d?{id:r,name:d.name||"Custom Embedding",color:"#6366F1",textIcon:"CE"}:null:A;if(!c&&!A||c&&!h&&!d)return null;if(c&&h)return e.jsx("div",{className:"text-text-muted text-sm py-12 text-center",children:"Loading..."});const v=c?["embedding"]:u.serviceKinds??["llm"];return!c&&!v.includes(t)?null:e.jsxs("div",{className:"flex flex-col gap-8",children:[e.jsxs("div",{children:[e.jsxs(Dt,{to:`/dashboard/media-providers/${t}`,className:"inline-flex items-center gap-1 text-sm text-text-muted hover:text-primary transition-colors mb-4",children:[e.jsx("span",{className:"material-symbols-outlined text-lg",children:"arrow_back"}),S.label]}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-4",children:[e.jsx("div",{className:"size-12 rounded-lg flex items-center justify-center shrink-0",style:{backgroundColor:`${u.color}15`},children:e.jsx(Pt,{src:`/providers/${u.id}.png`,alt:u.name,size:48,className:"object-contain rounded-lg max-w-[48px] max-h-[48px]",fallbackText:u.textIcon||u.id.slice(0,2).toUpperCase(),fallbackColor:u.color})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3",children:[e.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:u.name}),!c&&((U=u.notice)==null?void 0:U.apiKeyUrl)&&e.jsxs("a",{href:u.notice.apiKeyUrl,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline inline-flex items-center gap-1",children:[e.jsx("span",{className:"material-symbols-outlined text-sm",children:"open_in_new"}),"Get API Key"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 flex-wrap",children:[c&&e.jsxs(Oe,{variant:"default",size:"sm",children:["Custom · ",d==null?void 0:d.prefix]}),v.map(N=>e.jsx(Oe,{variant:N===t?"primary":"default",size:"sm",children:N.toUpperCase()},N))]})]}),c&&e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsx(be,{size:"sm",variant:"secondary",icon:"edit",onClick:()=>R(!0),children:"Edit"}),e.jsx(be,{size:"sm",variant:"secondary",icon:"delete",onClick:M,children:"Delete"})]})]})]}),!c&&((O=u.kindNotice)==null?void 0:O[t])&&e.jsxs("div",{className:"flex items-start gap-3 px-4 py-3 rounded-lg bg-amber-500/10 border border-amber-500/30 text-amber-700 dark:text-amber-400",children:[e.jsx("span",{className:"material-symbols-outlined text-[20px] mt-0.5",children:"warning"}),e.jsx("p",{className:"text-sm",children:u.kindNotice[t]})]}),!c&&((L=u.notice)==null?void 0:L.text)&&!u.deprecated&&e.jsxs("div",{className:"flex flex-col gap-2 rounded-lg border border-blue-500/30 bg-blue-500/10 px-3 py-2 sm:flex-row sm:items-center",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px] text-blue-500 shrink-0",children:"info"}),e.jsx("p",{className:"min-w-0 flex-1 text-xs leading-relaxed text-blue-600 dark:text-blue-400",children:u.notice.text}),u.notice.apiKeyUrl&&e.jsx("a",{href:u.notice.apiKeyUrl,target:"_blank",rel:"noopener noreferrer",className:"inline-flex justify-center rounded bg-blue-500 px-2 py-1 text-xs font-medium text-white transition-colors hover:bg-blue-600 sm:py-0.5",children:"Get API Key →"})]}),!c&&u.noAuth?e.jsx(Bt,{providerId:r}):e.jsx(Nt,{providerId:r,isOAuth:!1}),t!=="tts"&&t!=="webSearch"&&t!=="webFetch"&&e.jsx(St,{providerId:r,kindFilter:t,providerAliasOverride:c?d==null?void 0:d.prefix:void 0}),!c&&(u.searchConfig||u.fetchConfig||u.ttsConfig||u.sttConfig||u.embeddingConfig||u.searchViaChat)&&e.jsx(Vt,{config:t==="webFetch"?u.fetchConfig:t==="tts"?u.ttsConfig:t==="stt"?u.sttConfig:t==="embedding"?u.embeddingConfig:u.searchConfig||{mode:"chat-completions",defaultModel:(I=u.searchViaChat)==null?void 0:I.defaultModel,pricingUrl:(j=u.searchViaChat)==null?void 0:j.pricingUrl,freeTier:(x=u.searchViaChat)==null?void 0:x.freeTier},provider:u,title:`${S.label} Config`}),t==="embedding"&&e.jsx(Wt,{providerId:r,customAlias:d==null?void 0:d.prefix}),t==="tts"&&e.jsx(Gt,{providerId:r}),t==="stt"&&!c&&e.jsx(Xt,{providerId:r}),!c&&Ct[t]&&e.jsx(Yt,{providerId:r,kind:t}),c&&e.jsx(Kt,{isOpen:$,node:d,onClose:()=>R(!1),onSaved:N=>{p(N),R(!1)}})]})}export{ss as default};
@@ -0,0 +1 @@
1
+ import{F as le,j as e,g as Y,n as k,B as q,o as oe}from"./index.AIBoioDI.js";import{d as se,f as re,b as x}from"./router.Cjj1--8t.js";import{B as I,f as D,c as M,d as ie,P as de,U as ce,e as xe,C as V}from"./NoAuthProxyCard.CZTUlj4t.js";import{C as ae}from"./Loading.DFQ28pFE.js";import"./zustand.akaTi5uX.js";function Q(s){if(s==="leonardo"||s==="weavy")return!0;const t=Y[s];return t!=null&&t.serviceKinds?t.serviceKinds.includes("llm"):!0}function me(s){const t=Math.floor((Date.now()-new Date(s))/1e3);return t<60?`${t}s ago`:t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:`${Math.floor(t/86400)}d ago`}function ue({timestamp:s}){const[,t]=x.useState(0);return x.useEffect(()=>{const r=setInterval(()=>t(a=>a+1),1e3);return()=>clearInterval(r)},[]),e.jsx(e.Fragment,{children:me(s)})}function pe({requests:s=[]}){return e.jsxs(V,{className:"flex min-w-0 flex-col overflow-hidden",padding:"sm",style:{height:480},children:[e.jsx("div",{className:"px-1 py-2 border-b border-border shrink-0",children:e.jsx("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wide",children:"Recent Requests"})}),s.length?e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsxs("table",{className:"w-full min-w-[300px] border-collapse text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-bg z-10",children:e.jsxs("tr",{className:"border-b border-border",children:[e.jsx("th",{className:"py-1.5 text-left font-semibold text-text-muted w-2"}),e.jsx("th",{className:"py-1.5 text-left font-semibold text-text-muted",children:"Model"}),e.jsx("th",{className:"py-1.5 text-right font-semibold text-text-muted whitespace-nowrap",children:"In / Out"}),e.jsx("th",{className:"py-1.5 text-right font-semibold text-text-muted",children:"When"})]})}),e.jsx("tbody",{className:"divide-y divide-border/50",children:s.map((t,r)=>{const a=t.status==="streaming",i=!t.status||t.status==="ok"||t.status==="success";return e.jsxs("tr",{className:"hover:bg-bg-subtle transition-colors",children:[e.jsx("td",{className:"py-1.5",children:a?e.jsx("span",{className:"block w-1.5 h-1.5 rounded-full bg-warning animate-pulse",title:"Streaming…"}):e.jsx("span",{className:`block w-1.5 h-1.5 rounded-full ${i?"bg-success":"bg-error"}`})}),e.jsx("td",{className:"py-1.5 font-mono truncate max-w-[120px]",title:t.model,children:t.model}),e.jsx("td",{className:"py-1.5 text-right whitespace-nowrap",children:a?e.jsx("span",{className:"text-warning italic text-[10px]",children:"streaming…"}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-primary",children:[D(t.promptTokens),"↑"]})," ",e.jsxs("span",{className:"text-success",children:[D(t.completionTokens),"↓"]})]})}),e.jsx("td",{className:"py-1.5 text-right text-text-muted whitespace-nowrap",children:e.jsx(ue,{timestamp:t.timestamp})})]},r)})})]})}):e.jsx("div",{className:"flex-1 flex items-center justify-center text-text-muted text-sm",children:"No requests yet."})]})}function _(s,t={},r,a){return Object.entries(s||{}).map(([i,o])=>{const n=(o.promptTokens||0)+(o.completionTokens||0),l=o.cost||0,b=n>0?(o.promptTokens||0)*(l/n):0,p=n>0?(o.completionTokens||0)*(l/n):0;return{...o,key:i,totalTokens:n,totalCost:l,inputCost:b,outputCost:p,pending:t[i]||0}}).sort((i,o)=>{let n=i[r],l=o[r];return typeof n=="string"&&(n=n.toLowerCase()),typeof l=="string"&&(l=l.toLowerCase()),n<l?a==="asc"?-1:1:n>l?a==="asc"?1:-1:0})}function he(s,t){var r;switch(t){case"rawModel":return s.rawModel||"Unknown Model";case"accountName":return s.accountName||`Account ${(r=s.connectionId)==null?void 0:r.slice(0,8)}...`||"Unknown Account";case"keyName":return s.keyName||"Unknown Key";case"endpoint":return s.endpoint||"Unknown Endpoint";default:return s[t]||"Unknown"}}function K(s,t){if(!Array.isArray(s))return[];const r={};return s.forEach(a=>{const i=he(a,t);r[i]||(r[i]={groupKey:i,summary:{requests:0,promptTokens:0,completionTokens:0,totalTokens:0,cost:0,inputCost:0,outputCost:0,lastUsed:null,pending:0},items:[]});const o=r[i].summary;o.requests+=a.requests||0,o.promptTokens+=a.promptTokens||0,o.completionTokens+=a.completionTokens||0,o.totalTokens+=a.totalTokens||0,o.cost+=a.cost||0,o.inputCost+=a.inputCost||0,o.outputCost+=a.outputCost||0,o.pending+=a.pending||0,a.lastUsed&&(!o.lastUsed||new Date(a.lastUsed)>new Date(o.lastUsed))&&(o.lastUsed=a.lastUsed),r[i].items.push(a)}),Object.values(r)}const fe=[{field:"rawModel",label:"Model"},{field:"provider",label:"Provider"},{field:"requests",label:"Requests",align:"right"},{field:"lastUsed",label:"Last Used",align:"right"}],be=[{field:"rawModel",label:"Model"},{field:"provider",label:"Provider"},{field:"accountName",label:"Account"},{field:"requests",label:"Requests",align:"right"},{field:"lastUsed",label:"Last Used",align:"right"}],ge=[{field:"keyName",label:"API Key Name"},{field:"rawModel",label:"Model"},{field:"provider",label:"Provider"},{field:"requests",label:"Requests",align:"right"},{field:"lastUsed",label:"Last Used",align:"right"}],je=[{field:"endpoint",label:"Endpoint"},{field:"rawModel",label:"Model"},{field:"provider",label:"Provider"},{field:"requests",label:"Requests",align:"right"},{field:"lastUsed",label:"Last Used",align:"right"}],ve=[{value:"model",label:"Usage by Model"},{value:"account",label:"Usage by Account"},{value:"apiKey",label:"Usage by API Key"},{value:"endpoint",label:"Usage by Endpoint"}],ye=[{value:"today",label:"Today"},{value:"24h",label:"24h"},{value:"7d",label:"7D"},{value:"30d",label:"30D"},{value:"60d",label:"60D"}];function X(s){if(!s)return s;const t={...s};if(t.byProvider&&(t.byProvider={...t.byProvider},t.byProvider.cb)){if(!t.byProvider.codebuddy)t.byProvider.codebuddy=t.byProvider.cb;else{const r=t.byProvider.cb,a=t.byProvider.codebuddy;t.byProvider.codebuddy={requests:(a.requests||0)+(r.requests||0),promptTokens:(a.promptTokens||0)+(r.promptTokens||0),completionTokens:(a.completionTokens||0)+(r.completionTokens||0),cost:(a.cost||0)+(r.cost||0)}}delete t.byProvider.cb}return t.byModel&&(t.byModel=Object.fromEntries(Object.entries(t.byModel).map(([r,a])=>r.endsWith(" (cb)")?[r.slice(0,-5)+" (codebuddy)",{...a,provider:"CodeBuddy"}]:[r,a]))),t.byAccount&&(t.byAccount=Object.fromEntries(Object.entries(t.byAccount).map(([r,a])=>a.provider==="cb"||a.provider==="Codebuddy"||a.provider==="codebuddy"?[r,{...a,provider:"CodeBuddy"}]:[r,a]))),Array.isArray(t.recentRequests)&&(t.recentRequests=t.recentRequests.map(r=>r.provider==="cb"?{...r,provider:"codebuddy"}:r)),t}function Ne({period:s,setPeriod:t,hidePeriodSelector:r=!1}={}){var E,c,w,C;const a=se(),[i]=re(),o=i.get("sortBy")||"rawModel",n=i.get("sortOrder")||"asc",[l,b]=x.useState(null),[p,j]=x.useState(!0),[f,P]=x.useState(!1),[y,h]=x.useState("model"),[N,L]=x.useState("costs"),[O,J]=x.useState([]),[G,W]=x.useState("today"),A=x.useRef(!0),T=s??G,F=t??W;x.useEffect(()=>{fetch("/api/providers").then(m=>m.ok?m.json():null).then(m=>{const v=new Set,d=((m==null?void 0:m.connections)||[]).filter(g=>g.isActive===!1||!Q(g.provider)||v.has(g.provider)?!1:(v.add(g.provider),!0)),u=Object.values(le).filter(g=>g.noAuth&&!v.has(g.id)&&Q(g.id)).map(g=>({provider:g.id,name:g.name}));J([...d,...u])}).catch(()=>{})},[]),x.useEffect(()=>{A.current?(A.current=!1,j(!0)):P(!0),fetch(`/api/usage/stats?period=${T}`).then(m=>m.ok?m.json():null).then(m=>{if(m){const v=X(m);b(d=>({...d,...v}))}}).catch(()=>{}).finally(()=>{j(!1),P(!1)})},[T]),x.useEffect(()=>{const m=new EventSource(`/api/usage/stream?period=${T}`);return m.onmessage=v=>{try{const d=JSON.parse(v.data),u=X(d);b(u),j(!1)}catch(d){console.error("[SSE CLIENT] parse error:",d)}},m.onerror=()=>j(!1),()=>m.close()},[T]);const $=x.useCallback((m,v)=>{const d=new URLSearchParams(i.toString());d.get("sortBy")===v?d.set("sortOrder",d.get("sortOrder")==="asc"?"desc":"asc"):(d.set("sortBy",v),d.set("sortOrder","asc")),a(`?${d.toString()}`,{scroll:!1})},[i,a]),S=x.useMemo(()=>{var m,v;if(!l)return null;switch(y){case"model":{const d=((m=l.pending)==null?void 0:m.byModel)||{};return{columns:fe,groupedData:K(_(l.byModel,d,o,n),"rawModel"),storageKey:"usage-stats:expanded-models",emptyMessage:"No usage recorded yet.",renderSummaryCells:u=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(u.summary.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(u.summary.lastUsed)})]}),renderDetailCells:u=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:`px-6 py-3 font-medium transition-colors ${u.pending>0?"text-primary":""}`,children:u.rawModel}),e.jsx("td",{className:"px-6 py-3",children:e.jsx(I,{variant:u.pending>0?"primary":"neutral",size:"sm",children:u.provider})}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(u.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(u.lastUsed)})]})}}case"account":{const d={};return(v=l==null?void 0:l.pending)!=null&&v.byAccount&&Object.entries(l.byAccount||{}).forEach(([u,g])=>{const H=l.pending.byAccount[g.connectionId];if(H){const ne=g.provider?`${g.rawModel} (${g.provider})`:g.rawModel;d[u]=H[ne]||0}}),{columns:be,groupedData:K(_(l.byAccount,d,o,n),"accountName"),storageKey:"usage-stats:expanded-accounts",emptyMessage:"No account-specific usage recorded yet.",renderSummaryCells:u=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(u.summary.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(u.summary.lastUsed)})]}),renderDetailCells:u=>{var g;return e.jsxs(e.Fragment,{children:[e.jsx("td",{className:`px-6 py-3 font-medium transition-colors ${u.pending>0?"text-primary":""}`,children:u.accountName||`Account ${(g=u.connectionId)==null?void 0:g.slice(0,8)}...`}),e.jsx("td",{className:`px-6 py-3 font-medium transition-colors ${u.pending>0?"text-primary":""}`,children:u.rawModel}),e.jsx("td",{className:"px-6 py-3",children:e.jsx(I,{variant:u.pending>0?"primary":"neutral",size:"sm",children:u.provider})}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(u.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(u.lastUsed)})]})}}}case"apiKey":return{columns:ge,groupedData:K(_(l.byApiKey,{},o,n),"keyName"),storageKey:"usage-stats:expanded-apikeys",emptyMessage:"No API key usage recorded yet.",renderSummaryCells:d=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(d.summary.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(d.summary.lastUsed)})]}),renderDetailCells:d=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-6 py-3 font-medium",children:d.keyName}),e.jsx("td",{className:"px-6 py-3",children:d.rawModel}),e.jsx("td",{className:"px-6 py-3",children:e.jsx(I,{variant:"neutral",size:"sm",children:d.provider})}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(d.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(d.lastUsed)})]})};case"endpoint":default:return{columns:je,groupedData:K(_(l.byEndpoint,{},o,n),"endpoint"),storageKey:"usage-stats:expanded-endpoints",emptyMessage:"No endpoint usage recorded yet.",renderSummaryCells:d=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(d.summary.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(d.summary.lastUsed)})]}),renderDetailCells:d=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-6 py-3 font-medium font-mono text-sm",children:d.endpoint}),e.jsx("td",{className:"px-6 py-3",children:d.rawModel}),e.jsx("td",{className:"px-6 py-3",children:e.jsx(I,{variant:"neutral",size:"sm",children:d.provider})}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(d.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(d.lastUsed)})]})}}},[l,y,o,n]);if(!l&&!p)return e.jsx("div",{className:"text-text-muted",children:"Failed to load usage statistics."});const R=e.jsx("div",{className:"flex items-center justify-center py-12 text-text-muted",children:e.jsx("span",{className:"material-symbols-outlined text-[32px] animate-spin",children:"progress_activity"})});return e.jsxs("div",{className:"flex min-w-0 flex-col gap-6",children:[!r&&e.jsxs("div",{className:"flex w-full items-center gap-2 sm:w-auto sm:self-end",children:[e.jsx("div",{className:"grid flex-1 grid-cols-5 items-center gap-1 rounded-lg border border-border bg-bg-subtle p-1 sm:flex sm:flex-none",children:ye.map(m=>e.jsx("button",{onClick:()=>F(m.value),disabled:f,className:`rounded-md px-3 py-1 text-sm font-medium transition-colors ${T===m.value?"bg-primary text-white shadow-sm":"text-text-muted hover:bg-bg-hover hover:text-text"}`,children:m.label},m.value))}),f&&e.jsx("span",{className:"material-symbols-outlined text-[16px] text-text-muted animate-spin",children:"progress_activity"})]}),p?R:e.jsx(ie,{stats:l}),p?R:e.jsxs("div",{className:"grid min-w-0 grid-cols-1 items-stretch gap-2 lg:grid-cols-[minmax(0,2fr)_minmax(280px,1fr)]",children:[e.jsx(de,{providers:O,activeRequests:l.activeRequests||[],lastProvider:((c=(E=l.recentRequests)==null?void 0:E[0])==null?void 0:c.provider)||"",errorProvider:l.errorProvider||""}),e.jsx(pe,{requests:l.recentRequests||[]})]}),p?R:e.jsx(ce,{period:T,lastRequestTime:(C=(w=l==null?void 0:l.recentRequests)==null?void 0:w[0])==null?void 0:C.timestamp}),e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("select",{value:y,onChange:m=>h(m.target.value),className:"w-full rounded-lg border border-border bg-surface px-3 py-1.5 text-sm font-medium text-text-main focus:outline-none focus:ring-2 focus:ring-primary/50 sm:w-auto",style:{colorScheme:"auto"},children:ve.map(m=>e.jsx("option",{value:m.value,children:m.label},m.value))}),e.jsxs("div",{className:"grid grid-cols-2 items-center gap-1 rounded-lg border border-border bg-bg-subtle p-1 sm:flex",children:[e.jsx("button",{onClick:()=>L("costs"),className:`px-3 py-1 rounded-md text-sm font-medium transition-colors ${N==="costs"?"bg-primary text-white shadow-sm":"text-text-muted hover:text-text hover:bg-bg-hover"}`,children:"Costs"}),e.jsx("button",{onClick:()=>L("tokens"),className:`px-3 py-1 rounded-md text-sm font-medium transition-colors ${N==="tokens"?"bg-primary text-white shadow-sm":"text-text-muted hover:text-text hover:bg-bg-hover"}`,children:"Tokens"})]})]}),p?R:S&&e.jsx(xe,{title:"",columns:S.columns,groupedData:S.groupedData,tableType:y,sortBy:o,sortOrder:n,onToggleSort:$,viewMode:N,storageKey:S.storageKey,renderSummaryCells:S.renderSummaryCells,renderDetailCells:S.renderDetailCells,emptyMessage:S.emptyMessage})]})]})}function we(){const[s,t]=x.useState([]),[r,a]=x.useState(!0),[i,o]=x.useState(!0);x.useEffect(()=>{n()},[]),x.useEffect(()=>{let l;return i&&(l=setInterval(()=>{n(!1)},3e3)),()=>clearInterval(l)},[i]);const n=async(l=!0)=>{l&&a(!0);try{const b=await fetch("/api/usage/request-logs");if(b.ok){const p=await b.json();t(p)}}catch(b){console.error("Failed to fetch logs:",b)}finally{l&&a(!1)}};return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Request Logs"}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("label",{className:"text-sm font-medium text-text-muted flex items-center gap-2 cursor-pointer",children:[e.jsx("span",{children:"Auto Refresh (3s)"}),e.jsx("div",{onClick:()=>o(!i),className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none ${i?"bg-primary":"bg-bg-subtle border border-border"}`,children:e.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white transition-transform ${i?"translate-x-5":"translate-x-1"}`})})]})})]}),e.jsx(V,{className:"overflow-hidden bg-black/5 dark:bg-black/20",children:e.jsx("div",{className:"p-0 overflow-x-auto max-h-[600px] overflow-y-auto font-mono text-xs",children:r&&s.length===0?e.jsx("div",{className:"p-8 text-center text-text-muted",children:"Loading logs..."}):s.length===0?e.jsx("div",{className:"p-8 text-center text-text-muted",children:"No logs recorded yet."}):e.jsxs("table",{className:"w-full text-left border-collapse whitespace-nowrap",children:[e.jsx("thead",{className:"sticky top-0 bg-bg-subtle border-b border-border z-10",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 border-r border-border",children:"DateTime"}),e.jsx("th",{className:"px-3 py-2 border-r border-border",children:"Model"}),e.jsx("th",{className:"px-3 py-2 border-r border-border",children:"Provider"}),e.jsx("th",{className:"px-3 py-2 border-r border-border",children:"Account"}),e.jsx("th",{className:"px-3 py-2 border-r border-border",children:"In"}),e.jsx("th",{className:"px-3 py-2 border-r border-border",children:"Out"}),e.jsx("th",{className:"px-3 py-2",children:"Status"})]})}),e.jsx("tbody",{className:"divide-y divide-border/50",children:s.map((l,b)=>{const p=l.split(" | ");if(p.length<7)return null;const j=p[6],f=j.includes("PENDING"),P=j.includes("FAILED"),y=j.includes("OK");return e.jsxs("tr",{className:`hover:bg-primary/5 transition-colors ${f?"bg-primary/5":""}`,children:[e.jsx("td",{className:"px-3 py-1.5 border-r border-border text-text-muted",children:p[0]}),e.jsx("td",{className:"px-3 py-1.5 border-r border-border font-medium",children:p[1]}),e.jsx("td",{className:"px-3 py-1.5 border-r border-border",children:e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-bg-subtle border border-border text-[10px] uppercase font-bold",children:p[2]})}),e.jsx("td",{className:"px-3 py-1.5 border-r border-border truncate max-w-[150px]",title:p[3],children:p[3]}),e.jsx("td",{className:"px-3 py-1.5 border-r border-border text-right text-primary",children:p[4]}),e.jsx("td",{className:"px-3 py-1.5 border-r border-border text-right text-success",children:p[5]}),e.jsx("td",{className:`px-3 py-1.5 font-bold ${y?"text-success":P?"text-error":"text-primary animate-pulse"}`,children:j})]},b)})})]})})}),e.jsx("div",{className:"text-[10px] text-text-muted italic",children:"Logs are loaded from the request history database."})]})}function Z({options:s=[],value:t,onChange:r,size:a="md",className:i}){const o={sm:"h-7 text-xs",md:"h-9 text-sm",lg:"h-11 text-base"};return e.jsx("div",{className:k("inline-flex items-center p-1 rounded-[10px] overflow-x-auto","bg-surface-2",i),children:s.map(n=>e.jsxs("button",{onClick:()=>r(n.value),className:k("shrink-0 px-4 rounded-[8px] font-medium transition-all",o[a],t===n.value?"bg-surface text-text-main shadow-sm":"text-text-muted hover:text-text-main"),children:[n.icon&&e.jsx("span",{className:"material-symbols-outlined text-[16px] mr-1.5",children:n.icon}),n.label]},n.value))})}function ke({isOpen:s,onClose:t,title:r,children:a,width:i="md",className:o}){const n={sm:"w-[400px]",md:"w-[500px]",lg:"w-[600px]",xl:"w-[800px]",full:"w-full"};return x.useEffect(()=>(s?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[s]),x.useEffect(()=>{const l=b=>{b.key==="Escape"&&s&&t()};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[s,t]),s?e.jsxs("div",{className:"fixed inset-0 z-50",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-[2px] fade-in cursor-pointer",onClick:t,"aria-hidden":"true"}),e.jsxs("div",{className:k("absolute right-0 top-0 h-full bg-surface flex flex-col","shadow-[var(--shadow-elev)]","slide-in-right","border-l border-border-subtle",n[i]||n.md,o),children:[e.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border-subtle flex-shrink-0",children:[e.jsx("div",{className:"flex items-center gap-3",children:r&&e.jsx("h2",{className:"text-lg font-semibold text-text-main",children:r})}),e.jsx("button",{type:"button",onClick:t,className:"p-1.5 rounded-[10px] text-text-muted hover:bg-surface-2 hover:text-text-main transition-colors",children:e.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"close"})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-6 custom-scrollbar",children:a})]})]}):null}function Se({currentPage:s,pageSize:t,totalItems:r,onPageChange:a,onPageSizeChange:i,className:o}){const n=Math.ceil(r/t),l=r>0?(s-1)*t+1:0,b=Math.min(s*t,r),j=(()=>{const f=[];let y=Math.max(1,s-2),h=Math.min(n,y+5-1);h-y+1<5&&(y=Math.max(1,h-5+1));for(let N=y;N<=h;N++)f.push(N);return f})();return e.jsxs("div",{className:k("flex flex-col sm:flex-row items-center justify-between gap-4 py-4 px-2",o),children:[r>0&&e.jsxs("div",{className:"text-sm text-text-muted",children:["Showing ",e.jsx("span",{className:"font-medium text-text-main",children:l})," to"," ",e.jsx("span",{className:"font-medium text-text-main",children:b})," of"," ",e.jsx("span",{className:"font-medium text-text-main",children:r})," results"]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2 sm:gap-4",children:[i&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-text-muted",children:"Rows:"}),e.jsx("select",{value:t,onChange:f=>i(Number(f.target.value)),className:k("h-9 rounded-lg border border-black/10 dark:border-white/10 bg-surface","text-sm text-text-main focus:outline-none focus:ring-2 focus:ring-primary/20","cursor-pointer"),style:{colorScheme:"auto"},children:[10,20,50].map(f=>e.jsx("option",{value:f,children:f},f))})]}),n>1&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(q,{variant:"outline",size:"sm",onClick:()=>a(s-1),disabled:s===1,className:"w-9 px-0",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"chevron_left"})}),j[0]>1&&e.jsxs(e.Fragment,{children:[e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>a(1),className:"w-9 px-0 hidden sm:inline-flex",children:"1"}),j[0]>2&&e.jsx("span",{className:"text-text-muted px-1 hidden sm:inline",children:"..."})]}),j.map(f=>e.jsx(q,{variant:s===f?"primary":"ghost",size:"sm",onClick:()=>a(f),className:k("w-9 px-0",s===f?"inline-flex":"hidden sm:inline-flex"),children:f},f)),j[j.length-1]<n&&e.jsxs(e.Fragment,{children:[j[j.length-1]<n-1&&e.jsx("span",{className:"text-text-muted px-1 hidden sm:inline",children:"..."}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>a(n),className:"w-9 px-0 hidden sm:inline-flex",children:n})]}),e.jsx(q,{variant:"outline",size:"sm",onClick:()=>a(s+1),disabled:s===n,className:"w-9 px-0",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"chevron_right"})})]})]})]})}let z=null,U=null;async function Ce(){if(z&&U)return{providerNameCache:z,providerNodesCache:U};const r=(await(await fetch("/api/provider-nodes")).json()).nodes||[];U={};for(const a of r)U[a.id]=a.name;return z={...Y,...U},{providerNameCache:z,providerNodesCache:U}}function ee(s,t){if(!s||!t)return s;const r=t[s];if(typeof r=="string")return r;if(r!=null&&r.name)return r.name;const a=oe(s)||Y[s];return(a==null?void 0:a.name)||s}function B({title:s,children:t,defaultOpen:r=!1,icon:a=null}){const[i,o]=x.useState(r);return e.jsxs("div",{className:"border border-black/5 dark:border-white/5 rounded-lg overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>o(!i),className:"w-full flex items-center justify-between p-3 bg-black/[0.02] dark:bg-white/[0.02] hover:bg-black/[0.04] dark:hover:bg-white/[0.04] transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[a&&e.jsx("span",{className:"material-symbols-outlined text-[18px] text-text-muted",children:a}),e.jsx("span",{className:"font-semibold text-sm text-text-main",children:s})]}),e.jsx("span",{className:k("material-symbols-outlined text-[20px] text-text-muted transition-transform duration-200",i?"rotate-90":""),children:"chevron_right"})]}),i&&e.jsx("div",{className:"p-4 border-t border-black/5 dark:border-white/5",children:t})]})}function te(s){const t=(s==null?void 0:s.prompt_tokens)||(s==null?void 0:s.input_tokens)||0,r=(s==null?void 0:s.cached_tokens)||(s==null?void 0:s.cache_read_input_tokens)||0;return t<r?r:t}function De(){var T,F,$,S,R,E;const[s,t]=x.useState([]),[r,a]=x.useState({page:1,pageSize:20,totalItems:0,totalPages:0}),[i,o]=x.useState(!1),[n,l]=x.useState(null),[b,p]=x.useState(!1),[j,f]=x.useState([]),[P,y]=x.useState(null),[h,N]=x.useState({provider:"",startDate:"",endDate:""}),L=x.useCallback(async()=>{try{const w=await(await fetch("/api/usage/providers")).json();f(w.providers||[]);const C=await Ce();y(C.providerNameCache)}catch(c){console.error("Failed to fetch providers:",c)}},[]),O=x.useCallback(async()=>{o(!0);try{const c=new URLSearchParams({page:r.page.toString(),pageSize:r.pageSize.toString()});h.provider&&c.append("provider",h.provider),h.startDate&&c.append("startDate",h.startDate),h.endDate&&c.append("endDate",h.endDate);const C=await(await fetch(`/api/usage/request-details?${c}`)).json();t(C.details||[]),a(m=>({...m,...C.pagination}))}catch(c){console.error("Failed to fetch request details:",c)}finally{o(!1)}},[r.page,r.pageSize,h]);x.useEffect(()=>{L()},[L]),x.useEffect(()=>{O()},[O]);const J=c=>{l(c),p(!0)},G=c=>{a(w=>({...w,page:c}))},W=c=>{a(w=>({...w,pageSize:c,page:1}))},A=()=>{N({provider:"",startDate:"",endDate:""})};return e.jsxs("div",{className:"flex min-w-0 flex-col gap-6",children:[e.jsx(V,{padding:"md",children:e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsxs("div",{className:"flex min-w-0 flex-col gap-2",children:[e.jsx("label",{htmlFor:"provider-filter",className:"text-sm font-medium text-text-main",children:"Provider"}),e.jsxs("select",{id:"provider-filter",value:h.provider,onChange:c=>N({...h,provider:c.target.value}),className:k("h-9 px-3 rounded-lg border border-black/10 dark:border-white/10 bg-surface","text-sm text-text-main focus:outline-none focus:ring-2 focus:ring-primary/20","w-full min-w-0 cursor-pointer"),style:{colorScheme:"auto"},children:[e.jsx("option",{value:"",children:"All Providers"}),j.map(c=>e.jsx("option",{value:c.id,children:c.name},c.id))]})]}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-2",children:[e.jsx("label",{htmlFor:"start-date-filter",className:"text-sm font-medium text-text-main",children:"Start Date"}),e.jsx("input",{id:"start-date-filter",type:"datetime-local",value:h.startDate,onChange:c=>N({...h,startDate:c.target.value}),className:k("h-9 px-3 rounded-lg border border-black/10 dark:border-white/10 bg-surface","w-full min-w-0 text-sm text-text-main focus:outline-none focus:ring-2 focus:ring-primary/20")})]}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-2",children:[e.jsx("label",{htmlFor:"end-date-filter",className:"text-sm font-medium text-text-main",children:"End Date"}),e.jsx("input",{id:"end-date-filter",type:"datetime-local",value:h.endDate,onChange:c=>N({...h,endDate:c.target.value}),className:k("h-9 px-3 rounded-lg border border-black/10 dark:border-white/10 bg-surface","w-full min-w-0 text-sm text-text-main focus:outline-none focus:ring-2 focus:ring-primary/20")})]}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-2 sm:col-span-2 lg:col-span-1",children:[e.jsx("span",{className:"hidden text-sm font-medium text-text-main opacity-0 lg:block","aria-hidden":"true",children:"Clear"}),e.jsx(q,{variant:"ghost",onClick:A,disabled:!h.provider&&!h.startDate&&!h.endDate,className:"w-full",children:"Clear Filters"})]})]})}),e.jsxs(V,{padding:"none",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[880px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-black/5 dark:border-white/5",children:[e.jsx("th",{className:"text-left p-4 text-sm font-semibold text-text-main",children:"Timestamp"}),e.jsx("th",{className:"text-left p-4 text-sm font-semibold text-text-main",children:"Model"}),e.jsx("th",{className:"text-left p-4 text-sm font-semibold text-text-main",children:"Provider"}),e.jsx("th",{className:"text-right p-4 text-sm font-semibold text-text-main",children:"Input Tokens"}),e.jsx("th",{className:"text-right p-4 text-sm font-semibold text-text-main",children:"Output Tokens"}),e.jsx("th",{className:"text-left p-4 text-sm font-semibold text-text-main",children:"Latency"}),e.jsx("th",{className:"text-center p-4 text-sm font-semibold text-text-main",children:"Action"})]})}),e.jsx("tbody",{children:i?e.jsx("tr",{children:e.jsx("td",{colSpan:"7",className:"p-8 text-center text-text-muted",children:e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-[20px]",children:"progress_activity"}),"Loading..."]})})}):s.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:"7",className:"p-8 text-center text-text-muted",children:"No request details found"})}):s.map((c,w)=>{var C,m,v,d;return e.jsxs("tr",{className:"border-b border-black/5 dark:border-white/5 last:border-b-0 hover:bg-black/[0.02] dark:hover:bg-white/[0.02] transition-colors",children:[e.jsx("td",{className:"whitespace-nowrap p-4 text-sm text-text-main",children:new Date(c.timestamp).toLocaleString()}),e.jsx("td",{className:"max-w-[260px] truncate p-4 font-mono text-sm text-text-main",children:c.model}),e.jsx("td",{className:"max-w-[180px] truncate p-4 text-sm text-text-main",children:e.jsx("span",{className:"font-medium",children:ee(c.provider,P)})}),e.jsx("td",{className:"p-4 text-sm text-text-main text-right font-mono",children:te(c.tokens).toLocaleString()}),e.jsx("td",{className:"p-4 text-sm text-text-main text-right font-mono",children:((m=(C=c.tokens)==null?void 0:C.completion_tokens)==null?void 0:m.toLocaleString())||0}),e.jsx("td",{className:"p-4 text-sm text-text-muted",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{children:["TTFT: ",e.jsxs("span",{className:"font-mono",children:[((v=c.latency)==null?void 0:v.ttft)||0,"ms"]})]}),e.jsxs("div",{children:["Total: ",e.jsxs("span",{className:"font-mono",children:[((d=c.latency)==null?void 0:d.total)||0,"ms"]})]})]})}),e.jsx("td",{className:"p-4 text-center",children:e.jsx(q,{variant:"outline",size:"sm",onClick:()=>J(c),children:"Detail"})})]},`${c.id}-${w}`)})})]})}),!i&&s.length>0&&e.jsx("div",{className:"border-t border-black/5 dark:border-white/5",children:e.jsx(Se,{currentPage:r.page,pageSize:r.pageSize,totalItems:r.totalItems,onPageChange:G,onPageSizeChange:W})})]}),e.jsx(ke,{isOpen:b,onClose:()=>p(!1),title:"Request Details",width:"lg",children:n&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-4 text-sm sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"ID:"})," ",e.jsx("span",{className:"break-all font-mono text-text-main",children:n.id})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Timestamp:"})," ",e.jsx("span",{className:"text-text-main",children:new Date(n.timestamp).toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Provider:"})," ",e.jsx("span",{className:"text-text-main font-medium",children:ee(n.provider,P)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Model:"})," ",e.jsx("span",{className:"text-text-main font-mono",children:n.model})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Status:"})," ",e.jsx("span",{className:k("font-medium",n.status==="success"?"text-green-600":"text-red-600"),children:n.status})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Latency:"})," ",e.jsxs("span",{className:"text-text-main font-mono",children:["TTFT ",((T=n.latency)==null?void 0:T.ttft)||0,"ms / Total ",((F=n.latency)==null?void 0:F.total)||0,"ms"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Input Tokens:"})," ",e.jsx("span",{className:"text-text-main font-mono",children:te(n.tokens).toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Output Tokens:"})," ",e.jsx("span",{className:"text-text-main font-mono",children:((S=($=n.tokens)==null?void 0:$.completion_tokens)==null?void 0:S.toLocaleString())||0})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(B,{title:"1. Client Request (Input)",defaultOpen:!0,icon:"input",children:e.jsx("pre",{className:"max-h-[300px] max-w-full overflow-auto rounded-lg border border-black/5 bg-black/5 p-3 font-mono text-xs text-text-main dark:border-white/5 dark:bg-white/5 sm:p-4",children:JSON.stringify(n.request,null,2)})}),n.providerRequest&&e.jsx(B,{title:"2. Provider Request (Translated)",icon:"translate",children:e.jsx("pre",{className:"max-h-[300px] max-w-full overflow-auto rounded-lg border border-black/5 bg-black/5 p-3 font-mono text-xs text-text-main dark:border-white/5 dark:bg-white/5 sm:p-4",children:JSON.stringify(n.providerRequest,null,2)})}),n.providerResponse&&e.jsx(B,{title:"3. Provider Response (Raw)",icon:"data_object",children:e.jsx("pre",{className:"max-h-[300px] max-w-full overflow-auto rounded-lg border border-black/5 bg-black/5 p-3 font-mono text-xs text-text-main dark:border-white/5 dark:bg-white/5 sm:p-4",children:typeof n.providerResponse=="object"?JSON.stringify(n.providerResponse,null,2):n.providerResponse})}),e.jsxs(B,{title:"4. Client Response (Final)",defaultOpen:!0,icon:"output",children:[((R=n.response)==null?void 0:R.thinking)&&e.jsxs("div",{className:"mb-4",children:[e.jsxs("h4",{className:"font-semibold text-text-main mb-2 flex items-center gap-2 text-xs uppercase tracking-wide opacity-70",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"psychology"}),"Thinking Process"]}),e.jsx("pre",{className:"max-h-[200px] max-w-full overflow-auto rounded-lg border border-amber-200 bg-amber-50 p-3 font-mono text-xs text-amber-900 dark:border-amber-800 dark:bg-amber-950/30 dark:text-amber-100 sm:p-4",children:n.response.thinking})]}),e.jsx("h4",{className:"font-semibold text-text-main mb-2 text-xs uppercase tracking-wide opacity-70",children:"Content"}),e.jsx("pre",{className:"max-h-[300px] max-w-full overflow-auto rounded-lg border border-black/5 bg-black/5 p-3 font-mono text-xs text-text-main dark:border-white/5 dark:bg-white/5 sm:p-4",children:((E=n.response)==null?void 0:E.content)||"[No content]"})]})]})]})})]})}const Te=[{value:"today",label:"Today"},{value:"24h",label:"24h"},{value:"7d",label:"7D"},{value:"30d",label:"30D"},{value:"60d",label:"60D"}];function Ee(){return e.jsx(x.Suspense,{fallback:e.jsx(ae,{}),children:e.jsx(Pe,{})})}function Pe(){const[s]=re(),t=se(),[r,a]=x.useState("today"),i=s.get("tab"),o=i&&["overview","logs","details"].includes(i)?i:"overview",n=l=>{if(l===o)return;const b=new URLSearchParams(s);b.set("tab",l),t(`/dashboard/usage?${b.toString()}`,{scroll:!1})};return e.jsxs("div",{className:"flex min-w-0 flex-col gap-6 px-1 sm:px-0",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx(Z,{options:[{value:"overview",label:"Overview"},{value:"details",label:"Details"}],value:o,onChange:n,className:"w-full sm:w-auto"}),o==="overview"&&e.jsx(Z,{options:Te,value:r,onChange:a,size:"sm",className:"w-full sm:w-auto"})]}),o==="overview"&&e.jsx(x.Suspense,{fallback:e.jsx(ae,{}),children:e.jsx(Ne,{period:r,setPeriod:a,hidePeriodSelector:!0})}),o==="logs"&&e.jsx(we,{}),o==="details"&&e.jsx(De,{})]})}export{Ee as default};
@@ -0,0 +1 @@
1
+ import{J as m,j as e,B as p}from"./index.AIBoioDI.js";import{b as l}from"./router.Cjj1--8t.js";import{C as f}from"./NoAuthProxyCard.CZTUlj4t.js";import"./zustand.akaTi5uX.js";const g={LOG:"text-green-400",INFO:"text-blue-400",WARN:"text-yellow-400",ERROR:"text-red-400",DEBUG:"text-purple-400"};function h(n){var s;const o=n.match(/\[(\w+)\]/g),u=o?(s=o[1])==null?void 0:s.replace(/\[|\]/g,""):null,c=g[u]||"text-green-400";return e.jsx("span",{className:c,children:n})}function j(){const[n,o]=l.useState([]),[u,c]=l.useState(!1),s=l.useRef(null),d=async()=>{try{await fetch("/api/translator/console-logs",{method:"DELETE"})}catch(t){console.error("Failed to clear console logs:",t)}};return l.useEffect(()=>{const t=new EventSource("/api/translator/console-logs/stream");return t.onopen=()=>c(!0),t.onmessage=a=>{const r=JSON.parse(a.data);r.type==="init"?o(r.logs.slice(-200)):r.type==="line"?o(x=>{const i=[...x,r.line];return i.length>m.maxLines?i.slice(-200):i}):r.type==="clear"&&o([])},t.onerror=()=>c(!1),()=>t.close()},[]),l.useEffect(()=>{s.current&&(s.current.scrollTop=s.current.scrollHeight)},[n]),e.jsx("div",{className:"",children:e.jsxs(f,{children:[e.jsx("div",{className:"flex items-center justify-end px-4 pt-3 pb-2",children:e.jsx(p,{size:"sm",variant:"outline",icon:"delete",onClick:d,children:"Clear"})}),e.jsx("div",{ref:s,className:"bg-black rounded-b-lg p-4 text-xs font-mono h-[calc(100vh-220px)] overflow-y-auto",children:n.length===0?e.jsx("span",{className:"text-text-muted",children:"No console logs yet."}):e.jsx("div",{className:"space-y-0.5",children:n.map((t,a)=>e.jsx("div",{children:h(t)},a))})})]})})}const N="force-dynamic";function O(){return e.jsx(j,{})}export{O as default,N as dynamic};
@@ -0,0 +1,5 @@
1
+ import{j as e,N as pe,y as fe,B as A,P as be,g as ge}from"./index.AIBoioDI.js";import{h as je,d as we,b as c,L as ve}from"./router.Cjj1--8t.js";import{C as S,I as ye,T as Ne,M as ke}from"./NoAuthProxyCard.CZTUlj4t.js";import"./zustand.akaTi5uX.js";function Se(o){if(typeof o!="string")return{providerId:"",model:""};const g=o.indexOf("/");return g<0?{providerId:o,model:""}:{providerId:o.slice(0,g),model:o.slice(g+1)}}const Re=/^[a-zA-Z0-9_.\-]+$/,Ee={webSearch:"Web Search",webFetch:"Web Fetch",image:"Text to Image",tts:"Text To Speech"},V={webSearch:"/v1/search",webFetch:"/v1/web/fetch",image:"/v1/images/generations",tts:"/v1/audio/speech"},L={webSearch:o=>({model:o,query:"What is the latest news about AI?",search_type:"web",max_results:5}),webFetch:o=>({model:o,url:"https://example.com",format:"markdown"}),image:o=>({model:o,prompt:"A cute cat playing piano",n:1,size:"1024x1024"}),tts:o=>({model:o,input:"Hello, this is a test.",voice:"alloy"})};function X(o){return o==="webSearch"||o==="webFetch"?"/dashboard/media-providers/web":`/dashboard/media-providers/${o}`}function Le(){var K;const{id:o}=je(),g=we(),[r,P]=c.useState(null),[q,O]=c.useState(!0),[N,_]=c.useState(""),[G,R]=c.useState(""),[m,j]=c.useState([]),[Y,$]=c.useState(!1),[Z,M]=c.useState(!1),[D,Q]=c.useState([]),[I,B]=c.useState(!1),[l,w]=c.useState(null),[z,E]=c.useState(""),[U,ee]=c.useState(""),[te,se]=c.useState([]),[ae,ne]=c.useState({}),H=async()=>{var t,s,a;try{const[n,i,k,y,x,p]=await Promise.all([fetch(`/api/combos/${o}`,{cache:"no-store"}),fetch("/api/settings",{cache:"no-store"}),fetch("/api/usage/logs",{cache:"no-store"}),fetch("/api/keys",{cache:"no-store"}),fetch("/api/providers",{cache:"no-store"}),fetch("/api/models/alias",{cache:"no-store"})]);if(p.ok&&ne((await p.json()).aliases||{}),y.ok){const b=await y.json();ee(((t=(b.keys||[]).find(d=>d.isActive!==!1))==null?void 0:t.key)||"")}if(x.ok&&se((await x.json()).connections||[]),!n.ok){P(null),O(!1);return}const h=await n.json();P(h),_(h.name),j(h.models||[]);const f=i.ok?await i.json():{};$(((a=(s=f.comboStrategies)==null?void 0:s[h.name])==null?void 0:a.fallbackStrategy)==="round-robin");const u=k.ok?await k.json():[];Q(u.filter(b=>typeof b=="string"&&b.includes(h.name)).slice(0,50))}catch{}O(!1)};c.useEffect(()=>{H()},[o]);const F=t=>t.trim()?Re.test(t)?(R(""),!0):(R("Only letters, numbers, -, _ and ."),!1):(R("Name is required"),!1),v=async t=>{const s=await fetch(`/api/combos/${o}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const a=await s.json();return alert(a.error||"Failed to save"),!1}return!0},oe=async()=>{if(!F(N)||N===r.name)return;await v({name:N})&&await H()},re=async t=>{const s=(t==null?void 0:t.value)||t;if(!s||m.includes(s))return;const a=[...m,s];j(a),await v({models:a})},le=async t=>{const s=(t==null?void 0:t.value)||t;if(!s||!m.includes(s))return;const a=m.filter(n=>n!==s);j(a),await v({models:a})},ie=async t=>{const s=m.filter((a,n)=>n!==t);j(s),await v({models:s})},J=async(t,s)=>{const a=[...m],n=t+s;n<0||n>=a.length||([a[t],a[n]]=[a[n],a[t]],j(a),await v({models:a}))},ce=async t=>{$(t);const s=await fetch("/api/settings",{cache:"no-store"}),n={...(s.ok?await s.json():{}).comboStrategies||{}};t?n[r.name]={fallbackStrategy:"round-robin"}:delete n[r.name],await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({comboStrategies:n})})},de=async()=>{if(!confirm(`Delete combo "${r.name}"?`))return;(await fetch(`/api/combos/${o}`,{method:"DELETE"})).ok&&g(X(r.kind))},me=async()=>{var s,a,n;if(B(!0),w(null),E(""),l!=null&&l.audioUrl)try{URL.revokeObjectURL(l.audioUrl)}catch{}if((s=l==null?void 0:l.imageUrl)!=null&&s.startsWith("blob:"))try{URL.revokeObjectURL(l.imageUrl)}catch{}const t=Date.now();try{const i=V[r.kind],k=L[r.kind](r.name),y={"Content-Type":"application/json"};U&&(y.Authorization=`Bearer ${U}`);const x=await fetch(`/api${i}`,{method:"POST",headers:y,body:JSON.stringify(k)}),p=Date.now()-t;if(!x.ok){const d=await x.json().catch(()=>({}));E(((a=d==null?void 0:d.error)==null?void 0:a.message)||(d==null?void 0:d.error)||`HTTP ${x.status}`),w({json:JSON.stringify(d,null,2),latencyMs:p});return}const h=x.headers.get("content-type")||"";if(h.startsWith("image/")){const d=await x.blob();w({imageUrl:URL.createObjectURL(d),latencyMs:p});return}if(h.startsWith("audio/")||h==="application/octet-stream"){const d=await x.blob();w({audioUrl:URL.createObjectURL(d),latencyMs:p});return}const f=await x.json(),u=(n=f==null?void 0:f.data)==null?void 0:n[0],b=u!=null&&u.b64_json?`data:image/png;base64,${u.b64_json}`:(u==null?void 0:u.url)||"";w({json:JSON.stringify(C(f),null,2),imageUrl:b,latencyMs:p})}catch(i){E(i.message||"Network error")}B(!1)};function C(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(C);const s={};for(const[a,n]of Object.entries(t))s[a]=a==="b64_json"&&typeof n=="string"&&n.length>100?`<${n.length} chars base64>`:C(n);return s}if(q)return e.jsx("div",{className:"text-text-muted text-sm",children:"Loading..."});if(!r)return null;const W=Ee[r.kind]||((K=pe.find(t=>t.id===r.kind))==null?void 0:K.label)||"Combo",T=V[r.kind],xe=r.kind&&L[r.kind]?L[r.kind](r.name):null,he=T?`curl -X POST ${fe()}${T} \\
2
+ -H "Content-Type: application/json" \\
3
+ -H "Authorization: Bearer ${U||"YOUR_KEY"}" \\
4
+ -d '${JSON.stringify(xe)}'`:"",ue=X(r.kind);return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(ve,{to:ue,className:"text-text-muted hover:text-primary",children:e.jsx("span",{className:"material-symbols-outlined",children:"arrow_back"})}),e.jsx("div",{className:"size-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx("span",{className:"material-symbols-outlined text-primary",children:"layers"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"text-xs text-text-muted",children:[W," Combo"]}),e.jsx("code",{className:"text-lg font-semibold font-mono",children:r.name})]})]}),e.jsx(A,{variant:"outline",icon:"delete",onClick:de,className:"text-red-500 border-red-200 hover:bg-red-50",children:"Delete"})]}),e.jsxs(S,{children:[e.jsx("h2",{className:"text-lg font-semibold mb-3",children:"Settings"}),e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{children:[e.jsx(ye,{label:"Combo Name",value:N,onChange:t=>{_(t.target.value),F(t.target.value)},onBlur:oe,error:G}),e.jsx("p",{className:"text-[10px] text-text-muted mt-0.5",children:"Only letters, numbers, -, _ and ."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Round Robin"}),e.jsx("p",{className:"text-xs text-text-muted",children:"Rotate providers across requests instead of strict fallback order."})]}),e.jsx(Ne,{checked:Y,onChange:ce})]})]})]}),e.jsxs(S,{children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Providers"}),e.jsx("p",{className:"text-xs text-text-muted",children:"Tried in order (top-down) or rotated when round-robin is on."})]}),e.jsx(A,{size:"sm",icon:"add",onClick:()=>M(!0),children:"Add Provider"})]}),m.length===0?e.jsx("div",{className:"text-center py-6 border border-dashed border-border rounded-lg text-text-muted text-sm",children:"No providers yet."}):e.jsx("div",{className:"flex flex-col gap-2",children:m.map((t,s)=>{const{providerId:a,model:n}=Se(t),i=ge[a];return e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg bg-black/[0.02] dark:bg-white/[0.02]",children:[e.jsx("span",{className:"text-xs text-text-muted w-5 text-center",children:s+1}),e.jsx(be,{src:`/providers/${a}.png`,alt:(i==null?void 0:i.name)||a,size:24,className:"object-contain rounded shrink-0",fallbackText:(i==null?void 0:i.textIcon)||a.slice(0,2).toUpperCase(),fallbackColor:i==null?void 0:i.color}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:(i==null?void 0:i.name)||a}),n&&e.jsx("code",{className:"text-[10px] text-text-muted font-mono truncate block",children:n})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx("button",{onClick:()=>J(s,-1),disabled:s===0,className:`p-1 rounded ${s===0?"text-text-muted/20":"text-text-muted hover:text-primary hover:bg-black/5"}`,title:"Move up",children:e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"arrow_upward"})}),e.jsx("button",{onClick:()=>J(s,1),disabled:s===m.length-1,className:`p-1 rounded ${s===m.length-1?"text-text-muted/20":"text-text-muted hover:text-primary hover:bg-black/5"}`,title:"Move down",children:e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"arrow_downward"})}),e.jsx("button",{onClick:()=>ie(s),className:"p-1 rounded text-text-muted hover:text-red-500 hover:bg-red-500/10",title:"Remove",children:e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"close"})})]})]},`${t}-${s}`)})})]}),r.kind&&T&&e.jsxs(S,{children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between mb-3",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Test Example"}),e.jsx(A,{size:"sm",icon:"play_arrow",onClick:me,disabled:I||m.length===0,children:I?"Running...":"Run"})]}),e.jsx("pre",{className:"text-xs font-mono bg-black/[0.03] dark:bg-white/[0.03] p-3 rounded-lg overflow-x-auto whitespace-pre-wrap break-all",children:he}),z&&e.jsx("p",{className:"mt-3 text-xs text-red-500 break-words",children:z}),l&&e.jsxs("div",{className:"mt-3 flex flex-col gap-3",children:[l.latencyMs!=null&&e.jsxs("span",{className:"text-[11px] text-text-muted",children:["⚡ ",l.latencyMs,"ms"]}),l.imageUrl&&e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center justify-end mb-1.5",children:e.jsxs("a",{href:l.imageUrl,download:"image.png",className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"download"}),"Download"]})}),e.jsx("img",{src:l.imageUrl,alt:"Generated",className:"max-w-full rounded-lg border border-border"})]}),l.audioUrl&&e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center justify-end mb-1.5",children:e.jsxs("a",{href:l.audioUrl,download:"speech.mp3",className:"inline-flex items-center gap-1 text-xs text-text-muted hover:text-primary transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"download"}),"Download"]})}),e.jsx("audio",{controls:!0,src:l.audioUrl,className:"w-full"})]}),l.json&&e.jsx("pre",{className:"text-xs font-mono bg-black/[0.03] dark:bg-white/[0.03] p-3 rounded-lg overflow-auto max-h-[300px] whitespace-pre-wrap break-all",children:l.json})]})]}),e.jsxs(S,{children:[e.jsx("h2",{className:"text-lg font-semibold mb-3",children:"Usage Logs"}),D.length===0?e.jsx("p",{className:"text-xs text-text-muted italic",children:"No usage yet."}):e.jsx("pre",{className:"text-[11px] font-mono bg-black/[0.03] dark:bg-white/[0.03] p-3 rounded-lg overflow-auto max-h-[400px] whitespace-pre-wrap",children:D.join(`
5
+ `)})]}),e.jsx(ke,{isOpen:Z,onClose:()=>M(!1),onSelect:re,onDeselect:le,activeProviders:te,modelAliases:ae,title:`Add ${W} Model`,kindFilter:r.kind,addedModelValues:m,closeOnSelect:!1})]})}export{Le as default};
@@ -0,0 +1 @@
1
+ import{j as e}from"./index.AIBoioDI.js";import{b as n}from"./router.Cjj1--8t.js";import"./zustand.akaTi5uX.js";function j(){const[o,p]=n.useState("tts"),[x,h]=n.useState(""),[t,s]=n.useState(null),[i,r]=n.useState(!1),u=async()=>{r(!0);try{const a=await fetch("/api/audio/speech",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:x,model:"tts-1",voice:"alloy"})});if(a.ok){const c=await a.blob();s({audio:URL.createObjectURL(c)})}else s({error:await a.text()})}catch(a){s({error:a.message})}r(!1)},m=async a=>{const c=a.target.files[0];if(!c)return;r(!0);const l=new FormData;l.append("file",c),l.append("model","whisper-1");try{const d=await fetch("/api/audio/transcriptions",{method:"POST",body:l});s(await d.json())}catch(d){s({error:d.message})}r(!1)};return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Audio"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>p("tts"),className:`px-4 py-2 rounded-lg ${o==="tts"?"bg-primary text-white":"bg-black/5"}`,children:"Text to Speech"}),e.jsx("button",{onClick:()=>p("stt"),className:`px-4 py-2 rounded-lg ${o==="stt"?"bg-primary text-white":"bg-black/5"}`,children:"Speech to Text"})]}),o==="tts"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("textarea",{className:"w-full p-3 rounded-lg border h-40",placeholder:"Enter text to convert to speech...",value:x,onChange:a=>h(a.target.value)}),e.jsx("button",{onClick:u,disabled:i,className:"px-4 py-2 bg-primary text-white rounded-lg",children:i?"Generating...":"Generate Speech"}),(t==null?void 0:t.audio)&&e.jsx("audio",{controls:!0,src:t.audio,className:"w-full"})]}),o==="stt"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("input",{type:"file",accept:"audio/*",onChange:m,className:"block"}),i&&e.jsx("p",{children:"Transcribing..."})]}),(t==null?void 0:t.error)&&e.jsx("p",{className:"text-red-500",children:t.error}),(t==null?void 0:t.text)&&e.jsx("pre",{className:"p-4 bg-black/5 rounded-lg text-sm",children:t.text})]})}export{j as default};
@@ -0,0 +1 @@
1
+ import{j as e}from"./index.AIBoioDI.js";import{b as s}from"./router.Cjj1--8t.js";import"./zustand.akaTi5uX.js";function A(){const[a,y]=s.useState({currentVersion:"",latestVersion:"",hasUpdate:!1}),[k,b]=s.useState(!0),[f,i]=s.useState(!1),[c,g]=s.useState(0),[S,o]=s.useState(""),[m,h]=s.useState([]),[j,r]=s.useState(""),x=s.useRef(null),v=async()=>{try{b(!0);const n=await(await fetch("/api/version")).json();y(n)}catch(t){console.error(t),r("Gagal memuat informasi versi.")}finally{b(!1)}};s.useEffect(()=>{v()},[]),s.useEffect(()=>{x.current&&x.current.scrollIntoView({behavior:"smooth"})},[m]);const w=async()=>{if(window.confirm("Apakah Anda yakin ingin memulai update otomatis?")){i(!0),g(0),h([]),o("Menghubungi server untuk memulai update..."),r("");try{const n=await(await fetch("/api/version/update",{method:"POST"})).json();if(n.success){const d=new EventSource("/api/version/update");d.onmessage=u=>{const l=JSON.parse(u.data);if(g(l.progress||0),h(l.logs||[]),l.status==="updating")o(`Sedang memproses update... (${l.progress}%)`);else if(l.status==="done"||l.progress===100){d.close(),o("Update berhasil diselesaikan! Server sedang merestart...");let p=0;const N=setInterval(async()=>{p++,o(`Menunggu server online kembali... (Mencoba menghubungkan: ${p}s)`);try{(await fetch("/api/health")).ok&&(clearInterval(N),o("Update Selesai! Halaman akan dimuat ulang..."),setTimeout(()=>{window.location.reload()},1500))}catch{}p>90&&(clearInterval(N),i(!1),r("Server memakan waktu terlalu lama untuk online kembali. Silakan periksa status PM2 Anda secara manual."))},2e3)}},d.onerror=u=>{console.error("EventSource error:",u),c>80?d.close():(d.close(),r("Koneksi ke server terputus saat proses update berjalan."),i(!1))}}else r(n.message||"Gagal memulai update otomatis."),i(!1)}catch(t){console.error(t),r("Koneksi gagal saat memulai update."),i(!1)}}};return e.jsxs("div",{className:"max-w-4xl mx-auto p-4 space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("h1",{className:"text-2xl font-bold text-text-main flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-[28px] text-primary",children:"system_update"}),"FSRouter System Update"]}),e.jsx("p",{className:"text-xs text-text-muted",children:"Kelola dan perbarui versi FSRouter Anda langsung dari repositori GitHub atau NPM registry."})]}),k?e.jsx("div",{className:"flex items-center justify-center p-12 border border-border-subtle rounded-[14px] bg-surface",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx("span",{className:"material-symbols-outlined text-4xl animate-spin text-primary",children:"sync"}),e.jsx("span",{className:"text-sm text-text-muted",children:"Memuat informasi versi..."})]})}):e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"p-6 rounded-[14px] border border-border-subtle bg-surface flex flex-col gap-4",children:[e.jsx("h2",{className:"text-sm font-semibold text-text-main",children:"Detail Versi"}),e.jsxs("div",{className:"flex items-center justify-between border-b border-border-subtle pb-3",children:[e.jsx("span",{className:"text-xs text-text-muted",children:"Versi Saat Ini"}),e.jsxs("span",{className:"text-sm font-mono font-semibold text-text-main",children:["v",a.currentVersion||"0.0.0"]})]}),e.jsxs("div",{className:"flex items-center justify-between border-b border-border-subtle pb-3",children:[e.jsx("span",{className:"text-xs text-text-muted",children:"Versi Terbaru di GitHub"}),e.jsxs("span",{className:"text-sm font-mono font-semibold text-text-main",children:["v",a.latestVersion||"0.0.0"]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-text-muted",children:"Status"}),a.hasUpdate?e.jsx("span",{className:"px-2 py-0.5 rounded-full text-[10px] font-semibold bg-amber-500/10 text-amber-500 border border-amber-500/20",children:"Update Tersedia"}):e.jsx("span",{className:"px-2 py-0.5 rounded-full text-[10px] font-semibold bg-green-500/10 text-green-500 border border-green-500/20",children:"Versi Terbaru"})]})]}),e.jsxs("div",{className:"p-6 rounded-[14px] border border-border-subtle bg-surface flex flex-col justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h2",{className:"text-sm font-semibold text-text-main",children:"Aksi Pembaruan"}),e.jsx("p",{className:"text-xs text-text-muted leading-relaxed",children:a.hasUpdate?"Versi baru tersedia! Update otomatis akan menginstal versi terbaru, memperbarui dependensi, membangun ulang kode, dan me-restart server FSRouter Anda secara mulus.":"FSRouter Anda sudah menggunakan versi terbaru. Tidak ada pembaruan yang diperlukan saat ini."})]}),f?e.jsxs("div",{className:"p-4 rounded-lg bg-primary/5 border border-primary/20 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold text-primary",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px] animate-spin",children:"sync"}),"Proses Update Sedang Berjalan: ",c,"%"]}),e.jsx("div",{className:"w-full bg-border-subtle rounded-full h-2.5 overflow-hidden",children:e.jsx("div",{className:"bg-primary h-2.5 rounded-full transition-all duration-500",style:{width:`${c}%`}})}),e.jsx("p",{className:"text-[11px] text-text-muted leading-relaxed",children:S})]}):e.jsxs("div",{className:"space-y-2",children:[j&&e.jsx("p",{className:"text-xs text-red-500 font-semibold bg-red-500/10 border border-red-500/20 p-3 rounded-lg",children:j}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{disabled:!a.hasUpdate,onClick:w,className:`flex-1 py-2 px-4 rounded-lg text-xs font-semibold text-white transition-colors flex items-center justify-center gap-2 ${a.hasUpdate?"bg-primary hover:bg-primary/90 cursor-pointer":"bg-border-subtle text-text-muted cursor-not-allowed"}`,children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"download"}),"Otomatis Update Sekarang"]}),e.jsx("button",{onClick:v,className:"py-2 px-3 rounded-lg border border-border-subtle text-text-main text-xs hover:bg-surface-2 transition-colors cursor-pointer",title:"Periksa Ulang",children:e.jsx("span",{className:"material-symbols-outlined text-[16px] block",children:"refresh"})})]})]})]})]}),f&&m.length>0&&e.jsxs("div",{className:"p-4 rounded-[14px] border border-border-subtle bg-black text-green-400 font-mono text-xs overflow-hidden flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between pb-2 border-b border-green-900/50",children:[e.jsxs("span",{className:"text-green-500 font-semibold flex items-center gap-1.5",children:[e.jsx("span",{className:"size-2 rounded-full bg-green-500 animate-pulse"}),"Logs Konsol Pembaruan"]}),e.jsx("span",{className:"text-[10px] text-green-600",children:"FSRouter Updater"})]}),e.jsxs("div",{className:"max-h-[300px] overflow-y-auto space-y-1 custom-scrollbar",children:[m.map((t,n)=>e.jsx("pre",{className:"whitespace-pre-wrap leading-relaxed break-all font-mono",children:t},n)),e.jsx("div",{ref:x})]})]})]})}export{A as default};
package/public/index.html CHANGED
@@ -10,10 +10,10 @@
10
10
  <link rel="preconnect" href="https://fonts.googleapis.com" />
11
11
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
12
12
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet" />
13
- <script type="module" crossorigin src="/assets/index.2a3mqmx-.js?v=100"></script>
14
- <link rel="modulepreload" crossorigin href="/assets/router.Cjj1--8t.js?v=100">
15
- <link rel="modulepreload" crossorigin href="/assets/zustand.akaTi5uX.js?v=100">
16
- <link rel="stylesheet" crossorigin href="/assets/index.Blvwx0HS.css?v=100">
13
+ <script type="module" crossorigin src="/assets/index.AIBoioDI.js?v=106"></script>
14
+ <link rel="modulepreload" crossorigin href="/assets/router.Cjj1--8t.js?v=106">
15
+ <link rel="modulepreload" crossorigin href="/assets/zustand.akaTi5uX.js?v=106">
16
+ <link rel="stylesheet" crossorigin href="/assets/index.C--zNQ3O.css?v=106">
17
17
  </head>
18
18
  <body>
19
19
  <div id="root"></div>