@cuadra-ai/uikit 0.4.13 → 0.4.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,23 +1,23 @@
1
- "use strict";var br=Object.defineProperty;var wr=(e,t,r)=>t in e?br(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var z=(e,t,r)=>wr(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("react/jsx-runtime"),y=require("react"),T=require("@assistant-ui/react");require("@assistant-ui/react-markdown/styles/dot.css");const qe=require("@assistant-ui/react-markdown");var fe=typeof document<"u"?document.currentScript:null;let xe=!1,it=!1;function st(){if(it||(it=!0,typeof document>"u"||typeof window>"u"))return;const e=document.querySelector("link[data-cuadra-uikit-styles]"),t=document.querySelector("style[data-cuadra-uikit-styles]");if(e||t){xe=!0;return}try{const r=document.createElement("div");r.className="cuadra-flex",r.style.visibility="hidden",r.style.position="absolute",r.style.pointerEvents="none",document.body.appendChild(r);const a=window.getComputedStyle(r).display==="flex";if(document.body.removeChild(r),a){xe=!0;return}}catch{}kr()}function kr(){if(xe)return;const e=document.createElement("link");e.setAttribute("data-cuadra-uikit-styles","true"),e.rel="stylesheet",e.type="text/css";try{const t=new URL(typeof document>"u"?require("url").pathToFileURL(__filename).href:fe&&fe.tagName.toUpperCase()==="SCRIPT"&&fe.src||new URL("index.cjs",document.baseURI).href),r=new URL("../dist/uikit.css",t);e.href=r.href}catch{e.href="/node_modules/@cuadra-ai/uikit/dist/uikit.css"}e.onload=()=>{xe=!0},e.onerror=()=>{const t=["/node_modules/@cuadra-ai/uikit/dist/uikit.css","https://unpkg.com/@cuadra-ai/uikit@latest/dist/uikit.css"];let r=0;const a=()=>{r<t.length&&(e.href=t[r++],e.onerror=a,e.onload=()=>{xe=!0})};a()},document.head.appendChild(e)}typeof document<"u"&&typeof window<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",st):st());const Cr=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),vr=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,r,a)=>a?a.toUpperCase():r.toLowerCase()),ot=e=>{const t=vr(e);return t.charAt(0).toUpperCase()+t.slice(1)},St=(...e)=>e.filter((t,r,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===r).join(" ").trim(),Tr=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var jr={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Sr=y.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:a,className:n="",children:s,iconNode:i,...c},o)=>y.createElement("svg",{ref:o,...jr,width:t,height:t,stroke:e,strokeWidth:a?Number(r)*24/Number(t):r,className:St("lucide",n),...!s&&!Tr(c)&&{"aria-hidden":"true"},...c},[...i.map(([l,f])=>y.createElement(l,f)),...Array.isArray(s)?s:[s]]));const B=(e,t)=>{const r=y.forwardRef(({className:a,...n},s)=>y.createElement(Sr,{ref:s,iconNode:t,className:St(`lucide-${Cr(ot(e))}`,`lucide-${e}`,a),...n}));return r.displayName=ot(e),r};const Ir=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Mr=B("arrow-up",Ir);const Ar=[["path",{d:"M12 18V5",key:"adv99a"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4",key:"1e3is1"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5",key:"1gqd8o"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77",key:"iwvgf7"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464",key:"efp6ie"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517",key:"1gq6am"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464",key:"k1g0md"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77",key:"q97ue3"}]],ct=B("brain",Ar);const Nr=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],It=B("check",Nr);const _r=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Ke=B("chevron-down",_r);const Pr=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],Er=B("circle-alert",Pr);const Rr=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Lr=B("copy",Rr);const Dr=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],lt=B("eye",Dr);const Fr=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]],Ur=B("file-spreadsheet",Fr);const zr=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Mt=B("file-text",zr);const $r=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M11 18h2",key:"12mj7e"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M9 13v-.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 .5.5v.5",key:"qbrxap"}]],Or=B("file-type",$r);const Br=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],At=B("loader-circle",Br);const qr=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],Nt=B("paperclip",qr);const Vr=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],Wr=B("pencil",Vr);const Hr=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],_t=B("plus",Hr);const Kr=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Qr=B("trash-2",Kr);const Gr=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],Yr=B("upload",Gr);const Jr=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],ut=B("x",Jr),Xr=[/\[INST\]/gi,/\[\/INST\]/gi,/<<SYS>>/gi,/<<\/SYS>>/gi,/<\|.*?\|>/g,/<\|im_start\|>/gi,/<\|im_end\|>/gi,/\[HUMAN\]/gi,/\[ASSISTANT\]/gi,/^(system|user|assistant):\s*/gim];function Zr(e){if(!e||typeof e!="string")return"";let t=e;for(const r of Xr)t=t.replace(r,"");return t=t.replace(/\n{3,}/g,`
1
+ "use strict";var Cr=Object.defineProperty;var vr=(e,r,t)=>r in e?Cr(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var z=(e,r,t)=>vr(e,typeof r!="symbol"?r+"":r,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("react/jsx-runtime"),y=require("react"),j=require("@assistant-ui/react");require("@assistant-ui/react-markdown/styles/dot.css");const He=require("@assistant-ui/react-markdown");var me=typeof document<"u"?document.currentScript:null;let ye=!1,lt=!1;function dt(){if(lt||(lt=!0,typeof document>"u"||typeof window>"u"))return;const e=document.querySelector("link[data-cuadra-uikit-styles]"),r=document.querySelector("style[data-cuadra-uikit-styles]");if(e||r){ye=!0;return}try{const t=document.createElement("div");t.className="cuadra-flex",t.style.visibility="hidden",t.style.position="absolute",t.style.pointerEvents="none",document.body.appendChild(t);const a=window.getComputedStyle(t).display==="flex";if(document.body.removeChild(t),a){ye=!0;return}}catch{}jr()}function jr(){if(ye)return;const e=document.createElement("link");e.setAttribute("data-cuadra-uikit-styles","true"),e.rel="stylesheet",e.type="text/css";try{const r=new URL(typeof document>"u"?require("url").pathToFileURL(__filename).href:me&&me.tagName.toUpperCase()==="SCRIPT"&&me.src||new URL("index.cjs",document.baseURI).href),t=new URL("../dist/uikit.css",r);e.href=t.href}catch{e.href="/node_modules/@cuadra-ai/uikit/dist/uikit.css"}e.onload=()=>{ye=!0},e.onerror=()=>{const r=["/node_modules/@cuadra-ai/uikit/dist/uikit.css","https://unpkg.com/@cuadra-ai/uikit@latest/dist/uikit.css"];let t=0;const a=()=>{t<r.length&&(e.href=r[t++],e.onerror=a,e.onload=()=>{ye=!0})};a()},document.head.appendChild(e)}typeof document<"u"&&typeof window<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",dt):dt());const Tr=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Sr=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(r,t,a)=>a?a.toUpperCase():t.toLowerCase()),ht=e=>{const r=Sr(e);return r.charAt(0).toUpperCase()+r.slice(1)},At=(...e)=>e.filter((r,t,a)=>!!r&&r.trim()!==""&&a.indexOf(r)===t).join(" ").trim(),Ir=e=>{for(const r in e)if(r.startsWith("aria-")||r==="role"||r==="title")return!0};var Mr={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Ar=y.forwardRef(({color:e="currentColor",size:r=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:i="",children:s,iconNode:n,...c},o)=>y.createElement("svg",{ref:o,...Mr,width:r,height:r,stroke:e,strokeWidth:a?Number(t)*24/Number(r):t,className:At("lucide",i),...!s&&!Ir(c)&&{"aria-hidden":"true"},...c},[...n.map(([u,m])=>y.createElement(u,m)),...Array.isArray(s)?s:[s]]));const O=(e,r)=>{const t=y.forwardRef(({className:a,...i},s)=>y.createElement(Ar,{ref:s,iconNode:r,className:At(`lucide-${Tr(ht(e))}`,`lucide-${e}`,a),...i}));return t.displayName=ht(e),t};const Nr=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Pr=O("arrow-up",Nr);const _r=[["path",{d:"M12 18V5",key:"adv99a"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4",key:"1e3is1"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5",key:"1gqd8o"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77",key:"iwvgf7"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464",key:"efp6ie"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517",key:"1gq6am"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464",key:"k1g0md"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77",key:"q97ue3"}]],Fe=O("brain",_r);const Er=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Ke=O("check",Er);const Rr=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Xe=O("chevron-down",Rr);const Lr=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],Dr=O("circle-alert",Lr);const Fr=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Ur=O("copy",Fr);const zr=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],$r=O("ellipsis-vertical",zr);const Or=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Ue=O("eye",Or);const Br=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]],qr=O("file-spreadsheet",Br);const Vr=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Nt=O("file-text",Vr);const Wr=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M11 18h2",key:"12mj7e"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M9 13v-.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 .5.5v.5",key:"qbrxap"}]],Hr=O("file-type",Wr);const Kr=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Pt=O("loader-circle",Kr);const Qr=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],Gr=O("message-square",Qr);const Yr=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],_t=O("paperclip",Yr);const Jr=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],Et=O("pencil",Jr);const Xr=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Qe=O("plus",Xr);const Zr=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Rt=O("trash-2",Zr);const ea=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],ta=O("upload",ea);const ra=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Se=O("x",ra),aa=[/\[INST\]/gi,/\[\/INST\]/gi,/<<SYS>>/gi,/<<\/SYS>>/gi,/<\|.*?\|>/g,/<\|im_start\|>/gi,/<\|im_end\|>/gi,/\[HUMAN\]/gi,/\[ASSISTANT\]/gi,/^(system|user|assistant):\s*/gim];function na(e){if(!e||typeof e!="string")return"";let r=e;for(const t of aa)r=r.replace(t,"");return r=r.replace(/\n{3,}/g,`
2
2
 
3
- `).replace(/ {2,}/g," ").trim(),t}function ea(e){if(!e||typeof e!="string")return!1;try{const t=new URL(e);return["http:","https:"].includes(t.protocol)}catch{return!1}}function ta(e){if(!e)return{valid:!1,error:"URL is required"};if(typeof e!="string")return{valid:!1,error:"URL must be a string"};if(e.startsWith("/")||e.startsWith("./"))return{valid:!0};try{const t=new URL(e);return["http:","https:"].includes(t.protocol)?t.protocol==="http:"&&!ra(e)?{valid:!0,parsed:t,error:"Warning: Using HTTP for non-localhost URL. Consider using HTTPS."}:{valid:!0,parsed:t}:{valid:!1,error:`Invalid protocol "${t.protocol}". Only http and https are allowed.`}}catch{return{valid:!1,error:"Invalid URL format"}}}function ra(e){try{const t=new URL(e);return["localhost","127.0.0.1","[::1]"].includes(t.hostname)}catch{return!1}}function aa(e){if(!e||typeof e!="string")return"";const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"};return e.replace(/[&<>"'/]/g,r=>t[r]||r)}function Pt(){if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&crypto.getRandomValues){const e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn("[CuadraUIKit] Using non-cryptographic fallback for UUID generation"),`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`}class Et{constructor(t,r,a=!1){z(this,"baseUrl");z(this,"sessionToken",null);z(this,"isProxyMode",!1);this.baseUrl=t.replace(/\/$/,""),this.isProxyMode=a,r&&(this.sessionToken=r)}setSessionToken(t){this.sessionToken=t}getUrl(t){if(this.isProxyMode){const r=`${this.baseUrl}${t.replace("/v1","")}`;return r.startsWith("/")||r.startsWith("./"),r}return`${this.baseUrl}${t}`}async createOrContinueChat(t,r){const a=this.getUrl("/v1/chats"),s={"Content-Type":"application/json",Accept:"text/event-stream","Accept-Encoding":"identity","Cache-Control":"no-cache","X-Accel-Buffering":"no","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(s.Authorization=`Bearer ${this.sessionToken}`);const i={...t,stream:!0},c=await fetch(a,{method:"POST",headers:s,body:JSON.stringify(i),signal:r,cache:"no-store"});if(!c.ok){const o=await c.json().catch(()=>({}));throw new Error(o.detail||o.message||`API error: ${c.status} ${c.statusText}`)}if(!c.body)throw new Error("Response body is null");return c.body}async getChat(t){const r=this.getUrl(`/v1/chats/${t}`),a={"Content-Type":"application/json"};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const n=await fetch(r,{method:"GET",headers:a});if(!n.ok){const s=await n.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${n.status} ${n.statusText}`)}return n.json()}async listChats(t){const r=this.getUrl("/v1/chats"),a=r.startsWith("/")||r.startsWith("./")?new URL(r,window.location.origin):new URL(r);t?.limit&&a.searchParams.set("limit",t.limit.toString()),t?.cursor&&a.searchParams.set("cursor",t.cursor),t?.["expand[]"]&&t["expand[]"].forEach(i=>{a.searchParams.append("expand[]",i)});const n={"Content-Type":"application/json"};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const s=await fetch(a.toString(),{method:"GET",headers:n});if(!s.ok){const i=await s.json().catch(()=>({}));throw new Error(i.detail||i.message||`API error: ${s.status} ${s.statusText}`)}return s.json()}generateIdempotencyKey(){return Pt()}async updateChat(t,r){const a=`/v1/chats/${t}`,n=this.getUrl(a),s=n.startsWith("/")||n.startsWith("./")?new URL(n,window.location.origin):new URL(n),c={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(c.Authorization=`Bearer ${this.sessionToken}`);const o=await fetch(s.toString(),{method:"PATCH",headers:c,body:JSON.stringify(r)});if(!o.ok){const f=await o.text();let d={};try{d=JSON.parse(f)}catch{d={detail:f}}throw new Error(d.detail||d.message||`API error: ${o.status} ${o.statusText}`)}if(o.status===204)return{};const l=await o.text();if(!l)return{};try{return JSON.parse(l)}catch{return{}}}async deleteChat(t){const r=`/v1/chats/${t}`,a=this.getUrl(r),n=a.startsWith("/")||a.startsWith("./")?new URL(a,window.location.origin):new URL(a),i={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const c=await fetch(n.toString(),{method:"DELETE",headers:i});if(!c.ok){const o=await c.json().catch(()=>({}));throw new Error(o.detail||o.message||`API error: ${c.status} ${c.statusText}`)}}async generateChatTitle(t,r){const a=`/v1/chats/${t}/title`,n=this.getUrl(a),s=n.startsWith("/")||n.startsWith("./")?new URL(n,window.location.origin):new URL(n),c={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(c.Authorization=`Bearer ${this.sessionToken}`);const o=await fetch(s.toString(),{method:"POST",headers:c,body:r?JSON.stringify(r):void 0});if(!o.ok){const l=await o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}return o.json()}async listModels(t){const r=this.getUrl("/v1/models"),a=r.startsWith("/")||r.startsWith("./")?new URL(r,window.location.origin):new URL(r);t?.limit&&a.searchParams.set("limit",t.limit.toString()),t?.cursor&&a.searchParams.set("cursor",t.cursor),t?.["expand[]"]&&t["expand[]"].forEach(i=>{a.searchParams.append("expand[]",i)});const n={"Content-Type":"application/json"};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const s=await fetch(a.toString(),{method:"GET",headers:n});if(!s.ok){const i=await s.json().catch(()=>({}));throw new Error(i.detail||i.message||`API error: ${s.status} ${s.statusText}`)}return s.json()}async getModel(t){const r=this.getUrl(`/v1/models/${t}`),a={"Content-Type":"application/json"};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const n=await fetch(r,{method:"GET",headers:a});if(!n.ok){const s=await n.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${n.status} ${n.statusText}`)}return n.json()}async uploadFile(t,r,a){const n=this.getUrl("/v1/files"),s=this.generateIdempotencyKey(),i=new FormData;i.append("file",t),r&&i.append("resource_type",r),a&&i.append("resource_id",a);const c={"Idempotency-Key":s};this.sessionToken&&(c.Authorization=`Bearer ${this.sessionToken}`);const o=await fetch(n,{method:"POST",headers:c,body:i});if(!o.ok){const l=await o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}return o.json()}}async function*na(e,t){const r=e.getReader(),a=new TextDecoder;let n="";try{for(;;){if(t?.aborted){r.cancel();break}const{done:s,value:i}=await r.read();if(s)break;n+=a.decode(i,{stream:!0});const c=n.split(`
3
+ `).replace(/ {2,}/g," ").trim(),r}function ia(e){if(!e||typeof e!="string")return!1;try{const r=new URL(e);return["http:","https:"].includes(r.protocol)}catch{return!1}}function sa(e){if(!e)return{valid:!1,error:"URL is required"};if(typeof e!="string")return{valid:!1,error:"URL must be a string"};if(e.startsWith("/")||e.startsWith("./"))return{valid:!0};try{const r=new URL(e);return["http:","https:"].includes(r.protocol)?r.protocol==="http:"&&!oa(e)?{valid:!0,parsed:r,error:"Warning: Using HTTP for non-localhost URL. Consider using HTTPS."}:{valid:!0,parsed:r}:{valid:!1,error:`Invalid protocol "${r.protocol}". Only http and https are allowed.`}}catch{return{valid:!1,error:"Invalid URL format"}}}function oa(e){try{const r=new URL(e);return["localhost","127.0.0.1","[::1]"].includes(r.hostname)}catch{return!1}}function ca(e){if(!e||typeof e!="string")return"";const r={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"};return e.replace(/[&<>"'/]/g,t=>r[t]||t)}function Lt(){if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&crypto.getRandomValues){const e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const r=Array.from(e,t=>t.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}return typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn("[CuadraUIKit] Using non-cryptographic fallback for UUID generation"),`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`}class Dt{constructor(r,t,a=!1){z(this,"baseUrl");z(this,"sessionToken",null);z(this,"isProxyMode",!1);this.baseUrl=r.replace(/\/$/,""),this.isProxyMode=a,t&&(this.sessionToken=t)}setSessionToken(r){this.sessionToken=r}getUrl(r){if(this.isProxyMode){const t=`${this.baseUrl}${r.replace("/v1","")}`;return t.startsWith("/")||t.startsWith("./"),t}return`${this.baseUrl}${r}`}async createOrContinueChat(r,t){const a=this.getUrl("/v1/chats"),s={"Content-Type":"application/json",Accept:"text/event-stream","Accept-Encoding":"identity","Cache-Control":"no-cache","X-Accel-Buffering":"no","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(s.Authorization=`Bearer ${this.sessionToken}`);const n={...r,stream:!0},c=await fetch(a,{method:"POST",headers:s,body:JSON.stringify(n),signal:t,cache:"no-store"});if(!c.ok){const o=await c.json().catch(()=>({}));throw new Error(o.detail||o.message||`API error: ${c.status} ${c.statusText}`)}if(!c.body)throw new Error("Response body is null");return c.body}async getChat(r){const t=this.getUrl(`/v1/chats/${r}`),a={"Content-Type":"application/json"};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const i=await fetch(t,{method:"GET",headers:a});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${i.status} ${i.statusText}`)}return i.json()}async listChats(r){const t=this.getUrl("/v1/chats"),a=t.startsWith("/")||t.startsWith("./")?new URL(t,window.location.origin):new URL(t);r?.limit&&a.searchParams.set("limit",r.limit.toString()),r?.cursor&&a.searchParams.set("cursor",r.cursor),r?.["expand[]"]&&r["expand[]"].forEach(n=>{a.searchParams.append("expand[]",n)});const i={"Content-Type":"application/json"};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const s=await fetch(a.toString(),{method:"GET",headers:i});if(!s.ok){const n=await s.json().catch(()=>({}));throw new Error(n.detail||n.message||`API error: ${s.status} ${s.statusText}`)}return s.json()}generateIdempotencyKey(){return Lt()}async updateChat(r,t){const a=`/v1/chats/${r}`,i=this.getUrl(a),s=i.startsWith("/")||i.startsWith("./")?new URL(i,window.location.origin):new URL(i),c={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(c.Authorization=`Bearer ${this.sessionToken}`);const o=await fetch(s.toString(),{method:"PATCH",headers:c,body:JSON.stringify(t)});if(!o.ok){const m=await o.text();let d={};try{d=JSON.parse(m)}catch{d={detail:m}}throw new Error(d.detail||d.message||`API error: ${o.status} ${o.statusText}`)}if(o.status===204)return{};const u=await o.text();if(!u)return{};try{return JSON.parse(u)}catch{return{}}}async deleteChat(r){const t=`/v1/chats/${r}`,a=this.getUrl(t),i=a.startsWith("/")||a.startsWith("./")?new URL(a,window.location.origin):new URL(a),n={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const c=await fetch(i.toString(),{method:"DELETE",headers:n});if(!c.ok){const o=await c.json().catch(()=>({}));throw new Error(o.detail||o.message||`API error: ${c.status} ${c.statusText}`)}}async generateChatTitle(r,t){const a=`/v1/chats/${r}/title`,i=this.getUrl(a),s=i.startsWith("/")||i.startsWith("./")?new URL(i,window.location.origin):new URL(i),c={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(c.Authorization=`Bearer ${this.sessionToken}`);const o=await fetch(s.toString(),{method:"POST",headers:c,body:t?JSON.stringify(t):void 0});if(!o.ok){const u=await o.json().catch(()=>({}));throw new Error(u.detail||u.message||`API error: ${o.status} ${o.statusText}`)}return o.json()}async listModels(r){const t=this.getUrl("/v1/models"),a=t.startsWith("/")||t.startsWith("./")?new URL(t,window.location.origin):new URL(t);r?.limit&&a.searchParams.set("limit",r.limit.toString()),r?.cursor&&a.searchParams.set("cursor",r.cursor),r?.["expand[]"]&&r["expand[]"].forEach(n=>{a.searchParams.append("expand[]",n)});const i={"Content-Type":"application/json"};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const s=await fetch(a.toString(),{method:"GET",headers:i});if(!s.ok){const n=await s.json().catch(()=>({}));throw new Error(n.detail||n.message||`API error: ${s.status} ${s.statusText}`)}return s.json()}async getModel(r){const t=this.getUrl(`/v1/models/${r}`),a={"Content-Type":"application/json"};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const i=await fetch(t,{method:"GET",headers:a});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${i.status} ${i.statusText}`)}return i.json()}async uploadFile(r,t,a){const i=this.getUrl("/v1/files"),s=this.generateIdempotencyKey(),n=new FormData;n.append("file",r),t&&n.append("resource_type",t),a&&n.append("resource_id",a);const c={"Idempotency-Key":s};this.sessionToken&&(c.Authorization=`Bearer ${this.sessionToken}`);const o=await fetch(i,{method:"POST",headers:c,body:n});if(!o.ok){const u=await o.json().catch(()=>({}));throw new Error(u.detail||u.message||`API error: ${o.status} ${o.statusText}`)}return o.json()}}async function*ua(e,r){const t=e.getReader(),a=new TextDecoder;let i="";try{for(;;){if(r?.aborted){t.cancel();break}const{done:s,value:n}=await t.read();if(s)break;i+=a.decode(n,{stream:!0});const c=i.split(`
4
4
 
5
- `);n=c.pop()||"";for(const o of c)if(o.startsWith("data: ")){const l=o.slice(6);if(l.trim()==="[DONE]"){yield{done:!0};continue}try{yield JSON.parse(l)}catch{}}}}finally{r.releaseLock()}}function ia(e){return e.map(t=>{let r="";if(typeof t.content=="string")r=t.content;else if(Array.isArray(t.content)){const a=t.content.find(n=>n.type==="text");a&&typeof a=="object"&&"text"in a&&(r=a.text)}return{role:t.role,content:r}})}function sa(e){return{id:e.id,role:e.role,content:[{type:"text",text:e.content}],createdAt:new Date(e.createdAt),metadata:{custom:{}},...e.role==="assistant"&&{status:{type:"complete",reason:"stop"},metadata:{unstable_state:null,unstable_annotations:[],unstable_data:[],steps:[],custom:{}}},...e.role==="user"&&{attachments:[]}}}var oa=function(){let e,t;const r=new Promise((a,n)=>{e=a,t=n});if(!e||!t)throw new Error("Failed to create promise");return{promise:r,resolve:e,reject:t}},ca=()=>{const e=[];let t=!1,r,a;const n=i=>{i.promise||(i.promise=i.reader.read().then(({done:c,value:o})=>{i.promise=void 0,c?(e.splice(e.indexOf(i),1),t&&e.length===0&&r.close()):r.enqueue(o),a?.resolve(),a=void 0}).catch(c=>{console.error(c),e.forEach(o=>{o.reader.cancel()}),e.length=0,r.error(c),a?.reject(c),a=void 0}))};return{readable:new ReadableStream({start(i){r=i},pull(){return a=oa(),e.forEach(i=>{n(i)}),a.promise},cancel(){e.forEach(i=>{i.reader.cancel()}),e.length=0}}),isSealed(){return t},seal(){t=!0,e.length===0&&r.close()},addStream(i){if(t)throw new Error("Cannot add streams after the run callback has settled.");const c={reader:i.getReader()};e.push(c),n(c)},enqueue(i){this.addStream(new ReadableStream({start(c){c.enqueue(i),c.close()}}))}}},dt=class{constructor(e){z(this,"_controller");z(this,"_isClosed",!1);this._controller=e}append(e){return this._controller.enqueue({type:"text-delta",path:[],textDelta:e}),this}close(){this._isClosed||(this._isClosed=!0,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}},Rt=e=>new ReadableStream({start(t){return e.start?.(new dt(t))},pull(t){return e.pull?.(new dt(t))},cancel(t){return e.cancel?.(t)}}),ht=()=>{let e;return[Rt({start(r){e=r}}),e]},ft=class{constructor(e){z(this,"_isClosed",!1);z(this,"_mergeTask");z(this,"_argsTextController");this._controller=e;const t=Rt({start:a=>{this._argsTextController=a}});let r=!1;this._mergeTask=t.pipeTo(new WritableStream({write:a=>{switch(a.type){case"text-delta":r=!0,this._controller.enqueue(a);break;case"part-finish":r||this._controller.enqueue({type:"text-delta",textDelta:"{}",path:[]}),this._controller.enqueue({type:"tool-call-args-text-finish",path:[]});break;default:throw new Error(`Unexpected chunk type: ${a.type}`)}}}))}get argsText(){return this._argsTextController}async setResponse(e){this._argsTextController.close(),await Promise.resolve(),this._controller.enqueue({type:"result",path:[],...e.artifact!==void 0?{artifact:e.artifact}:{},result:e.result,isError:e.isError??!1})}async close(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),await this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}},la=e=>new ReadableStream({start(t){return e.start?.(new ft(t))},pull(t){return e.pull?.(new ft(t))},cancel(t){return e.cancel?.(t)}}),ua=()=>{let e;return[la({start(r){e=r}}),e]},Lt=class{constructor(){z(this,"value",-1)}up(){return++this.value}},da=class extends TransformStream{constructor(e){super({transform(t,r){r.enqueue({...t,path:[e,...t.path]})}})}};(class extends TransformStream{constructor(e){super({transform(t,r){const{path:[a,...n]}=t;if(e!==a)throw new Error(`Path mismatch: expected ${e}, got ${a}`);r.enqueue({...t,path:n})}})}});var ha=class extends TransformStream{constructor(e){const t=new Lt,r=new Map;super({transform(a,n){a.type==="part-start"&&a.path.length===0&&r.set(t.up(),e.up());const[s,...i]=a.path;if(s===void 0){n.enqueue(a);return}const c=r.get(s);if(c===void 0)throw new Error("Path not found");n.enqueue({...a,path:[c,...i]})}})}};let fa=(e,t=21)=>(r=t)=>{let a="",n=r|0;for(;n--;)a+=e[Math.random()*e.length|0];return a};var ma=fa("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),pa=class Dt{constructor(t){z(this,"_state");z(this,"_parentId");this._state=t||{merger:ca(),contentCounter:new Lt}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(t){this._state.closeSubscriber=t}_addPart(t,r){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:"part-start",part:t,path:[]}),this._state.merger.addStream(r.pipeThrough(new da(this._state.contentCounter.value)))}merge(t){this._state.merger.addStream(t.pipeThrough(new ha(this._state.contentCounter)))}appendText(t){this._state.append?.kind!=="text"&&(this._state.append={kind:"text",controller:this.addTextPart()}),this._state.append.controller.append(t)}appendReasoning(t){this._state.append?.kind!=="reasoning"&&(this._state.append={kind:"reasoning",controller:this.addReasoningPart()}),this._state.append.controller.append(t)}addTextPart(){const[t,r]=ht();return this._addPart({type:"text"},t),r}addReasoningPart(){const[t,r]=ht();return this._addPart({type:"reasoning"},t),r}addToolCallPart(t){const r=typeof t=="string"?{toolName:t}:t,a=r.toolName,n=r.toolCallId??ma(),[s,i]=ua();return this._addPart({type:"tool-call",toolName:a,toolCallId:n,...this._parentId&&{parentId:this._parentId}},s),r.argsText!==void 0&&(i.argsText.append(r.argsText),i.argsText.close()),r.args!==void 0&&(i.argsText.append(JSON.stringify(r.args)),i.argsText.close()),r.response!==void 0&&i.setResponse(r.response),i}appendSource(t){this._addPart({...t,...this._parentId&&{parentId:this._parentId}},new ReadableStream({start(r){r.enqueue({type:"part-finish",path:[]}),r.close()}}))}appendFile(t){this._addPart(t,new ReadableStream({start(r){r.enqueue({type:"part-finish",path:[]}),r.close()}}))}enqueue(t){this._state.merger.enqueue(t),t.type==="part-start"&&t.path.length===0&&this._state.contentCounter.up()}withParentId(t){const r=new Dt(this._state);return r._parentId=t,r}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}};function ga(e){const t=new pa;return(async()=>{try{await e(t)}catch(a){throw t.__internal_isClosed||t.enqueue({type:"error",path:[],error:String(a)}),a}finally{t.__internal_isClosed||t.close()}})(),t.__internal_getReadable()}const me=new Map,Se=new Map;let ce;function De(e,t){const r=me.get(e);if(r)return r;if(t)for(const a of t){const n=Se.get(a.id);if(n)return me.set(e,n),n}return e}function xa(e,t){return{async list(){const r=[];let n,s=0;do{const c=await e.listChats({limit:50,cursor:n}),o=c.items||[];Array.isArray(o)&&o.length>0&&r.push(...o),n=c.nextCursor||void 0,s++}while(n&&s<50);return{threads:r.map(c=>{const o=c.id;return!o||c.deletedAt?null:{status:"regular",remoteId:o,title:c.title||"New Chat",createdAt:c.createdAt?new Date(c.createdAt):new Date,updatedAt:c.updatedAt?new Date(c.updatedAt):new Date}}).filter(c=>c!==null)}},async initialize(r){return{remoteId:me.get(r)||r,externalId:void 0}},async rename(r,a){const n=De(r);await e.updateChat(n,{title:a})},async archive(r){},async unarchive(r){},async delete(r){const a=De(r);await e.deleteChat(a)},async generateTitle(r,a){const n=De(r,a);let s;try{s=(await e.generateChatTitle(n)).title}catch(i){console.error("[generateTitle] API call failed, falling back to first message",i);const o=a.find(l=>l.role==="user")?.content?.filter(l=>l.type==="text").map(l=>l.text).join(" ").trim();s=o?o.length>60?o.slice(0,57)+"...":o:void 0}return ga(i=>{const c=i.addTextPart();s&&c.append(s),c.close(),i.close()})},async fetch(r){try{const a=await e.getChat(r);return{status:"regular",remoteId:a.id||r,title:a.title||"Chat",createdAt:a.createdAt?new Date(a.createdAt):new Date,updatedAt:a.updatedAt?new Date(a.updatedAt):new Date}}catch{return{status:"regular",remoteId:r,createdAt:new Date,updatedAt:new Date}}},updateRemoteId(r,a){me.set(r,a),t?.(r,a)},unstable_Provider:({children:r})=>{const n=T.useThreadListItem()?.remoteId;y.useEffect(()=>{n&&(ce=n)},[n]);const s=y.useMemo(()=>({async load(){if(!n)return{messages:[]};try{const c=await e.getChat(n);if(!c.messages||c.messages.length===0)return{messages:[]};const o=c.messages.map(f=>sa(f)),l=o.map((f,d)=>({message:f,parentId:d>0?o[d-1].id:null}));for(const f of o)Se.set(f.id,n);return{messages:l}}catch{return{messages:[]}}},async append(c){}}),[n,e]),i=y.useMemo(()=>({history:s}),[s]);return u.jsx(T.RuntimeAdapterProvider,{adapters:i,children:r})}}}class ya{constructor(){z(this,"messageMetadata",new Map);z(this,"currentMessageId",null);z(this,"listeners",new Set)}setCurrentMessage(t){this.currentMessageId=t}update(t){if(!this.currentMessageId)return;const r=this.messageMetadata.get(this.currentMessageId)||{},a=t.sources;a&&a.length>0&&(this.messageMetadata.set(this.currentMessageId,{...r,sources:a}),this.notify())}get(){return this.currentMessageId?this.messageMetadata.get(this.currentMessageId)||{}:{}}getForMessage(t){return this.messageMetadata.get(t)||{}}getCurrentMessageId(){return this.currentMessageId}clear(){this.currentMessageId=null}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}notify(){this.listeners.forEach(t=>t())}}const ee=new ya,mt=new Map,Ve=[];let Ce=[];function Ft(e,t,r=50,a=800){Ve.push({question:e,response:t,streamingSpeed:r,initialDelay:a})}function Ut(e,t){const{modelId:r,systemPrompt:a,ephemeral:n,enableReasoning:s,onChatCreated:i,onUserMessage:c,onThreadIdUpdate:o,onBeforeRequest:l,mockResponseOnBlocked:f}=t;let d;return{async*run(m){const{messages:g,abortSignal:h}=m,w=Ve.shift();if(w){c?.();const k=w.initialDelay??800;if(k>0&&await new Promise(S=>setTimeout(S,k)),h?.aborted)throw new Error("Request aborted");const j=w.response.split(" ");let _="";const F=w.streamingSpeed||50,D=`premade-${Date.now()}`;n&&i?.(D);for(let S=0;S<j.length;S++){if(h?.aborted)throw new Error("Request aborted");_+=(S===0?"":" ")+j[S],yield{content:[{type:"text",text:_}]},await new Promise(O=>setTimeout(O,F+Math.random()*(F*.5)))}yield{content:[{type:"text",text:_}]},Ce.push({role:"user",content:w.question},{role:"assistant",content:w.response});return}let x;for(const k of g){const j=Se.get(k.id);if(j){x=j;break}}if(!x&&g.length>0){const k=g.find(j=>j.role==="user");if(k){const _=(typeof k.content=="string"?k.content:Array.isArray(k.content)&&k.content.find(F=>F.type==="text")?.text||"").substring(0,50);x=mt.get(_)}}!x&&d&&(x=d),c?.();let b=g,C=-1;for(let k=g.length-1;k>=0;k--)if(g[k].role==="assistant"){C=k;break}(x||C>=0)&&C>=0&&(b=g.slice(C+1));const v=ia(b);if(Ce.length>0&&!x){const k=Ce.map(j=>({role:j.role,content:j.content}));v.unshift(...k),Ce=[]}const P=[];let N;for(let k=b.length-1;k>=0;k--)if(b[k].role==="user"){N=b[k];break}if(N&&"attachments"in N){const k=N.attachments;if(k&&k.length>0){for(const j of k)if(j.file)try{const _=await e.uploadFile(j.file);P.push(_.id)}catch{}}}const I={messages:v,chatId:x||null,systemPrompt:a,ephemeral:n,enableReasoning:s,stream:!0};if(r&&r.trim()!==""&&(I.modelId=r),P.length>0&&(I.fileIds=P),l&&!await l()){if(f){const j=typeof f=="function"?f():f,_=g.filter(O=>O.role==="user"),F=_.length>0?_[_.length-1]:void 0;let D="Message";F&&(typeof F.content=="string"?D=F.content:Array.isArray(F.content)&&(D=F.content.find(Y=>Y.type==="text")?.text||"Message")),Ft(D,j,40,400);const S=Ve.shift();if(S){c?.();const O=S.initialDelay??400;if(O>0&&await new Promise(X=>setTimeout(X,O)),h?.aborted)throw new Error("Request aborted");const Y=S.response.split(" ");let J="";const ge=S.streamingSpeed||40,Ee=`mock-${Date.now()}`;n&&i?.(Ee);for(let X=0;X<Y.length;X++){if(h?.aborted)throw new Error("Request aborted");J+=(X===0?"":" ")+Y[X],yield{content:[{type:"text",text:J}]},await new Promise(ne=>setTimeout(ne,ge+Math.random()*(ge*.3)))}yield{content:[{type:"text",text:J}]};return}}throw new Error("Request blocked")}const q=await e.createOrContinueChat(I,h);let M="",U="",p;const L=[];let W=0,H=!1;const K=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;ee.clear(),ee.setCurrentMessage(K);const A=()=>{L.length!==W&&(W=L.length,ee.update({sources:L.length>0?[...L]:void 0}))},R=()=>{A();const k=[];return U&&k.push({type:"reasoning",text:U}),M&&k.push({type:"text",text:M}),k.length===0&&k.push({type:"text",text:""}),{content:k}};for await(const k of na(q,h)){if(h?.aborted)throw new Error("Request aborted");const j=k.id||k.chatId||k.messageId;if(j&&!p){p=j,d=j,i?.(j);for(const S of g)Se.set(S.id,j);if(g.length>0){const S=g.find(O=>O.role==="user");if(S){const Y=(typeof S.content=="string"?S.content:Array.isArray(S.content)&&S.content.find(J=>J.type==="text")?.text||"").substring(0,50);mt.set(Y,j)}}ce&&!me.has(ce)&&me.set(ce,j),o&&ce&&o(ce,j)}const _=k.sources;if(_&&Array.isArray(_)&&_.length>0)for(const S of _)L.some(O=>O.sourceId===S.sourceId)||L.push({sourceId:S.sourceId,filename:S.filename||"Unknown",score:S.score??1,chunkId:S.chunkId,datasetId:S.datasetId});const F=k.reasoning;if(F&&F.length>0&&(U+=F,yield R()),k.type)switch(k.type){case"source-document":k.sourceId&&L.push({sourceId:k.sourceId,filename:k.title||"Unknown",score:1});continue;case"reasoning-start":continue;case"reasoning-delta":k.delta&&(U+=k.delta),(M||U)&&(yield R());continue;case"reasoning-end":(M||U)&&(yield R());continue;case"text-delta":k.delta&&(U&&!H&&!M&&(H=!0,await new Promise(S=>setTimeout(S,400))),M+=k.delta),M&&(yield R());continue;case"error":throw new Error(k.errorText||"Stream error");case"text-start":case"text-end":case"start":case"start-step":case"finish-step":case"finish":continue}const D=k.delta;if(D!=null&&(U&&!H&&!M&&(H=!0,await new Promise(S=>setTimeout(S,400))),M+=D),k.content&&(M+=k.content),k.message&&(M+=k.message.content||""),k.finished){(M||U||L.length>0)&&(yield R());break}(M||U||L.length>0)&&(yield R())}(M||U||L.length>0)&&(yield R())}}}class le extends Error{constructor(t,r,a){super(t),this.code=r,this.file=a,this.name="AttachmentValidationError"}}const ba=["image/jpeg","image/png","image/gif","image/webp","image/svg+xml","application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","text/plain","text/markdown","text/csv","application/json"],wa=[".pdf",".doc",".docx",".xls",".xlsx",".txt",".md",".csv",".json",".jpg",".jpeg",".png",".gif",".webp",".svg"],ka=10*1024*1024;function pt(e){if(e===0)return"0 Bytes";const t=1024,r=["Bytes","KB","MB","GB"],a=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,a)).toFixed(2))+" "+r[a]}function Ca(e){return e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")).toLowerCase():""}function va(e,t){const a={"image/jpeg":[".jpg",".jpeg"],"image/png":[".png"],"image/gif":[".gif"],"image/webp":[".webp"],"image/svg+xml":[".svg"],"application/pdf":[".pdf"],"text/plain":[".txt"],"text/markdown":[".md"],"text/csv":[".csv"],"application/json":[".json"]}[e];return a?a.includes(t.toLowerCase()):!0}function Ta(){return typeof crypto<"u"&&crypto.randomUUID?"attachment-"+crypto.randomUUID():"attachment-"+Date.now()+"-"+Math.random().toString(36).slice(2,11)}function Qe(e={}){const{validation:t={},supportsVision:r=!0,onValidationError:a,onAttachmentAdded:n,onAttachmentRemoved:s}=e,{maxFileSizeBytes:i=ka,allowedMimeTypes:c=ba,allowedExtensions:o=wa,validateContentType:l=!0}=t,f=o.join(",");function d(m){if(m.size>i){const h=new le('File "'+m.name+'" is too large ('+pt(m.size)+"). Maximum size is "+pt(i)+".","FILE_TOO_LARGE",m);throw a?.(h),h}if(!r&&m.type.startsWith("image/")){const h=new le("The current model does not support image inputs. Please select a model with vision capabilities to attach images.","VISION_NOT_SUPPORTED",m);throw a?.(h),h}const g=Ca(m.name);if(g&&!o.some(h=>h.toLowerCase()===g)){const h=new le('File type "'+g+'" is not allowed. Allowed types: '+o.join(", "),"INVALID_TYPE",m);throw a?.(h),h}if(m.type&&!c.some(h=>{if(h.endsWith("/*")){const w=h.slice(0,-1);return m.type.startsWith(w)}return m.type===h})){const h=new le('File type "'+m.type+'" is not allowed.',"INVALID_TYPE",m);throw a?.(h),h}if(l&&m.type&&g&&!va(m.type,g)){const h=new le('File extension "'+g+'" does not match content type "'+m.type+'".',"VALIDATION_FAILED",m);throw a?.(h),h}}return{accept:f,async add({file:m}){d(m);let g="file";m.type.startsWith("image/")?g="image":(m.type.includes("pdf")||m.type.includes("document")||m.type.includes("text")||m.name.endsWith(".pdf")||m.name.endsWith(".docx")||m.name.endsWith(".txt")||m.name.endsWith(".md")||m.name.endsWith(".csv")||m.name.endsWith(".json"))&&(g="document");const h={id:Ta(),type:g,name:m.name,contentType:m.type,file:m,status:{type:"requires-action",reason:"composer-send"}};return n?.(h),h},async remove(m){s?.(m.id)},async send(m){if(m.type==="image"&&m.file){const g=await new Promise((h,w)=>{const x=new FileReader;x.onload=()=>h(x.result),x.onerror=()=>w(new Error("Failed to read file")),x.readAsDataURL(m.file)});return{...m,status:{type:"complete"},content:[{type:"image",image:g}]}}return{...m,status:{type:"complete"},content:[]}}}}class ja{constructor(){z(this,"current",null);z(this,"listeners",new Set);z(this,"getSnapshot",()=>this.current);z(this,"subscribe",t=>(this.listeners.add(t),()=>this.listeners.delete(t)))}push(t,r){this.current={message:t,code:r,timestamp:Date.now()},this.notify()}clear(){this.current&&(this.current=null,this.notify())}notify(){this.listeners.forEach(t=>t())}}const de=new ja;function Sa({children:e,baseUrl:t,sessionToken:r,isProxyMode:a=!1,mode:n="multiChat",modelId:s,onModelChange:i,ephemeral:c=!1,systemPrompt:o,enableReasoning:l=!1,initialThreadId:f,onError:d,onChatCreated:m,onUserMessage:g,onThreadIdUpdate:h,onChatsLoaded:w,enableAttachments:x=!1,supportsVision:b=!0,onBeforeRequest:C,mockResponseOnBlocked:v}){const P=y.useMemo(()=>new Et(t,r||void 0,a),[t,r,a]),[N,I]=y.useState(s||null);y.useEffect(()=>{s&&I(s)},[s]);const q=y.useCallback(p=>{m?.(p)},[m]),M=y.useCallback((p,L)=>{h?.(p,L)},[h]),U=y.useMemo(()=>Ut(P,{modelId:N||void 0,systemPrompt:o,ephemeral:c,enableReasoning:l,onChatCreated:q,onUserMessage:g,onBeforeRequest:C,mockResponseOnBlocked:v}),[P,N,o,c,l,q,g,C,v]);return n==="singleChat"?u.jsx(Ia,{modelAdapter:U,enableAttachments:x,supportsVision:b,children:e}):u.jsx(Ma,{client:P,modelAdapterOptions:{modelId:N||void 0,systemPrompt:o,ephemeral:c,enableReasoning:l,onChatCreated:q,onUserMessage:g,onBeforeRequest:C,mockResponseOnBlocked:v},initialThreadId:f,onChatsLoaded:w,onThreadIdUpdate:M,onError:d,enableAttachments:x,supportsVision:b,children:e})}function Ia({modelAdapter:e,enableAttachments:t,supportsVision:r=!0,children:a}){const n=y.useMemo(()=>t?Qe({supportsVision:r,onValidationError:i=>{de.push(i.message,i.code)}}):void 0,[t,r]),s=T.useLocalRuntime(e,{adapters:{...n&&{attachments:n}}});return u.jsx(T.AssistantRuntimeProvider,{runtime:s,children:a})}function Ma({client:e,modelAdapterOptions:t,initialThreadId:r,onChatsLoaded:a,onThreadIdUpdate:n,onError:s,enableAttachments:i,supportsVision:c,children:o}){const l=y.useMemo(()=>xa(e,(x,b)=>{n?.(x,b)}),[e,n]),f=y.useCallback((x,b)=>{l.updateRemoteId&&l.updateRemoteId(x,b),n?.(x,b)},[l,n]),d=y.useMemo(()=>({...l,async list(){const x=await l.list();return a?.(),x}}),[l,a]);y.useEffect(()=>{window.__cuadraThreadListAdapter=d,window.__cuadraThreadListRuntime=null},[d]);const m=y.useMemo(()=>Ut(e,{...t,onThreadIdUpdate:f}),[e,t,f]),g=y.useMemo(()=>i?Qe({supportsVision:c,onValidationError:x=>{de.push(x.message,x.code)}}):void 0,[i,c]),h=y.useCallback(()=>T.useLocalRuntime(m,{adapters:{...g&&{attachments:g}}}),[m,g]),w=T.unstable_useRemoteThreadListRuntime({adapter:d,runtimeHook:h});return y.useEffect(()=>{window.__cuadraThreadListRuntime=w},[w]),u.jsx(T.AssistantRuntimeProvider,{runtime:w,children:o})}function gt(e,t){const r=String(e);if(typeof t!="string")throw new TypeError("Expected character");let a=0,n=r.indexOf(t);for(;n!==-1;)a++,n=r.indexOf(t,n+t.length);return a}const ye=Ne(/[A-Za-z]/),Ge=Ne(/[\dA-Za-z]/);function Aa(e){return e!==null&&(e<32||e===127)}function he(e){return e!==null&&e<-2}function V(e){return e!==null&&(e<0||e===32)}function te(e){return e===-2||e===-1||e===32}const Ae=Ne(/\p{P}|\p{S}/u),oe=Ne(/\s/);function Ne(e){return t;function t(r){return r!==null&&r>-1&&e.test(String.fromCharCode(r))}}function Na(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}const _e=(function(e){if(e==null)return Ra;if(typeof e=="function")return Pe(e);if(typeof e=="object")return Array.isArray(e)?_a(e):Pa(e);if(typeof e=="string")return Ea(e);throw new Error("Expected function, string, or object as test")});function _a(e){const t=[];let r=-1;for(;++r<e.length;)t[r]=_e(e[r]);return Pe(a);function a(...n){let s=-1;for(;++s<t.length;)if(t[s].apply(this,n))return!0;return!1}}function Pa(e){const t=e;return Pe(r);function r(a){const n=a;let s;for(s in e)if(n[s]!==t[s])return!1;return!0}}function Ea(e){return Pe(t);function t(r){return r&&r.type===e}}function Pe(e){return t;function t(r,a,n){return!!(La(r)&&e.call(this,r,typeof a=="number"?a:void 0,n||void 0))}}function Ra(){return!0}function La(e){return e!==null&&typeof e=="object"&&"type"in e}const zt=[],Da=!0,We=!1,Fa="skip";function $t(e,t,r,a){let n;typeof t=="function"&&typeof r!="function"?(a=r,r=t):n=t;const s=_e(n),i=a?-1:1;c(e,void 0,[])();function c(o,l,f){const d=o&&typeof o=="object"?o:{};if(typeof d.type=="string"){const g=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(m,"name",{value:"node ("+(o.type+(g?"<"+g+">":""))+")"})}return m;function m(){let g=zt,h,w,x;if((!t||s(o,l,f[f.length-1]||void 0))&&(g=Ua(r(o,f)),g[0]===We))return g;if("children"in o&&o.children){const b=o;if(b.children&&g[0]!==Fa)for(w=(a?b.children.length:-1)+i,x=f.concat(b);w>-1&&w<b.children.length;){const C=b.children[w];if(h=c(C,w,x)(),h[0]===We)return h;w=typeof h[1]=="number"?h[1]:w+i}}return g}}}function Ua(e){return Array.isArray(e)?e:typeof e=="number"?[Da,e]:e==null?zt:[e]}function za(e,t,r){const n=_e((r||{}).ignore||[]),s=$a(t);let i=-1;for(;++i<s.length;)$t(e,"text",c);function c(l,f){let d=-1,m;for(;++d<f.length;){const g=f[d],h=m?m.children:void 0;if(n(g,h?h.indexOf(g):void 0,m))return;m=g}if(m)return o(l,f)}function o(l,f){const d=f[f.length-1],m=s[i][0],g=s[i][1];let h=0;const x=d.children.indexOf(l);let b=!1,C=[];m.lastIndex=0;let v=m.exec(l.value);for(;v;){const P=v.index,N={index:v.index,input:v.input,stack:[...f,l]};let I=g(...v,N);if(typeof I=="string"&&(I=I.length>0?{type:"text",value:I}:void 0),I===!1?m.lastIndex=P+1:(h!==P&&C.push({type:"text",value:l.value.slice(h,P)}),Array.isArray(I)?C.push(...I):I&&C.push(I),h=P+v[0].length,b=!0),!m.global)break;v=m.exec(l.value)}return b?(h<l.value.length&&C.push({type:"text",value:l.value.slice(h)}),d.children.splice(x,1,...C)):C=[l],x+C.length}}function $a(e){const t=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const r=!e[0]||Array.isArray(e[0])?e:[e];let a=-1;for(;++a<r.length;){const n=r[a];t.push([Oa(n[0]),Ba(n[1])])}return t}function Oa(e){return typeof e=="string"?new RegExp(Na(e),"g"):e}function Ba(e){return typeof e=="function"?e:function(){return e}}const Fe="phrasing",Ue=["autolink","link","image","label"];function qa(){return{transforms:[Ya],enter:{literalAutolink:Wa,literalAutolinkEmail:ze,literalAutolinkHttp:ze,literalAutolinkWww:ze},exit:{literalAutolink:Ga,literalAutolinkEmail:Qa,literalAutolinkHttp:Ha,literalAutolinkWww:Ka}}}function Va(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Fe,notInConstruct:Ue},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Fe,notInConstruct:Ue},{character:":",before:"[ps]",after:"\\/",inConstruct:Fe,notInConstruct:Ue}]}}function Wa(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function ze(e){this.config.enter.autolinkProtocol.call(this,e)}function Ha(e){this.config.exit.autolinkProtocol.call(this,e)}function Ka(e){this.config.exit.data.call(this,e);const t=this.stack[this.stack.length-1];t.type,t.url="http://"+this.sliceSerialize(e)}function Qa(e){this.config.exit.autolinkEmail.call(this,e)}function Ga(e){this.exit(e)}function Ya(e){za(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,Ja],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,Xa]],{ignore:["link","linkReference"]})}function Ja(e,t,r,a,n){let s="";if(!Ot(n)||(/^w/i.test(t)&&(r=t+r,t="",s="http://"),!Za(r)))return!1;const i=en(r+a);if(!i[0])return!1;const c={type:"link",title:null,url:s+t+i[0],children:[{type:"text",value:t+i[0]}]};return i[1]?[c,{type:"text",value:i[1]}]:c}function Xa(e,t,r,a){return!Ot(a,!0)||/[-\d_]$/.test(r)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+r,children:[{type:"text",value:t+"@"+r}]}}function Za(e){const t=e.split(".");return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function en(e){const t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let r=t[0],a=r.indexOf(")");const n=gt(e,"(");let s=gt(e,")");for(;a!==-1&&n>s;)e+=r.slice(0,a+1),r=r.slice(a+1),a=r.indexOf(")"),s++;return[e,r]}function Ot(e,t){const r=e.input.charCodeAt(e.index-1);return(e.index===0||oe(r)||Ae(r))&&(!t||r!==47)}function we(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}Bt.peek=un;function tn(){this.buffer()}function rn(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function an(){this.buffer()}function nn(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function sn(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=we(this.sliceSerialize(e)).toLowerCase(),r.label=t}function on(e){this.exit(e)}function cn(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=we(this.sliceSerialize(e)).toLowerCase(),r.label=t}function ln(e){this.exit(e)}function un(){return"["}function Bt(e,t,r,a){const n=r.createTracker(a);let s=n.move("[^");const i=r.enter("footnoteReference"),c=r.enter("reference");return s+=n.move(r.safe(r.associationId(e),{after:"]",before:s})),c(),i(),s+=n.move("]"),s}function dn(){return{enter:{gfmFootnoteCallString:tn,gfmFootnoteCall:rn,gfmFootnoteDefinitionLabelString:an,gfmFootnoteDefinition:nn},exit:{gfmFootnoteCallString:sn,gfmFootnoteCall:on,gfmFootnoteDefinitionLabelString:cn,gfmFootnoteDefinition:ln}}}function hn(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:r,footnoteReference:Bt},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function r(a,n,s,i){const c=s.createTracker(i);let o=c.move("[^");const l=s.enter("footnoteDefinition"),f=s.enter("label");return o+=c.move(s.safe(s.associationId(a),{before:o,after:"]"})),f(),o+=c.move("]:"),a.children&&a.children.length>0&&(c.shift(4),o+=c.move((t?`
6
- `:" ")+s.indentLines(s.containerFlow(a,c.current()),t?qt:fn))),l(),o}}function fn(e,t,r){return t===0?e:qt(e,t,r)}function qt(e,t,r){return(r?"":" ")+e}const mn=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Vt.peek=bn;function pn(){return{canContainEols:["delete"],enter:{strikethrough:xn},exit:{strikethrough:yn}}}function gn(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:mn}],handlers:{delete:Vt}}}function xn(e){this.enter({type:"delete",children:[]},e)}function yn(e){this.exit(e)}function Vt(e,t,r,a){const n=r.createTracker(a),s=r.enter("strikethrough");let i=n.move("~~");return i+=r.containerPhrasing(e,{...n.current(),before:i,after:"~"}),i+=n.move("~~"),s(),i}function bn(){return"~"}function wn(e){return e.length}function kn(e,t){const r=t||{},a=(r.align||[]).concat(),n=r.stringLength||wn,s=[],i=[],c=[],o=[];let l=0,f=-1;for(;++f<e.length;){const w=[],x=[];let b=-1;for(e[f].length>l&&(l=e[f].length);++b<e[f].length;){const C=Cn(e[f][b]);if(r.alignDelimiters!==!1){const v=n(C);x[b]=v,(o[b]===void 0||v>o[b])&&(o[b]=v)}w.push(C)}i[f]=w,c[f]=x}let d=-1;if(typeof a=="object"&&"length"in a)for(;++d<l;)s[d]=xt(a[d]);else{const w=xt(a);for(;++d<l;)s[d]=w}d=-1;const m=[],g=[];for(;++d<l;){const w=s[d];let x="",b="";w===99?(x=":",b=":"):w===108?x=":":w===114&&(b=":");let C=r.alignDelimiters===!1?1:Math.max(1,o[d]-x.length-b.length);const v=x+"-".repeat(C)+b;r.alignDelimiters!==!1&&(C=x.length+C+b.length,C>o[d]&&(o[d]=C),g[d]=C),m[d]=v}i.splice(1,0,m),c.splice(1,0,g),f=-1;const h=[];for(;++f<i.length;){const w=i[f],x=c[f];d=-1;const b=[];for(;++d<l;){const C=w[d]||"";let v="",P="";if(r.alignDelimiters!==!1){const N=o[d]-(x[d]||0),I=s[d];I===114?v=" ".repeat(N):I===99?N%2?(v=" ".repeat(N/2+.5),P=" ".repeat(N/2-.5)):(v=" ".repeat(N/2),P=v):P=" ".repeat(N)}r.delimiterStart!==!1&&!d&&b.push("|"),r.padding!==!1&&!(r.alignDelimiters===!1&&C==="")&&(r.delimiterStart!==!1||d)&&b.push(" "),r.alignDelimiters!==!1&&b.push(v),b.push(C),r.alignDelimiters!==!1&&b.push(P),r.padding!==!1&&b.push(" "),(r.delimiterEnd!==!1||d!==l-1)&&b.push("|")}h.push(r.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return h.join(`
7
- `)}function Cn(e){return e==null?"":String(e)}function xt(e){const t=typeof e=="string"?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}function vn(e,t,r,a){const n=r.enter("blockquote"),s=r.createTracker(a);s.move("> "),s.shift(2);const i=r.indentLines(r.containerFlow(e,s.current()),Tn);return n(),i}function Tn(e,t,r){return">"+(r?"":" ")+e}function jn(e,t){return yt(e,t.inConstruct,!0)&&!yt(e,t.notInConstruct,!1)}function yt(e,t,r){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return r;let a=-1;for(;++a<t.length;)if(e.includes(t[a]))return!0;return!1}function bt(e,t,r,a){let n=-1;for(;++n<r.unsafe.length;)if(r.unsafe[n].character===`
8
- `&&jn(r.stack,r.unsafe[n]))return/[ \t]/.test(a.before)?"":" ";return`\\
9
- `}function Sn(e,t){const r=String(e);let a=r.indexOf(t),n=a,s=0,i=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;a!==-1;)a===n?++s>i&&(i=s):s=1,n=a+t.length,a=r.indexOf(t,n);return i}function In(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function Mn(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function An(e,t,r,a){const n=Mn(r),s=e.value||"",i=n==="`"?"GraveAccent":"Tilde";if(In(e,r)){const d=r.enter("codeIndented"),m=r.indentLines(s,Nn);return d(),m}const c=r.createTracker(a),o=n.repeat(Math.max(Sn(s,n)+1,3)),l=r.enter("codeFenced");let f=c.move(o);if(e.lang){const d=r.enter(`codeFencedLang${i}`);f+=c.move(r.safe(e.lang,{before:f,after:" ",encode:["`"],...c.current()})),d()}if(e.lang&&e.meta){const d=r.enter(`codeFencedMeta${i}`);f+=c.move(" "),f+=c.move(r.safe(e.meta,{before:f,after:`
10
- `,encode:["`"],...c.current()})),d()}return f+=c.move(`
11
- `),s&&(f+=c.move(s+`
12
- `)),f+=c.move(o),l(),f}function Nn(e,t,r){return(r?"":" ")+e}function Ye(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function _n(e,t,r,a){const n=Ye(r),s=n==='"'?"Quote":"Apostrophe",i=r.enter("definition");let c=r.enter("label");const o=r.createTracker(a);let l=o.move("[");return l+=o.move(r.safe(r.associationId(e),{before:l,after:"]",...o.current()})),l+=o.move("]: "),c(),!e.url||/[\0- \u007F]/.test(e.url)?(c=r.enter("destinationLiteral"),l+=o.move("<"),l+=o.move(r.safe(e.url,{before:l,after:">",...o.current()})),l+=o.move(">")):(c=r.enter("destinationRaw"),l+=o.move(r.safe(e.url,{before:l,after:e.title?" ":`
13
- `,...o.current()}))),c(),e.title&&(c=r.enter(`title${s}`),l+=o.move(" "+n),l+=o.move(r.safe(e.title,{before:l,after:n,...o.current()})),l+=o.move(n),c()),i(),l}function Pn(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function be(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Ie(e){if(e===null||V(e)||oe(e))return 1;if(Ae(e))return 2}function Me(e,t,r){const a=Ie(e),n=Ie(t);return a===void 0?n===void 0?r==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:n===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:a===1?n===void 0?{inside:!1,outside:!1}:n===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:n===void 0?{inside:!1,outside:!1}:n===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Wt.peek=En;function Wt(e,t,r,a){const n=Pn(r),s=r.enter("emphasis"),i=r.createTracker(a),c=i.move(n);let o=i.move(r.containerPhrasing(e,{after:n,before:c,...i.current()}));const l=o.charCodeAt(0),f=Me(a.before.charCodeAt(a.before.length-1),l,n);f.inside&&(o=be(l)+o.slice(1));const d=o.charCodeAt(o.length-1),m=Me(a.after.charCodeAt(0),d,n);m.inside&&(o=o.slice(0,-1)+be(d));const g=i.move(n);return s(),r.attentionEncodeSurroundingInfo={after:m.outside,before:f.outside},c+o+g}function En(e,t,r){return r.options.emphasis||"*"}function Rn(e,t,r,a){let n,s,i;typeof t=="function"&&typeof r!="function"?(s=void 0,i=t,n=r):(s=t,i=r,n=a),$t(e,s,c,n);function c(o,l){const f=l[l.length-1],d=f?f.children.indexOf(o):void 0;return i(o,d,f)}}const Ln={};function Ht(e,t){const r=Ln,a=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,n=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return Kt(e,a,n)}function Kt(e,t,r){if(Dn(e)){if("value"in e)return e.type==="html"&&!r?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return wt(e.children,t,r)}return Array.isArray(e)?wt(e,t,r):""}function wt(e,t,r){const a=[];let n=-1;for(;++n<e.length;)a[n]=Kt(e[n],t,r);return a.join("")}function Dn(e){return!!(e&&typeof e=="object")}function Fn(e,t){let r=!1;return Rn(e,function(a){if("value"in a&&/\r?\n|\r/.test(a.value)||a.type==="break")return r=!0,We}),!!((!e.depth||e.depth<3)&&Ht(e)&&(t.options.setext||r))}function Un(e,t,r,a){const n=Math.max(Math.min(6,e.depth||1),1),s=r.createTracker(a);if(Fn(e,r)){const f=r.enter("headingSetext"),d=r.enter("phrasing"),m=r.containerPhrasing(e,{...s.current(),before:`
5
+ `);i=c.pop()||"";for(const o of c)if(o.startsWith("data: ")){const u=o.slice(6);if(u.trim()==="[DONE]"){yield{done:!0};continue}try{yield JSON.parse(u)}catch{}}}}finally{t.releaseLock()}}function la(e){return e.map(r=>{let t="";if(typeof r.content=="string")t=r.content;else if(Array.isArray(r.content)){const a=r.content.find(i=>i.type==="text");a&&typeof a=="object"&&"text"in a&&(t=a.text)}return{role:r.role,content:t}})}function da(e){return{id:e.id,role:e.role,content:[{type:"text",text:e.content}],createdAt:new Date(e.createdAt),metadata:{custom:{}},...e.role==="assistant"&&{status:{type:"complete",reason:"stop"},metadata:{unstable_state:null,unstable_annotations:[],unstable_data:[],steps:[],custom:{}}},...e.role==="user"&&{attachments:[]}}}var ha=function(){let e,r;const t=new Promise((a,i)=>{e=a,r=i});if(!e||!r)throw new Error("Failed to create promise");return{promise:t,resolve:e,reject:r}},fa=()=>{const e=[];let r=!1,t,a;const i=n=>{n.promise||(n.promise=n.reader.read().then(({done:c,value:o})=>{n.promise=void 0,c?(e.splice(e.indexOf(n),1),r&&e.length===0&&t.close()):t.enqueue(o),a?.resolve(),a=void 0}).catch(c=>{console.error(c),e.forEach(o=>{o.reader.cancel()}),e.length=0,t.error(c),a?.reject(c),a=void 0}))};return{readable:new ReadableStream({start(n){t=n},pull(){return a=ha(),e.forEach(n=>{i(n)}),a.promise},cancel(){e.forEach(n=>{n.reader.cancel()}),e.length=0}}),isSealed(){return r},seal(){r=!0,e.length===0&&t.close()},addStream(n){if(r)throw new Error("Cannot add streams after the run callback has settled.");const c={reader:n.getReader()};e.push(c),i(c)},enqueue(n){this.addStream(new ReadableStream({start(c){c.enqueue(n),c.close()}}))}}},ft=class{constructor(e){z(this,"_controller");z(this,"_isClosed",!1);this._controller=e}append(e){return this._controller.enqueue({type:"text-delta",path:[],textDelta:e}),this}close(){this._isClosed||(this._isClosed=!0,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}},Ft=e=>new ReadableStream({start(r){return e.start?.(new ft(r))},pull(r){return e.pull?.(new ft(r))},cancel(r){return e.cancel?.(r)}}),mt=()=>{let e;return[Ft({start(t){e=t}}),e]},pt=class{constructor(e){z(this,"_isClosed",!1);z(this,"_mergeTask");z(this,"_argsTextController");this._controller=e;const r=Ft({start:a=>{this._argsTextController=a}});let t=!1;this._mergeTask=r.pipeTo(new WritableStream({write:a=>{switch(a.type){case"text-delta":t=!0,this._controller.enqueue(a);break;case"part-finish":t||this._controller.enqueue({type:"text-delta",textDelta:"{}",path:[]}),this._controller.enqueue({type:"tool-call-args-text-finish",path:[]});break;default:throw new Error(`Unexpected chunk type: ${a.type}`)}}}))}get argsText(){return this._argsTextController}async setResponse(e){this._argsTextController.close(),await Promise.resolve(),this._controller.enqueue({type:"result",path:[],...e.artifact!==void 0?{artifact:e.artifact}:{},result:e.result,isError:e.isError??!1})}async close(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),await this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}},ma=e=>new ReadableStream({start(r){return e.start?.(new pt(r))},pull(r){return e.pull?.(new pt(r))},cancel(r){return e.cancel?.(r)}}),pa=()=>{let e;return[ma({start(t){e=t}}),e]},Ut=class{constructor(){z(this,"value",-1)}up(){return++this.value}},ga=class extends TransformStream{constructor(e){super({transform(r,t){t.enqueue({...r,path:[e,...r.path]})}})}};(class extends TransformStream{constructor(e){super({transform(r,t){const{path:[a,...i]}=r;if(e!==a)throw new Error(`Path mismatch: expected ${e}, got ${a}`);t.enqueue({...r,path:i})}})}});var xa=class extends TransformStream{constructor(e){const r=new Ut,t=new Map;super({transform(a,i){a.type==="part-start"&&a.path.length===0&&t.set(r.up(),e.up());const[s,...n]=a.path;if(s===void 0){i.enqueue(a);return}const c=t.get(s);if(c===void 0)throw new Error("Path not found");i.enqueue({...a,path:[c,...n]})}})}};let ya=(e,r=21)=>(t=r)=>{let a="",i=t|0;for(;i--;)a+=e[Math.random()*e.length|0];return a};var ba=ya("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),wa=class zt{constructor(r){z(this,"_state");z(this,"_parentId");this._state=r||{merger:fa(),contentCounter:new Ut}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(r){this._state.closeSubscriber=r}_addPart(r,t){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:"part-start",part:r,path:[]}),this._state.merger.addStream(t.pipeThrough(new ga(this._state.contentCounter.value)))}merge(r){this._state.merger.addStream(r.pipeThrough(new xa(this._state.contentCounter)))}appendText(r){this._state.append?.kind!=="text"&&(this._state.append={kind:"text",controller:this.addTextPart()}),this._state.append.controller.append(r)}appendReasoning(r){this._state.append?.kind!=="reasoning"&&(this._state.append={kind:"reasoning",controller:this.addReasoningPart()}),this._state.append.controller.append(r)}addTextPart(){const[r,t]=mt();return this._addPart({type:"text"},r),t}addReasoningPart(){const[r,t]=mt();return this._addPart({type:"reasoning"},r),t}addToolCallPart(r){const t=typeof r=="string"?{toolName:r}:r,a=t.toolName,i=t.toolCallId??ba(),[s,n]=pa();return this._addPart({type:"tool-call",toolName:a,toolCallId:i,...this._parentId&&{parentId:this._parentId}},s),t.argsText!==void 0&&(n.argsText.append(t.argsText),n.argsText.close()),t.args!==void 0&&(n.argsText.append(JSON.stringify(t.args)),n.argsText.close()),t.response!==void 0&&n.setResponse(t.response),n}appendSource(r){this._addPart({...r,...this._parentId&&{parentId:this._parentId}},new ReadableStream({start(t){t.enqueue({type:"part-finish",path:[]}),t.close()}}))}appendFile(r){this._addPart(r,new ReadableStream({start(t){t.enqueue({type:"part-finish",path:[]}),t.close()}}))}enqueue(r){this._state.merger.enqueue(r),r.type==="part-start"&&r.path.length===0&&this._state.contentCounter.up()}withParentId(r){const t=new zt(this._state);return t._parentId=r,t}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}};function ka(e){const r=new wa;return(async()=>{try{await e(r)}catch(a){throw r.__internal_isClosed||r.enqueue({type:"error",path:[],error:String(a)}),a}finally{r.__internal_isClosed||r.close()}})(),r.__internal_getReadable()}const pe=new Map,Ie=new Map;let ue;function ze(e,r){const t=pe.get(e);if(t)return t;if(r)for(const a of r){const i=Ie.get(a.id);if(i)return pe.set(e,i),i}return e}function Ca(e,r){return{async list(){const t=[];let i,s=0;do{const c=await e.listChats({limit:50,cursor:i}),o=c.items||[];Array.isArray(o)&&o.length>0&&t.push(...o),i=c.nextCursor||void 0,s++}while(i&&s<50);return{threads:t.map(c=>{const o=c.id;return!o||c.deletedAt?null:{status:"regular",remoteId:o,title:c.title||"New Chat",createdAt:c.createdAt?new Date(c.createdAt):new Date,updatedAt:c.updatedAt?new Date(c.updatedAt):new Date}}).filter(c=>c!==null)}},async initialize(t){return{remoteId:pe.get(t)||t,externalId:void 0}},async rename(t,a){const i=ze(t);await e.updateChat(i,{title:a})},async archive(t){},async unarchive(t){},async delete(t){const a=ze(t);await e.deleteChat(a)},async generateTitle(t,a){const i=ze(t,a);let s;try{s=(await e.generateChatTitle(i)).title}catch(n){console.error("[generateTitle] API call failed, falling back to first message",n);const o=a.find(u=>u.role==="user")?.content?.filter(u=>u.type==="text").map(u=>u.text).join(" ").trim();s=o?o.length>60?o.slice(0,57)+"...":o:void 0}return ka(n=>{const c=n.addTextPart();s&&c.append(s),c.close(),n.close()})},async fetch(t){try{const a=await e.getChat(t);return{status:"regular",remoteId:a.id||t,title:a.title||"Chat",createdAt:a.createdAt?new Date(a.createdAt):new Date,updatedAt:a.updatedAt?new Date(a.updatedAt):new Date}}catch{return{status:"regular",remoteId:t,createdAt:new Date,updatedAt:new Date}}},updateRemoteId(t,a){pe.set(t,a),r?.(t,a)},unstable_Provider:({children:t})=>{const i=j.useThreadListItem()?.remoteId;y.useEffect(()=>{i&&(ue=i)},[i]);const s=y.useMemo(()=>({async load(){if(!i)return{messages:[]};try{const c=await e.getChat(i);if(!c.messages||c.messages.length===0)return{messages:[]};const o=c.messages.map(m=>da(m)),u=o.map((m,d)=>({message:m,parentId:d>0?o[d-1].id:null}));for(const m of o)Ie.set(m.id,i);return{messages:u}}catch{return{messages:[]}}},async append(c){}}),[i,e]),n=y.useMemo(()=>({history:s}),[s]);return l.jsx(j.RuntimeAdapterProvider,{adapters:n,children:t})}}}class va{constructor(){z(this,"messageMetadata",new Map);z(this,"currentMessageId",null);z(this,"listeners",new Set)}setCurrentMessage(r){this.currentMessageId=r}update(r){if(!this.currentMessageId)return;const t=this.messageMetadata.get(this.currentMessageId)||{},a=r.sources;a&&a.length>0&&(this.messageMetadata.set(this.currentMessageId,{...t,sources:a}),this.notify())}get(){return this.currentMessageId?this.messageMetadata.get(this.currentMessageId)||{}:{}}getForMessage(r){return this.messageMetadata.get(r)||{}}getCurrentMessageId(){return this.currentMessageId}clear(){this.currentMessageId=null}subscribe(r){return this.listeners.add(r),()=>this.listeners.delete(r)}notify(){this.listeners.forEach(r=>r())}}const ee=new va,gt=new Map,Ge=[];let ve=[];function $t(e,r,t=50,a=800){Ge.push({question:e,response:r,streamingSpeed:t,initialDelay:a})}function Ot(e,r){const{modelId:t,systemPrompt:a,ephemeral:i,enableReasoning:s,onChatCreated:n,onUserMessage:c,onThreadIdUpdate:o,onBeforeRequest:u,mockResponseOnBlocked:m}=r;let d;return{async*run(f){const{messages:x,abortSignal:h}=f,w=Ge.shift();if(w){c?.();const k=w.initialDelay??800;if(k>0&&await new Promise(S=>setTimeout(S,k)),h?.aborted)throw new Error("Request aborted");const T=w.response.split(" ");let P="";const F=w.streamingSpeed||50,D=`premade-${Date.now()}`;i&&n?.(D);for(let S=0;S<T.length;S++){if(h?.aborted)throw new Error("Request aborted");P+=(S===0?"":" ")+T[S],yield{content:[{type:"text",text:P}]},await new Promise(B=>setTimeout(B,F+Math.random()*(F*.5)))}yield{content:[{type:"text",text:P}]},ve.push({role:"user",content:w.question},{role:"assistant",content:w.response});return}let b;for(const k of x){const T=Ie.get(k.id);if(T){b=T;break}}if(!b&&x.length>0){const k=x.find(T=>T.role==="user");if(k){const P=(typeof k.content=="string"?k.content:Array.isArray(k.content)&&k.content.find(F=>F.type==="text")?.text||"").substring(0,50);b=gt.get(P)}}!b&&d&&(b=d),c?.();let g=x,C=-1;for(let k=x.length-1;k>=0;k--)if(x[k].role==="assistant"){C=k;break}(b||C>=0)&&C>=0&&(g=x.slice(C+1));const v=la(g);if(ve.length>0&&!b){const k=ve.map(T=>({role:T.role,content:T.content}));v.unshift(...k),ve=[]}const _=[];let N;for(let k=g.length-1;k>=0;k--)if(g[k].role==="user"){N=g[k];break}if(N&&"attachments"in N){const k=N.attachments;if(k&&k.length>0){for(const T of k)if(T.file)try{const P=await e.uploadFile(T.file);_.push(P.id)}catch{}}}const I={messages:v,chatId:b||null,systemPrompt:a,ephemeral:i,enableReasoning:s,stream:!0};if(t&&t.trim()!==""&&(I.modelId=t),_.length>0&&(I.fileIds=_),u&&!await u()){if(m){const T=typeof m=="function"?m():m,P=x.filter(B=>B.role==="user"),F=P.length>0?P[P.length-1]:void 0;let D="Message";F&&(typeof F.content=="string"?D=F.content:Array.isArray(F.content)&&(D=F.content.find(Y=>Y.type==="text")?.text||"Message")),$t(D,T,40,400);const S=Ge.shift();if(S){c?.();const B=S.initialDelay??400;if(B>0&&await new Promise(X=>setTimeout(X,B)),h?.aborted)throw new Error("Request aborted");const Y=S.response.split(" ");let J="";const xe=S.streamingSpeed||40,Re=`mock-${Date.now()}`;i&&n?.(Re);for(let X=0;X<Y.length;X++){if(h?.aborted)throw new Error("Request aborted");J+=(X===0?"":" ")+Y[X],yield{content:[{type:"text",text:J}]},await new Promise(ne=>setTimeout(ne,xe+Math.random()*(xe*.3)))}yield{content:[{type:"text",text:J}]};return}}throw new Error("Request blocked")}const q=await e.createOrContinueChat(I,h);let M="",U="",p;const L=[];let W=0,H=!1;const K=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;ee.clear(),ee.setCurrentMessage(K);const A=()=>{L.length!==W&&(W=L.length,ee.update({sources:L.length>0?[...L]:void 0}))},R=()=>{A();const k=[];return U&&k.push({type:"reasoning",text:U}),M&&k.push({type:"text",text:M}),k.length===0&&k.push({type:"text",text:""}),{content:k}};for await(const k of ua(q,h)){if(h?.aborted)throw new Error("Request aborted");const T=k.id||k.chatId||k.messageId;if(T&&!p){p=T,d=T,n?.(T);for(const S of x)Ie.set(S.id,T);if(x.length>0){const S=x.find(B=>B.role==="user");if(S){const Y=(typeof S.content=="string"?S.content:Array.isArray(S.content)&&S.content.find(J=>J.type==="text")?.text||"").substring(0,50);gt.set(Y,T)}}ue&&!pe.has(ue)&&pe.set(ue,T),o&&ue&&o(ue,T)}const P=k.sources;if(P&&Array.isArray(P)&&P.length>0)for(const S of P)L.some(B=>B.sourceId===S.sourceId)||L.push({sourceId:S.sourceId,filename:S.filename||"Unknown",score:S.score??1,chunkId:S.chunkId,datasetId:S.datasetId});const F=k.reasoning;if(F&&F.length>0&&(U+=F,yield R()),k.type)switch(k.type){case"source-document":k.sourceId&&L.push({sourceId:k.sourceId,filename:k.title||"Unknown",score:1});continue;case"reasoning-start":continue;case"reasoning-delta":k.delta&&(U+=k.delta),(M||U)&&(yield R());continue;case"reasoning-end":(M||U)&&(yield R());continue;case"text-delta":k.delta&&(U&&!H&&!M&&(H=!0,await new Promise(S=>setTimeout(S,400))),M+=k.delta),M&&(yield R());continue;case"error":throw new Error(k.errorText||"Stream error");case"text-start":case"text-end":case"start":case"start-step":case"finish-step":case"finish":continue}const D=k.delta;if(D!=null&&(U&&!H&&!M&&(H=!0,await new Promise(S=>setTimeout(S,400))),M+=D),k.content&&(M+=k.content),k.message&&(M+=k.message.content||""),k.finished){(M||U||L.length>0)&&(yield R());break}(M||U||L.length>0)&&(yield R())}(M||U||L.length>0)&&(yield R())}}}class le extends Error{constructor(r,t,a){super(r),this.code=t,this.file=a,this.name="AttachmentValidationError"}}const ja=["image/jpeg","image/png","image/gif","image/webp","image/svg+xml","application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","text/plain","text/markdown","text/csv","application/json"],Ta=[".pdf",".doc",".docx",".xls",".xlsx",".txt",".md",".csv",".json",".jpg",".jpeg",".png",".gif",".webp",".svg"],Sa=10*1024*1024;function xt(e){if(e===0)return"0 Bytes";const r=1024,t=["Bytes","KB","MB","GB"],a=Math.floor(Math.log(e)/Math.log(r));return parseFloat((e/Math.pow(r,a)).toFixed(2))+" "+t[a]}function Ia(e){return e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")).toLowerCase():""}function Ma(e,r){const a={"image/jpeg":[".jpg",".jpeg"],"image/png":[".png"],"image/gif":[".gif"],"image/webp":[".webp"],"image/svg+xml":[".svg"],"application/pdf":[".pdf"],"text/plain":[".txt"],"text/markdown":[".md"],"text/csv":[".csv"],"application/json":[".json"]}[e];return a?a.includes(r.toLowerCase()):!0}function Aa(){return typeof crypto<"u"&&crypto.randomUUID?"attachment-"+crypto.randomUUID():"attachment-"+Date.now()+"-"+Math.random().toString(36).slice(2,11)}function Ze(e={}){const{validation:r={},supportsVision:t=!0,onValidationError:a,onAttachmentAdded:i,onAttachmentRemoved:s}=e,{maxFileSizeBytes:n=Sa,allowedMimeTypes:c=ja,allowedExtensions:o=Ta,validateContentType:u=!0}=r,m=o.join(",");function d(f){if(f.size>n){const h=new le('File "'+f.name+'" is too large ('+xt(f.size)+"). Maximum size is "+xt(n)+".","FILE_TOO_LARGE",f);throw a?.(h),h}if(!t&&f.type.startsWith("image/")){const h=new le("The current model does not support image inputs. Please select a model with vision capabilities to attach images.","VISION_NOT_SUPPORTED",f);throw a?.(h),h}const x=Ia(f.name);if(x&&!o.some(h=>h.toLowerCase()===x)){const h=new le('File type "'+x+'" is not allowed. Allowed types: '+o.join(", "),"INVALID_TYPE",f);throw a?.(h),h}if(f.type&&!c.some(h=>{if(h.endsWith("/*")){const w=h.slice(0,-1);return f.type.startsWith(w)}return f.type===h})){const h=new le('File type "'+f.type+'" is not allowed.',"INVALID_TYPE",f);throw a?.(h),h}if(u&&f.type&&x&&!Ma(f.type,x)){const h=new le('File extension "'+x+'" does not match content type "'+f.type+'".',"VALIDATION_FAILED",f);throw a?.(h),h}}return{accept:m,async add({file:f}){d(f);let x="file";f.type.startsWith("image/")?x="image":(f.type.includes("pdf")||f.type.includes("document")||f.type.includes("text")||f.name.endsWith(".pdf")||f.name.endsWith(".docx")||f.name.endsWith(".txt")||f.name.endsWith(".md")||f.name.endsWith(".csv")||f.name.endsWith(".json"))&&(x="document");const h={id:Aa(),type:x,name:f.name,contentType:f.type,file:f,status:{type:"requires-action",reason:"composer-send"}};return i?.(h),h},async remove(f){s?.(f.id)},async send(f){if(f.type==="image"&&f.file){const x=await new Promise((h,w)=>{const b=new FileReader;b.onload=()=>h(b.result),b.onerror=()=>w(new Error("Failed to read file")),b.readAsDataURL(f.file)});return{...f,status:{type:"complete"},content:[{type:"image",image:x}]}}return{...f,status:{type:"complete"},content:[]}}}}class Na{constructor(){z(this,"current",null);z(this,"listeners",new Set);z(this,"getSnapshot",()=>this.current);z(this,"subscribe",r=>(this.listeners.add(r),()=>this.listeners.delete(r)))}push(r,t){this.current={message:r,code:t,timestamp:Date.now()},this.notify()}clear(){this.current&&(this.current=null,this.notify())}notify(){this.listeners.forEach(r=>r())}}const he=new Na;function Pa({children:e,baseUrl:r,sessionToken:t,isProxyMode:a=!1,mode:i="multiChat",modelId:s,onModelChange:n,ephemeral:c=!1,systemPrompt:o,enableReasoning:u=!1,initialThreadId:m,onError:d,onChatCreated:f,onUserMessage:x,onThreadIdUpdate:h,onChatsLoaded:w,enableAttachments:b=!1,supportsVision:g=!0,onBeforeRequest:C,mockResponseOnBlocked:v}){const _=y.useMemo(()=>new Dt(r,t||void 0,a),[r,t,a]),[N,I]=y.useState(s||null);y.useEffect(()=>{s&&I(s)},[s]);const q=y.useCallback(p=>{f?.(p)},[f]),M=y.useCallback((p,L)=>{h?.(p,L)},[h]),U=y.useMemo(()=>Ot(_,{modelId:N||void 0,systemPrompt:o,ephemeral:c,enableReasoning:u,onChatCreated:q,onUserMessage:x,onBeforeRequest:C,mockResponseOnBlocked:v}),[_,N,o,c,u,q,x,C,v]);return i==="singleChat"?l.jsx(_a,{modelAdapter:U,enableAttachments:b,supportsVision:g,children:e}):l.jsx(Ea,{client:_,modelAdapterOptions:{modelId:N||void 0,systemPrompt:o,ephemeral:c,enableReasoning:u,onChatCreated:q,onUserMessage:x,onBeforeRequest:C,mockResponseOnBlocked:v},initialThreadId:m,onChatsLoaded:w,onThreadIdUpdate:M,onError:d,enableAttachments:b,supportsVision:g,children:e})}function _a({modelAdapter:e,enableAttachments:r,supportsVision:t=!0,children:a}){const i=y.useMemo(()=>r?Ze({supportsVision:t,onValidationError:n=>{he.push(n.message,n.code)}}):void 0,[r,t]),s=j.useLocalRuntime(e,{adapters:{...i&&{attachments:i}}});return l.jsx(j.AssistantRuntimeProvider,{runtime:s,children:a})}function Ea({client:e,modelAdapterOptions:r,initialThreadId:t,onChatsLoaded:a,onThreadIdUpdate:i,onError:s,enableAttachments:n,supportsVision:c,children:o}){const u=y.useMemo(()=>Ca(e,(b,g)=>{i?.(b,g)}),[e,i]),m=y.useCallback((b,g)=>{u.updateRemoteId&&u.updateRemoteId(b,g),i?.(b,g)},[u,i]),d=y.useMemo(()=>({...u,async list(){const b=await u.list();return a?.(),b}}),[u,a]);y.useEffect(()=>{window.__cuadraThreadListAdapter=d,window.__cuadraThreadListRuntime=null},[d]);const f=y.useMemo(()=>Ot(e,{...r,onThreadIdUpdate:m}),[e,r,m]),x=y.useMemo(()=>n?Ze({supportsVision:c,onValidationError:b=>{he.push(b.message,b.code)}}):void 0,[n,c]),h=y.useCallback(()=>j.useLocalRuntime(f,{adapters:{...x&&{attachments:x}}}),[f,x]),w=j.unstable_useRemoteThreadListRuntime({adapter:d,runtimeHook:h});return y.useEffect(()=>{window.__cuadraThreadListRuntime=w},[w]),l.jsx(j.AssistantRuntimeProvider,{runtime:w,children:o})}function yt(e,r){const t=String(e);if(typeof r!="string")throw new TypeError("Expected character");let a=0,i=t.indexOf(r);for(;i!==-1;)a++,i=t.indexOf(r,i+r.length);return a}const be=Pe(/[A-Za-z]/),et=Pe(/[\dA-Za-z]/);function Ra(e){return e!==null&&(e<32||e===127)}function fe(e){return e!==null&&e<-2}function V(e){return e!==null&&(e<0||e===32)}function te(e){return e===-2||e===-1||e===32}const Ne=Pe(/\p{P}|\p{S}/u),oe=Pe(/\s/);function Pe(e){return r;function r(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function La(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}const _e=(function(e){if(e==null)return za;if(typeof e=="function")return Ee(e);if(typeof e=="object")return Array.isArray(e)?Da(e):Fa(e);if(typeof e=="string")return Ua(e);throw new Error("Expected function, string, or object as test")});function Da(e){const r=[];let t=-1;for(;++t<e.length;)r[t]=_e(e[t]);return Ee(a);function a(...i){let s=-1;for(;++s<r.length;)if(r[s].apply(this,i))return!0;return!1}}function Fa(e){const r=e;return Ee(t);function t(a){const i=a;let s;for(s in e)if(i[s]!==r[s])return!1;return!0}}function Ua(e){return Ee(r);function r(t){return t&&t.type===e}}function Ee(e){return r;function r(t,a,i){return!!($a(t)&&e.call(this,t,typeof a=="number"?a:void 0,i||void 0))}}function za(){return!0}function $a(e){return e!==null&&typeof e=="object"&&"type"in e}const Bt=[],Oa=!0,Ye=!1,Ba="skip";function qt(e,r,t,a){let i;typeof r=="function"&&typeof t!="function"?(a=t,t=r):i=r;const s=_e(i),n=a?-1:1;c(e,void 0,[])();function c(o,u,m){const d=o&&typeof o=="object"?o:{};if(typeof d.type=="string"){const x=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(o.type+(x?"<"+x+">":""))+")"})}return f;function f(){let x=Bt,h,w,b;if((!r||s(o,u,m[m.length-1]||void 0))&&(x=qa(t(o,m)),x[0]===Ye))return x;if("children"in o&&o.children){const g=o;if(g.children&&x[0]!==Ba)for(w=(a?g.children.length:-1)+n,b=m.concat(g);w>-1&&w<g.children.length;){const C=g.children[w];if(h=c(C,w,b)(),h[0]===Ye)return h;w=typeof h[1]=="number"?h[1]:w+n}}return x}}}function qa(e){return Array.isArray(e)?e:typeof e=="number"?[Oa,e]:e==null?Bt:[e]}function Va(e,r,t){const i=_e((t||{}).ignore||[]),s=Wa(r);let n=-1;for(;++n<s.length;)qt(e,"text",c);function c(u,m){let d=-1,f;for(;++d<m.length;){const x=m[d],h=f?f.children:void 0;if(i(x,h?h.indexOf(x):void 0,f))return;f=x}if(f)return o(u,m)}function o(u,m){const d=m[m.length-1],f=s[n][0],x=s[n][1];let h=0;const b=d.children.indexOf(u);let g=!1,C=[];f.lastIndex=0;let v=f.exec(u.value);for(;v;){const _=v.index,N={index:v.index,input:v.input,stack:[...m,u]};let I=x(...v,N);if(typeof I=="string"&&(I=I.length>0?{type:"text",value:I}:void 0),I===!1?f.lastIndex=_+1:(h!==_&&C.push({type:"text",value:u.value.slice(h,_)}),Array.isArray(I)?C.push(...I):I&&C.push(I),h=_+v[0].length,g=!0),!f.global)break;v=f.exec(u.value)}return g?(h<u.value.length&&C.push({type:"text",value:u.value.slice(h)}),d.children.splice(b,1,...C)):C=[u],b+C.length}}function Wa(e){const r=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const t=!e[0]||Array.isArray(e[0])?e:[e];let a=-1;for(;++a<t.length;){const i=t[a];r.push([Ha(i[0]),Ka(i[1])])}return r}function Ha(e){return typeof e=="string"?new RegExp(La(e),"g"):e}function Ka(e){return typeof e=="function"?e:function(){return e}}const $e="phrasing",Oe=["autolink","link","image","label"];function Qa(){return{transforms:[tn],enter:{literalAutolink:Ya,literalAutolinkEmail:Be,literalAutolinkHttp:Be,literalAutolinkWww:Be},exit:{literalAutolink:en,literalAutolinkEmail:Za,literalAutolinkHttp:Ja,literalAutolinkWww:Xa}}}function Ga(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:$e,notInConstruct:Oe},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:$e,notInConstruct:Oe},{character:":",before:"[ps]",after:"\\/",inConstruct:$e,notInConstruct:Oe}]}}function Ya(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Be(e){this.config.enter.autolinkProtocol.call(this,e)}function Ja(e){this.config.exit.autolinkProtocol.call(this,e)}function Xa(e){this.config.exit.data.call(this,e);const r=this.stack[this.stack.length-1];r.type,r.url="http://"+this.sliceSerialize(e)}function Za(e){this.config.exit.autolinkEmail.call(this,e)}function en(e){this.exit(e)}function tn(e){Va(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,rn],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,an]],{ignore:["link","linkReference"]})}function rn(e,r,t,a,i){let s="";if(!Vt(i)||(/^w/i.test(r)&&(t=r+t,r="",s="http://"),!nn(t)))return!1;const n=sn(t+a);if(!n[0])return!1;const c={type:"link",title:null,url:s+r+n[0],children:[{type:"text",value:r+n[0]}]};return n[1]?[c,{type:"text",value:n[1]}]:c}function an(e,r,t,a){return!Vt(a,!0)||/[-\d_]$/.test(t)?!1:{type:"link",title:null,url:"mailto:"+r+"@"+t,children:[{type:"text",value:r+"@"+t}]}}function nn(e){const r=e.split(".");return!(r.length<2||r[r.length-1]&&(/_/.test(r[r.length-1])||!/[a-zA-Z\d]/.test(r[r.length-1]))||r[r.length-2]&&(/_/.test(r[r.length-2])||!/[a-zA-Z\d]/.test(r[r.length-2])))}function sn(e){const r=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!r)return[e,void 0];e=e.slice(0,r.index);let t=r[0],a=t.indexOf(")");const i=yt(e,"(");let s=yt(e,")");for(;a!==-1&&i>s;)e+=t.slice(0,a+1),t=t.slice(a+1),a=t.indexOf(")"),s++;return[e,t]}function Vt(e,r){const t=e.input.charCodeAt(e.index-1);return(e.index===0||oe(t)||Ne(t))&&(!r||t!==47)}function ke(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}Wt.peek=pn;function on(){this.buffer()}function cn(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function un(){this.buffer()}function ln(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function dn(e){const r=this.resume(),t=this.stack[this.stack.length-1];t.type,t.identifier=ke(this.sliceSerialize(e)).toLowerCase(),t.label=r}function hn(e){this.exit(e)}function fn(e){const r=this.resume(),t=this.stack[this.stack.length-1];t.type,t.identifier=ke(this.sliceSerialize(e)).toLowerCase(),t.label=r}function mn(e){this.exit(e)}function pn(){return"["}function Wt(e,r,t,a){const i=t.createTracker(a);let s=i.move("[^");const n=t.enter("footnoteReference"),c=t.enter("reference");return s+=i.move(t.safe(t.associationId(e),{after:"]",before:s})),c(),n(),s+=i.move("]"),s}function gn(){return{enter:{gfmFootnoteCallString:on,gfmFootnoteCall:cn,gfmFootnoteDefinitionLabelString:un,gfmFootnoteDefinition:ln},exit:{gfmFootnoteCallString:dn,gfmFootnoteCall:hn,gfmFootnoteDefinitionLabelString:fn,gfmFootnoteDefinition:mn}}}function xn(e){let r=!1;return e&&e.firstLineBlank&&(r=!0),{handlers:{footnoteDefinition:t,footnoteReference:Wt},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function t(a,i,s,n){const c=s.createTracker(n);let o=c.move("[^");const u=s.enter("footnoteDefinition"),m=s.enter("label");return o+=c.move(s.safe(s.associationId(a),{before:o,after:"]"})),m(),o+=c.move("]:"),a.children&&a.children.length>0&&(c.shift(4),o+=c.move((r?`
6
+ `:" ")+s.indentLines(s.containerFlow(a,c.current()),r?Ht:yn))),u(),o}}function yn(e,r,t){return r===0?e:Ht(e,r,t)}function Ht(e,r,t){return(t?"":" ")+e}const bn=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Kt.peek=jn;function wn(){return{canContainEols:["delete"],enter:{strikethrough:Cn},exit:{strikethrough:vn}}}function kn(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:bn}],handlers:{delete:Kt}}}function Cn(e){this.enter({type:"delete",children:[]},e)}function vn(e){this.exit(e)}function Kt(e,r,t,a){const i=t.createTracker(a),s=t.enter("strikethrough");let n=i.move("~~");return n+=t.containerPhrasing(e,{...i.current(),before:n,after:"~"}),n+=i.move("~~"),s(),n}function jn(){return"~"}function Tn(e){return e.length}function Sn(e,r){const t=r||{},a=(t.align||[]).concat(),i=t.stringLength||Tn,s=[],n=[],c=[],o=[];let u=0,m=-1;for(;++m<e.length;){const w=[],b=[];let g=-1;for(e[m].length>u&&(u=e[m].length);++g<e[m].length;){const C=In(e[m][g]);if(t.alignDelimiters!==!1){const v=i(C);b[g]=v,(o[g]===void 0||v>o[g])&&(o[g]=v)}w.push(C)}n[m]=w,c[m]=b}let d=-1;if(typeof a=="object"&&"length"in a)for(;++d<u;)s[d]=bt(a[d]);else{const w=bt(a);for(;++d<u;)s[d]=w}d=-1;const f=[],x=[];for(;++d<u;){const w=s[d];let b="",g="";w===99?(b=":",g=":"):w===108?b=":":w===114&&(g=":");let C=t.alignDelimiters===!1?1:Math.max(1,o[d]-b.length-g.length);const v=b+"-".repeat(C)+g;t.alignDelimiters!==!1&&(C=b.length+C+g.length,C>o[d]&&(o[d]=C),x[d]=C),f[d]=v}n.splice(1,0,f),c.splice(1,0,x),m=-1;const h=[];for(;++m<n.length;){const w=n[m],b=c[m];d=-1;const g=[];for(;++d<u;){const C=w[d]||"";let v="",_="";if(t.alignDelimiters!==!1){const N=o[d]-(b[d]||0),I=s[d];I===114?v=" ".repeat(N):I===99?N%2?(v=" ".repeat(N/2+.5),_=" ".repeat(N/2-.5)):(v=" ".repeat(N/2),_=v):_=" ".repeat(N)}t.delimiterStart!==!1&&!d&&g.push("|"),t.padding!==!1&&!(t.alignDelimiters===!1&&C==="")&&(t.delimiterStart!==!1||d)&&g.push(" "),t.alignDelimiters!==!1&&g.push(v),g.push(C),t.alignDelimiters!==!1&&g.push(_),t.padding!==!1&&g.push(" "),(t.delimiterEnd!==!1||d!==u-1)&&g.push("|")}h.push(t.delimiterEnd===!1?g.join("").replace(/ +$/,""):g.join(""))}return h.join(`
7
+ `)}function In(e){return e==null?"":String(e)}function bt(e){const r=typeof e=="string"?e.codePointAt(0):0;return r===67||r===99?99:r===76||r===108?108:r===82||r===114?114:0}function Mn(e,r,t,a){const i=t.enter("blockquote"),s=t.createTracker(a);s.move("> "),s.shift(2);const n=t.indentLines(t.containerFlow(e,s.current()),An);return i(),n}function An(e,r,t){return">"+(t?"":" ")+e}function Nn(e,r){return wt(e,r.inConstruct,!0)&&!wt(e,r.notInConstruct,!1)}function wt(e,r,t){if(typeof r=="string"&&(r=[r]),!r||r.length===0)return t;let a=-1;for(;++a<r.length;)if(e.includes(r[a]))return!0;return!1}function kt(e,r,t,a){let i=-1;for(;++i<t.unsafe.length;)if(t.unsafe[i].character===`
8
+ `&&Nn(t.stack,t.unsafe[i]))return/[ \t]/.test(a.before)?"":" ";return`\\
9
+ `}function Pn(e,r){const t=String(e);let a=t.indexOf(r),i=a,s=0,n=0;if(typeof r!="string")throw new TypeError("Expected substring");for(;a!==-1;)a===i?++s>n&&(n=s):s=1,i=a+r.length,a=t.indexOf(r,i);return n}function _n(e,r){return!!(r.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function En(e){const r=e.options.fence||"`";if(r!=="`"&&r!=="~")throw new Error("Cannot serialize code with `"+r+"` for `options.fence`, expected `` ` `` or `~`");return r}function Rn(e,r,t,a){const i=En(t),s=e.value||"",n=i==="`"?"GraveAccent":"Tilde";if(_n(e,t)){const d=t.enter("codeIndented"),f=t.indentLines(s,Ln);return d(),f}const c=t.createTracker(a),o=i.repeat(Math.max(Pn(s,i)+1,3)),u=t.enter("codeFenced");let m=c.move(o);if(e.lang){const d=t.enter(`codeFencedLang${n}`);m+=c.move(t.safe(e.lang,{before:m,after:" ",encode:["`"],...c.current()})),d()}if(e.lang&&e.meta){const d=t.enter(`codeFencedMeta${n}`);m+=c.move(" "),m+=c.move(t.safe(e.meta,{before:m,after:`
10
+ `,encode:["`"],...c.current()})),d()}return m+=c.move(`
11
+ `),s&&(m+=c.move(s+`
12
+ `)),m+=c.move(o),u(),m}function Ln(e,r,t){return(t?"":" ")+e}function tt(e){const r=e.options.quote||'"';if(r!=='"'&&r!=="'")throw new Error("Cannot serialize title with `"+r+"` for `options.quote`, expected `\"`, or `'`");return r}function Dn(e,r,t,a){const i=tt(t),s=i==='"'?"Quote":"Apostrophe",n=t.enter("definition");let c=t.enter("label");const o=t.createTracker(a);let u=o.move("[");return u+=o.move(t.safe(t.associationId(e),{before:u,after:"]",...o.current()})),u+=o.move("]: "),c(),!e.url||/[\0- \u007F]/.test(e.url)?(c=t.enter("destinationLiteral"),u+=o.move("<"),u+=o.move(t.safe(e.url,{before:u,after:">",...o.current()})),u+=o.move(">")):(c=t.enter("destinationRaw"),u+=o.move(t.safe(e.url,{before:u,after:e.title?" ":`
13
+ `,...o.current()}))),c(),e.title&&(c=t.enter(`title${s}`),u+=o.move(" "+i),u+=o.move(t.safe(e.title,{before:u,after:i,...o.current()})),u+=o.move(i),c()),n(),u}function Fn(e){const r=e.options.emphasis||"*";if(r!=="*"&&r!=="_")throw new Error("Cannot serialize emphasis with `"+r+"` for `options.emphasis`, expected `*`, or `_`");return r}function we(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Me(e){if(e===null||V(e)||oe(e))return 1;if(Ne(e))return 2}function Ae(e,r,t){const a=Me(e),i=Me(r);return a===void 0?i===void 0?t==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:a===1?i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Qt.peek=Un;function Qt(e,r,t,a){const i=Fn(t),s=t.enter("emphasis"),n=t.createTracker(a),c=n.move(i);let o=n.move(t.containerPhrasing(e,{after:i,before:c,...n.current()}));const u=o.charCodeAt(0),m=Ae(a.before.charCodeAt(a.before.length-1),u,i);m.inside&&(o=we(u)+o.slice(1));const d=o.charCodeAt(o.length-1),f=Ae(a.after.charCodeAt(0),d,i);f.inside&&(o=o.slice(0,-1)+we(d));const x=n.move(i);return s(),t.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+o+x}function Un(e,r,t){return t.options.emphasis||"*"}function zn(e,r,t,a){let i,s,n;typeof r=="function"&&typeof t!="function"?(s=void 0,n=r,i=t):(s=r,n=t,i=a),qt(e,s,c,i);function c(o,u){const m=u[u.length-1],d=m?m.children.indexOf(o):void 0;return n(o,d,m)}}const $n={};function Gt(e,r){const t=$n,a=typeof t.includeImageAlt=="boolean"?t.includeImageAlt:!0,i=typeof t.includeHtml=="boolean"?t.includeHtml:!0;return Yt(e,a,i)}function Yt(e,r,t){if(On(e)){if("value"in e)return e.type==="html"&&!t?"":e.value;if(r&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Ct(e.children,r,t)}return Array.isArray(e)?Ct(e,r,t):""}function Ct(e,r,t){const a=[];let i=-1;for(;++i<e.length;)a[i]=Yt(e[i],r,t);return a.join("")}function On(e){return!!(e&&typeof e=="object")}function Bn(e,r){let t=!1;return zn(e,function(a){if("value"in a&&/\r?\n|\r/.test(a.value)||a.type==="break")return t=!0,Ye}),!!((!e.depth||e.depth<3)&&Gt(e)&&(r.options.setext||t))}function qn(e,r,t,a){const i=Math.max(Math.min(6,e.depth||1),1),s=t.createTracker(a);if(Bn(e,t)){const m=t.enter("headingSetext"),d=t.enter("phrasing"),f=t.containerPhrasing(e,{...s.current(),before:`
14
14
  `,after:`
15
- `});return d(),f(),m+`
16
- `+(n===1?"=":"-").repeat(m.length-(Math.max(m.lastIndexOf("\r"),m.lastIndexOf(`
17
- `))+1))}const i="#".repeat(n),c=r.enter("headingAtx"),o=r.enter("phrasing");s.move(i+" ");let l=r.containerPhrasing(e,{before:"# ",after:`
18
- `,...s.current()});return/^[\t ]/.test(l)&&(l=be(l.charCodeAt(0))+l.slice(1)),l=l?i+" "+l:i,r.options.closeAtx&&(l+=" "+i),o(),c(),l}Qt.peek=zn;function Qt(e){return e.value||""}function zn(){return"<"}Gt.peek=$n;function Gt(e,t,r,a){const n=Ye(r),s=n==='"'?"Quote":"Apostrophe",i=r.enter("image");let c=r.enter("label");const o=r.createTracker(a);let l=o.move("![");return l+=o.move(r.safe(e.alt,{before:l,after:"]",...o.current()})),l+=o.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=r.enter("destinationLiteral"),l+=o.move("<"),l+=o.move(r.safe(e.url,{before:l,after:">",...o.current()})),l+=o.move(">")):(c=r.enter("destinationRaw"),l+=o.move(r.safe(e.url,{before:l,after:e.title?" ":")",...o.current()}))),c(),e.title&&(c=r.enter(`title${s}`),l+=o.move(" "+n),l+=o.move(r.safe(e.title,{before:l,after:n,...o.current()})),l+=o.move(n),c()),l+=o.move(")"),i(),l}function $n(){return"!"}Yt.peek=On;function Yt(e,t,r,a){const n=e.referenceType,s=r.enter("imageReference");let i=r.enter("label");const c=r.createTracker(a);let o=c.move("![");const l=r.safe(e.alt,{before:o,after:"]",...c.current()});o+=c.move(l+"]["),i();const f=r.stack;r.stack=[],i=r.enter("reference");const d=r.safe(r.associationId(e),{before:o,after:"]",...c.current()});return i(),r.stack=f,s(),n==="full"||!l||l!==d?o+=c.move(d+"]"):n==="shortcut"?o=o.slice(0,-1):o+=c.move("]"),o}function On(){return"!"}Jt.peek=Bn;function Jt(e,t,r){let a=e.value||"",n="`",s=-1;for(;new RegExp("(^|[^`])"+n+"([^`]|$)").test(a);)n+="`";for(/[^ \r\n]/.test(a)&&(/^[ \r\n]/.test(a)&&/[ \r\n]$/.test(a)||/^`|`$/.test(a))&&(a=" "+a+" ");++s<r.unsafe.length;){const i=r.unsafe[s],c=r.compilePattern(i);let o;if(i.atBreak)for(;o=c.exec(a);){let l=o.index;a.charCodeAt(l)===10&&a.charCodeAt(l-1)===13&&l--,a=a.slice(0,l)+" "+a.slice(o.index+1)}}return n+a+n}function Bn(){return"`"}function Xt(e,t){const r=Ht(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(r===e.url||"mailto:"+r===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}Zt.peek=qn;function Zt(e,t,r,a){const n=Ye(r),s=n==='"'?"Quote":"Apostrophe",i=r.createTracker(a);let c,o;if(Xt(e,r)){const f=r.stack;r.stack=[],c=r.enter("autolink");let d=i.move("<");return d+=i.move(r.containerPhrasing(e,{before:d,after:">",...i.current()})),d+=i.move(">"),c(),r.stack=f,d}c=r.enter("link"),o=r.enter("label");let l=i.move("[");return l+=i.move(r.containerPhrasing(e,{before:l,after:"](",...i.current()})),l+=i.move("]("),o(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(o=r.enter("destinationLiteral"),l+=i.move("<"),l+=i.move(r.safe(e.url,{before:l,after:">",...i.current()})),l+=i.move(">")):(o=r.enter("destinationRaw"),l+=i.move(r.safe(e.url,{before:l,after:e.title?" ":")",...i.current()}))),o(),e.title&&(o=r.enter(`title${s}`),l+=i.move(" "+n),l+=i.move(r.safe(e.title,{before:l,after:n,...i.current()})),l+=i.move(n),o()),l+=i.move(")"),c(),l}function qn(e,t,r){return Xt(e,r)?"<":"["}er.peek=Vn;function er(e,t,r,a){const n=e.referenceType,s=r.enter("linkReference");let i=r.enter("label");const c=r.createTracker(a);let o=c.move("[");const l=r.containerPhrasing(e,{before:o,after:"]",...c.current()});o+=c.move(l+"]["),i();const f=r.stack;r.stack=[],i=r.enter("reference");const d=r.safe(r.associationId(e),{before:o,after:"]",...c.current()});return i(),r.stack=f,s(),n==="full"||!l||l!==d?o+=c.move(d+"]"):n==="shortcut"?o=o.slice(0,-1):o+=c.move("]"),o}function Vn(){return"["}function Je(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function Wn(e){const t=Je(e),r=e.options.bulletOther;if(!r)return t==="*"?"-":"*";if(r!=="*"&&r!=="+"&&r!=="-")throw new Error("Cannot serialize items with `"+r+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(r===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+r+"`) to be different");return r}function Hn(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function tr(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function Kn(e,t,r,a){const n=r.enter("list"),s=r.bulletCurrent;let i=e.ordered?Hn(r):Je(r);const c=e.ordered?i==="."?")":".":Wn(r);let o=t&&r.bulletLastUsed?i===r.bulletLastUsed:!1;if(!e.ordered){const f=e.children?e.children[0]:void 0;if((i==="*"||i==="-")&&f&&(!f.children||!f.children[0])&&r.stack[r.stack.length-1]==="list"&&r.stack[r.stack.length-2]==="listItem"&&r.stack[r.stack.length-3]==="list"&&r.stack[r.stack.length-4]==="listItem"&&r.indexStack[r.indexStack.length-1]===0&&r.indexStack[r.indexStack.length-2]===0&&r.indexStack[r.indexStack.length-3]===0&&(o=!0),tr(r)===i&&f){let d=-1;for(;++d<e.children.length;){const m=e.children[d];if(m&&m.type==="listItem"&&m.children&&m.children[0]&&m.children[0].type==="thematicBreak"){o=!0;break}}}}o&&(i=c),r.bulletCurrent=i;const l=r.containerFlow(e,a);return r.bulletLastUsed=i,r.bulletCurrent=s,n(),l}function Qn(e){const t=e.options.listItemIndent||"one";if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function Gn(e,t,r,a){const n=Qn(r);let s=r.bulletCurrent||Je(r);t&&t.type==="list"&&t.ordered&&(s=(typeof t.start=="number"&&t.start>-1?t.start:1)+(r.options.incrementListMarker===!1?0:t.children.indexOf(e))+s);let i=s.length+1;(n==="tab"||n==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(i=Math.ceil(i/4)*4);const c=r.createTracker(a);c.move(s+" ".repeat(i-s.length)),c.shift(i);const o=r.enter("listItem"),l=r.indentLines(r.containerFlow(e,c.current()),f);return o(),l;function f(d,m,g){return m?(g?"":" ".repeat(i))+d:(g?s:s+" ".repeat(i-s.length))+d}}function Yn(e,t,r,a){const n=r.enter("paragraph"),s=r.enter("phrasing"),i=r.containerPhrasing(e,a);return s(),n(),i}const Jn=_e(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function Xn(e,t,r,a){return(e.children.some(function(i){return Jn(i)})?r.containerPhrasing:r.containerFlow).call(r,e,a)}function Zn(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}rr.peek=ei;function rr(e,t,r,a){const n=Zn(r),s=r.enter("strong"),i=r.createTracker(a),c=i.move(n+n);let o=i.move(r.containerPhrasing(e,{after:n,before:c,...i.current()}));const l=o.charCodeAt(0),f=Me(a.before.charCodeAt(a.before.length-1),l,n);f.inside&&(o=be(l)+o.slice(1));const d=o.charCodeAt(o.length-1),m=Me(a.after.charCodeAt(0),d,n);m.inside&&(o=o.slice(0,-1)+be(d));const g=i.move(n+n);return s(),r.attentionEncodeSurroundingInfo={after:m.outside,before:f.outside},c+o+g}function ei(e,t,r){return r.options.strong||"*"}function ti(e,t,r,a){return r.safe(e.value,a)}function ri(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function ai(e,t,r){const a=(tr(r)+(r.options.ruleSpaces?" ":"")).repeat(ri(r));return r.options.ruleSpaces?a.slice(0,-1):a}const ar={blockquote:vn,break:bt,code:An,definition:_n,emphasis:Wt,hardBreak:bt,heading:Un,html:Qt,image:Gt,imageReference:Yt,inlineCode:Jt,link:Zt,linkReference:er,list:Kn,listItem:Gn,paragraph:Yn,root:Xn,strong:rr,text:ti,thematicBreak:ai};function ni(){return{enter:{table:ii,tableData:kt,tableHeader:kt,tableRow:oi},exit:{codeText:ci,table:si,tableData:$e,tableHeader:$e,tableRow:$e}}}function ii(e){const t=e._align;this.enter({type:"table",align:t.map(function(r){return r==="none"?null:r}),children:[]},e),this.data.inTable=!0}function si(e){this.exit(e),this.data.inTable=void 0}function oi(e){this.enter({type:"tableRow",children:[]},e)}function $e(e){this.exit(e)}function kt(e){this.enter({type:"tableCell",children:[]},e)}function ci(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,li));const r=this.stack[this.stack.length-1];r.type,r.value=t,this.exit(e)}function li(e,t){return t==="|"?t:e}function ui(e){const t=e||{},r=t.tableCellPadding,a=t.tablePipeAlign,n=t.stringLength,s=r?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
19
- `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:m,table:i,tableCell:o,tableRow:c}};function i(g,h,w,x){return l(f(g,w,x),g.align)}function c(g,h,w,x){const b=d(g,w,x),C=l([b]);return C.slice(0,C.indexOf(`
20
- `))}function o(g,h,w,x){const b=w.enter("tableCell"),C=w.enter("phrasing"),v=w.containerPhrasing(g,{...x,before:s,after:s});return C(),b(),v}function l(g,h){return kn(g,{align:h,alignDelimiters:a,padding:r,stringLength:n})}function f(g,h,w){const x=g.children;let b=-1;const C=[],v=h.enter("table");for(;++b<x.length;)C[b]=d(x[b],h,w);return v(),C}function d(g,h,w){const x=g.children;let b=-1;const C=[],v=h.enter("tableRow");for(;++b<x.length;)C[b]=o(x[b],g,h,w);return v(),C}function m(g,h,w){let x=ar.inlineCode(g,h,w);return w.stack.includes("tableCell")&&(x=x.replace(/\|/g,"\\$&")),x}}function di(){return{exit:{taskListCheckValueChecked:Ct,taskListCheckValueUnchecked:Ct,paragraph:fi}}}function hi(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:mi}}}function Ct(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function fi(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const r=this.stack[this.stack.length-1];r.type;const a=r.children[0];if(a&&a.type==="text"){const n=t.children;let s=-1,i;for(;++s<n.length;){const c=n[s];if(c.type==="paragraph"){i=c;break}}i===r&&(a.value=a.value.slice(1),a.value.length===0?r.children.shift():r.position&&a.position&&typeof a.position.start.offset=="number"&&(a.position.start.column++,a.position.start.offset++,r.position.start=Object.assign({},a.position.start)))}}this.exit(e)}function mi(e,t,r,a){const n=e.children[0],s=typeof e.checked=="boolean"&&n&&n.type==="paragraph",i="["+(e.checked?"x":" ")+"] ",c=r.createTracker(a);s&&c.move(i);let o=ar.listItem(e,t,r,{...a,...c.current()});return s&&(o=o.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,l)),o;function l(f){return f+i}}function pi(){return[qa(),dn(),pn(),ni(),di()]}function gi(e){return{extensions:[Va(),hn(e),gn(),ui(e),hi()]}}function je(e,t,r,a){const n=e.length;let s=0,i;if(t<0?t=-t>n?0:n+t:t=t>n?n:t,r=r>0?r:0,a.length<1e4)i=Array.from(a),i.unshift(t,r),e.splice(...i);else for(r&&e.splice(t,r);s<a.length;)i=a.slice(s,s+1e4),i.unshift(t,0),e.splice(...i),s+=1e4,t+=1e4}const vt={}.hasOwnProperty;function xi(e){const t={};let r=-1;for(;++r<e.length;)yi(t,e[r]);return t}function yi(e,t){let r;for(r in t){const n=(vt.call(e,r)?e[r]:void 0)||(e[r]={}),s=t[r];let i;if(s)for(i in s){vt.call(n,i)||(n[i]=[]);const c=s[i];bi(n[i],Array.isArray(c)?c:c?[c]:[])}}}function bi(e,t){let r=-1;const a=[];for(;++r<t.length;)(t[r].add==="after"?e:a).push(t[r]);je(e,0,0,a)}const wi={tokenize:Si,partial:!0},nr={tokenize:Ii,partial:!0},ir={tokenize:Mi,partial:!0},sr={tokenize:Ai,partial:!0},ki={tokenize:Ni,partial:!0},or={name:"wwwAutolink",tokenize:Ti,previous:lr},cr={name:"protocolAutolink",tokenize:ji,previous:ur},ae={name:"emailAutolink",tokenize:vi,previous:dr},G={};function Ci(){return{text:G}}let se=48;for(;se<123;)G[se]=ae,se++,se===58?se=65:se===91&&(se=97);G[43]=ae;G[45]=ae;G[46]=ae;G[95]=ae;G[72]=[ae,cr];G[104]=[ae,cr];G[87]=[ae,or];G[119]=[ae,or];function vi(e,t,r){const a=this;let n,s;return i;function i(d){return!He(d)||!dr.call(a,a.previous)||Xe(a.events)?r(d):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(d))}function c(d){return He(d)?(e.consume(d),c):d===64?(e.consume(d),o):r(d)}function o(d){return d===46?e.check(ki,f,l)(d):d===45||d===95||Ge(d)?(s=!0,e.consume(d),o):f(d)}function l(d){return e.consume(d),n=!0,o}function f(d){return s&&n&&ye(a.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(d)):r(d)}}function Ti(e,t,r){const a=this;return n;function n(i){return i!==87&&i!==119||!lr.call(a,a.previous)||Xe(a.events)?r(i):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(wi,e.attempt(nr,e.attempt(ir,s),r),r)(i))}function s(i){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(i)}}function ji(e,t,r){const a=this;let n="",s=!1;return i;function i(d){return(d===72||d===104)&&ur.call(a,a.previous)&&!Xe(a.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),n+=String.fromCodePoint(d),e.consume(d),c):r(d)}function c(d){if(ye(d)&&n.length<5)return n+=String.fromCodePoint(d),e.consume(d),c;if(d===58){const m=n.toLowerCase();if(m==="http"||m==="https")return e.consume(d),o}return r(d)}function o(d){return d===47?(e.consume(d),s?l:(s=!0,o)):r(d)}function l(d){return d===null||Aa(d)||V(d)||oe(d)||Ae(d)?r(d):e.attempt(nr,e.attempt(ir,f),r)(d)}function f(d){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(d)}}function Si(e,t,r){let a=0;return n;function n(i){return(i===87||i===119)&&a<3?(a++,e.consume(i),n):i===46&&a===3?(e.consume(i),s):r(i)}function s(i){return i===null?r(i):t(i)}}function Ii(e,t,r){let a,n,s;return i;function i(l){return l===46||l===95?e.check(sr,o,c)(l):l===null||V(l)||oe(l)||l!==45&&Ae(l)?o(l):(s=!0,e.consume(l),i)}function c(l){return l===95?a=!0:(n=a,a=void 0),e.consume(l),i}function o(l){return n||a||!s?r(l):t(l)}}function Mi(e,t){let r=0,a=0;return n;function n(i){return i===40?(r++,e.consume(i),n):i===41&&a<r?s(i):i===33||i===34||i===38||i===39||i===41||i===42||i===44||i===46||i===58||i===59||i===60||i===63||i===93||i===95||i===126?e.check(sr,t,s)(i):i===null||V(i)||oe(i)?t(i):(e.consume(i),n)}function s(i){return i===41&&a++,e.consume(i),n}}function Ai(e,t,r){return a;function a(c){return c===33||c===34||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===63||c===95||c===126?(e.consume(c),a):c===38?(e.consume(c),s):c===93?(e.consume(c),n):c===60||c===null||V(c)||oe(c)?t(c):r(c)}function n(c){return c===null||c===40||c===91||V(c)||oe(c)?t(c):a(c)}function s(c){return ye(c)?i(c):r(c)}function i(c){return c===59?(e.consume(c),a):ye(c)?(e.consume(c),i):r(c)}}function Ni(e,t,r){return a;function a(s){return e.consume(s),n}function n(s){return Ge(s)?r(s):t(s)}}function lr(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||V(e)}function ur(e){return!ye(e)}function dr(e){return!(e===47||He(e))}function He(e){return e===43||e===45||e===46||e===95||Ge(e)}function Xe(e){let t=e.length,r=!1;for(;t--;){const a=e[t][1];if((a.type==="labelLink"||a.type==="labelImage")&&!a._balanced){r=!0;break}if(a._gfmAutolinkLiteralWalkedInto){r=!1;break}}return e.length>0&&!r&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}function _i(e,t,r){const a=[];let n=-1;for(;++n<e.length;){const s=e[n].resolveAll;s&&!a.includes(s)&&(t=s(t,r),a.push(s))}return t}function re(e,t,r,a){const n=a?a-1:Number.POSITIVE_INFINITY;let s=0;return i;function i(o){return te(o)?(e.enter(r),c(o)):t(o)}function c(o){return te(o)&&s++<n?(e.consume(o),c):(e.exit(r),t(o))}}const Pi={partial:!0,tokenize:Ei};function Ei(e,t,r){return a;function a(s){return te(s)?re(e,n,"linePrefix")(s):n(s)}function n(s){return s===null||he(s)?t(s):r(s)}}const Ri={tokenize:Bi,partial:!0};function Li(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:zi,continuation:{tokenize:$i},exit:Oi}},text:{91:{name:"gfmFootnoteCall",tokenize:Ui},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Di,resolveTo:Fi}}}}function Di(e,t,r){const a=this;let n=a.events.length;const s=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let i;for(;n--;){const o=a.events[n][1];if(o.type==="labelImage"){i=o;break}if(o.type==="gfmFootnoteCall"||o.type==="labelLink"||o.type==="label"||o.type==="image"||o.type==="link")break}return c;function c(o){if(!i||!i._balanced)return r(o);const l=we(a.sliceSerialize({start:i.end,end:a.now()}));return l.codePointAt(0)!==94||!s.includes(l.slice(1))?r(o):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(o),e.exit("gfmFootnoteCallLabelMarker"),t(o))}}function Fi(e,t){let r=e.length;for(;r--;)if(e[r][1].type==="labelImage"&&e[r][0]==="enter"){e[r][1];break}e[r+1][1].type="data",e[r+3][1].type="gfmFootnoteCallLabelMarker";const a={type:"gfmFootnoteCall",start:Object.assign({},e[r+3][1].start),end:Object.assign({},e[e.length-1][1].end)},n={type:"gfmFootnoteCallMarker",start:Object.assign({},e[r+3][1].end),end:Object.assign({},e[r+3][1].end)};n.end.column++,n.end.offset++,n.end._bufferIndex++;const s={type:"gfmFootnoteCallString",start:Object.assign({},n.end),end:Object.assign({},e[e.length-1][1].start)},i={type:"chunkString",contentType:"string",start:Object.assign({},s.start),end:Object.assign({},s.end)},c=[e[r+1],e[r+2],["enter",a,t],e[r+3],e[r+4],["enter",n,t],["exit",n,t],["enter",s,t],["enter",i,t],["exit",i,t],["exit",s,t],e[e.length-2],e[e.length-1],["exit",a,t]];return e.splice(r,e.length-r+1,...c),e}function Ui(e,t,r){const a=this,n=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let s=0,i;return c;function c(d){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),o}function o(d){return d!==94?r(d):(e.enter("gfmFootnoteCallMarker"),e.consume(d),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",l)}function l(d){if(s>999||d===93&&!i||d===null||d===91||V(d))return r(d);if(d===93){e.exit("chunkString");const m=e.exit("gfmFootnoteCallString");return n.includes(we(a.sliceSerialize(m)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(d)}return V(d)||(i=!0),s++,e.consume(d),d===92?f:l}function f(d){return d===91||d===92||d===93?(e.consume(d),s++,l):l(d)}}function zi(e,t,r){const a=this,n=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let s,i=0,c;return o;function o(h){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(h),e.exit("gfmFootnoteDefinitionLabelMarker"),l}function l(h){return h===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(h),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",f):r(h)}function f(h){if(i>999||h===93&&!c||h===null||h===91||V(h))return r(h);if(h===93){e.exit("chunkString");const w=e.exit("gfmFootnoteDefinitionLabelString");return s=we(a.sliceSerialize(w)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(h),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),m}return V(h)||(c=!0),i++,e.consume(h),h===92?d:f}function d(h){return h===91||h===92||h===93?(e.consume(h),i++,f):f(h)}function m(h){return h===58?(e.enter("definitionMarker"),e.consume(h),e.exit("definitionMarker"),n.includes(s)||n.push(s),re(e,g,"gfmFootnoteDefinitionWhitespace")):r(h)}function g(h){return t(h)}}function $i(e,t,r){return e.check(Pi,t,e.attempt(Ri,t,r))}function Oi(e){e.exit("gfmFootnoteDefinition")}function Bi(e,t,r){const a=this;return re(e,n,"gfmFootnoteDefinitionIndent",5);function n(s){const i=a.events[a.events.length-1];return i&&i[1].type==="gfmFootnoteDefinitionIndent"&&i[2].sliceSerialize(i[1],!0).length===4?t(s):r(s)}}function qi(e){let r=(e||{}).singleTilde;const a={name:"strikethrough",tokenize:s,resolveAll:n};return r==null&&(r=!0),{text:{126:a},insideSpan:{null:[a]},attentionMarkers:{null:[126]}};function n(i,c){let o=-1;for(;++o<i.length;)if(i[o][0]==="enter"&&i[o][1].type==="strikethroughSequenceTemporary"&&i[o][1]._close){let l=o;for(;l--;)if(i[l][0]==="exit"&&i[l][1].type==="strikethroughSequenceTemporary"&&i[l][1]._open&&i[o][1].end.offset-i[o][1].start.offset===i[l][1].end.offset-i[l][1].start.offset){i[o][1].type="strikethroughSequence",i[l][1].type="strikethroughSequence";const f={type:"strikethrough",start:Object.assign({},i[l][1].start),end:Object.assign({},i[o][1].end)},d={type:"strikethroughText",start:Object.assign({},i[l][1].end),end:Object.assign({},i[o][1].start)},m=[["enter",f,c],["enter",i[l][1],c],["exit",i[l][1],c],["enter",d,c]],g=c.parser.constructs.insideSpan.null;g&&je(m,m.length,0,_i(g,i.slice(l+1,o),c)),je(m,m.length,0,[["exit",d,c],["enter",i[o][1],c],["exit",i[o][1],c],["exit",f,c]]),je(i,l-1,o-l+3,m),o=l+m.length-2;break}}for(o=-1;++o<i.length;)i[o][1].type==="strikethroughSequenceTemporary"&&(i[o][1].type="data");return i}function s(i,c,o){const l=this.previous,f=this.events;let d=0;return m;function m(h){return l===126&&f[f.length-1][1].type!=="characterEscape"?o(h):(i.enter("strikethroughSequenceTemporary"),g(h))}function g(h){const w=Ie(l);if(h===126)return d>1?o(h):(i.consume(h),d++,g);if(d<2&&!r)return o(h);const x=i.exit("strikethroughSequenceTemporary"),b=Ie(h);return x._open=!b||b===2&&!!w,x._close=!w||w===2&&!!b,c(h)}}}class Vi{constructor(){this.map=[]}add(t,r,a){Wi(this,t,r,a)}consume(t){if(this.map.sort(function(s,i){return s[0]-i[0]}),this.map.length===0)return;let r=this.map.length;const a=[];for(;r>0;)r-=1,a.push(t.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),t.length=this.map[r][0];a.push(t.slice()),t.length=0;let n=a.pop();for(;n;){for(const s of n)t.push(s);n=a.pop()}this.map.length=0}}function Wi(e,t,r,a){let n=0;if(!(r===0&&a.length===0)){for(;n<e.map.length;){if(e.map[n][0]===t){e.map[n][1]+=r,e.map[n][2].push(...a);return}n+=1}e.map.push([t,r,a])}}function Hi(e,t){let r=!1;const a=[];for(;t<e.length;){const n=e[t];if(r){if(n[0]==="enter")n[1].type==="tableContent"&&a.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(n[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const s=a.length-1;a[s]=a[s]==="left"?"center":"right"}}else if(n[1].type==="tableDelimiterRow")break}else n[0]==="enter"&&n[1].type==="tableDelimiterRow"&&(r=!0);t+=1}return a}function Ki(){return{flow:{null:{name:"table",tokenize:Qi,resolveAll:Gi}}}}function Qi(e,t,r){const a=this;let n=0,s=0,i;return c;function c(p){let L=a.events.length-1;for(;L>-1;){const K=a.events[L][1].type;if(K==="lineEnding"||K==="linePrefix")L--;else break}const W=L>-1?a.events[L][1].type:null,H=W==="tableHead"||W==="tableRow"?I:o;return H===I&&a.parser.lazy[a.now().line]?r(p):H(p)}function o(p){return e.enter("tableHead"),e.enter("tableRow"),l(p)}function l(p){return p===124||(i=!0,s+=1),f(p)}function f(p){return p===null?r(p):he(p)?s>1?(s=0,a.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),g):r(p):te(p)?re(e,f,"whitespace")(p):(s+=1,i&&(i=!1,n+=1),p===124?(e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),i=!0,f):(e.enter("data"),d(p)))}function d(p){return p===null||p===124||V(p)?(e.exit("data"),f(p)):(e.consume(p),p===92?m:d)}function m(p){return p===92||p===124?(e.consume(p),d):d(p)}function g(p){return a.interrupt=!1,a.parser.lazy[a.now().line]?r(p):(e.enter("tableDelimiterRow"),i=!1,te(p)?re(e,h,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(p):h(p))}function h(p){return p===45||p===58?x(p):p===124?(i=!0,e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),w):N(p)}function w(p){return te(p)?re(e,x,"whitespace")(p):x(p)}function x(p){return p===58?(s+=1,i=!0,e.enter("tableDelimiterMarker"),e.consume(p),e.exit("tableDelimiterMarker"),b):p===45?(s+=1,b(p)):p===null||he(p)?P(p):N(p)}function b(p){return p===45?(e.enter("tableDelimiterFiller"),C(p)):N(p)}function C(p){return p===45?(e.consume(p),C):p===58?(i=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(p),e.exit("tableDelimiterMarker"),v):(e.exit("tableDelimiterFiller"),v(p))}function v(p){return te(p)?re(e,P,"whitespace")(p):P(p)}function P(p){return p===124?h(p):p===null||he(p)?!i||n!==s?N(p):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(p)):N(p)}function N(p){return r(p)}function I(p){return e.enter("tableRow"),q(p)}function q(p){return p===124?(e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),q):p===null||he(p)?(e.exit("tableRow"),t(p)):te(p)?re(e,q,"whitespace")(p):(e.enter("data"),M(p))}function M(p){return p===null||p===124||V(p)?(e.exit("data"),q(p)):(e.consume(p),p===92?U:M)}function U(p){return p===92||p===124?(e.consume(p),M):M(p)}}function Gi(e,t){let r=-1,a=!0,n=0,s=[0,0,0,0],i=[0,0,0,0],c=!1,o=0,l,f,d;const m=new Vi;for(;++r<e.length;){const g=e[r],h=g[1];g[0]==="enter"?h.type==="tableHead"?(c=!1,o!==0&&(Tt(m,t,o,l,f),f=void 0,o=0),l={type:"table",start:Object.assign({},h.start),end:Object.assign({},h.end)},m.add(r,0,[["enter",l,t]])):h.type==="tableRow"||h.type==="tableDelimiterRow"?(a=!0,d=void 0,s=[0,0,0,0],i=[0,r+1,0,0],c&&(c=!1,f={type:"tableBody",start:Object.assign({},h.start),end:Object.assign({},h.end)},m.add(r,0,[["enter",f,t]])),n=h.type==="tableDelimiterRow"?2:f?3:1):n&&(h.type==="data"||h.type==="tableDelimiterMarker"||h.type==="tableDelimiterFiller")?(a=!1,i[2]===0&&(s[1]!==0&&(i[0]=i[1],d=ve(m,t,s,n,void 0,d),s=[0,0,0,0]),i[2]=r)):h.type==="tableCellDivider"&&(a?a=!1:(s[1]!==0&&(i[0]=i[1],d=ve(m,t,s,n,void 0,d)),s=i,i=[s[1],r,0,0])):h.type==="tableHead"?(c=!0,o=r):h.type==="tableRow"||h.type==="tableDelimiterRow"?(o=r,s[1]!==0?(i[0]=i[1],d=ve(m,t,s,n,r,d)):i[1]!==0&&(d=ve(m,t,i,n,r,d)),n=0):n&&(h.type==="data"||h.type==="tableDelimiterMarker"||h.type==="tableDelimiterFiller")&&(i[3]=r)}for(o!==0&&Tt(m,t,o,l,f),m.consume(t.events),r=-1;++r<t.events.length;){const g=t.events[r];g[0]==="enter"&&g[1].type==="table"&&(g[1]._align=Hi(t.events,r))}return e}function ve(e,t,r,a,n,s){const i=a===1?"tableHeader":a===2?"tableDelimiter":"tableData",c="tableContent";r[0]!==0&&(s.end=Object.assign({},ue(t.events,r[0])),e.add(r[0],0,[["exit",s,t]]));const o=ue(t.events,r[1]);if(s={type:i,start:Object.assign({},o),end:Object.assign({},o)},e.add(r[1],0,[["enter",s,t]]),r[2]!==0){const l=ue(t.events,r[2]),f=ue(t.events,r[3]),d={type:c,start:Object.assign({},l),end:Object.assign({},f)};if(e.add(r[2],0,[["enter",d,t]]),a!==2){const m=t.events[r[2]],g=t.events[r[3]];if(m[1].end=Object.assign({},g[1].end),m[1].type="chunkText",m[1].contentType="text",r[3]>r[2]+1){const h=r[2]+1,w=r[3]-r[2]-1;e.add(h,w,[])}}e.add(r[3]+1,0,[["exit",d,t]])}return n!==void 0&&(s.end=Object.assign({},ue(t.events,n)),e.add(n,0,[["exit",s,t]]),s=void 0),s}function Tt(e,t,r,a,n){const s=[],i=ue(t.events,r);n&&(n.end=Object.assign({},i),s.push(["exit",n,t])),a.end=Object.assign({},i),s.push(["exit",a,t]),e.add(r+1,0,s)}function ue(e,t){const r=e[t],a=r[0]==="enter"?"start":"end";return r[1][a]}const Yi={name:"tasklistCheck",tokenize:Xi};function Ji(){return{text:{91:Yi}}}function Xi(e,t,r){const a=this;return n;function n(o){return a.previous!==null||!a._gfmTasklistFirstContentOfListItem?r(o):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(o),e.exit("taskListCheckMarker"),s)}function s(o){return V(o)?(e.enter("taskListCheckValueUnchecked"),e.consume(o),e.exit("taskListCheckValueUnchecked"),i):o===88||o===120?(e.enter("taskListCheckValueChecked"),e.consume(o),e.exit("taskListCheckValueChecked"),i):r(o)}function i(o){return o===93?(e.enter("taskListCheckMarker"),e.consume(o),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):r(o)}function c(o){return he(o)?t(o):te(o)?e.check({tokenize:Zi},t,r)(o):r(o)}}function Zi(e,t,r){return re(e,a,"whitespace");function a(n){return n===null?r(n):t(n)}}function es(e){return xi([Ci(),Li(),qi(e),Ki(),Ji()])}const ts={};function rs(e){const t=this,r=e||ts,a=t.data(),n=a.micromarkExtensions||(a.micromarkExtensions=[]),s=a.fromMarkdownExtensions||(a.fromMarkdownExtensions=[]),i=a.toMarkdownExtensions||(a.toMarkdownExtensions=[]);n.push(es(r)),s.push(pi()),i.push(gi(r))}function $(...e){return e.filter(Boolean).join(" ")}const as=({content:e})=>u.jsx(qe.MarkdownTextPrimitive,{remarkPlugins:[rs],className:"cuadra-aui-md",components:ss,children:e}),Ze=y.memo(as),ns=({language:e,code:t})=>{const{isCopied:r,copyToClipboard:a}=is(),n=()=>{!t||r||a(t)};return u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-gap-4 cuadra-mt-4 cuadra-rounded-t-lg cuadra-bg-muted/50 cuadra-border-b cuadra-border-border cuadra-px-4 cuadra-py-2 cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-font-brand",children:[u.jsx("span",{className:"cuadra-lowercase [&>span]:cuadra-text-xs cuadra-font-brand",children:e}),u.jsxs("button",{onClick:n,className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-muted cuadra-transition-colors","aria-label":"Copy code",children:[!r&&u.jsx(Lr,{className:"cuadra-h-4 cuadra-w-4"}),r&&u.jsx(It,{className:"cuadra-h-4 cuadra-w-4"})]})]})},is=({copiedDuration:e=3e3}={})=>{const[t,r]=y.useState(!1);return{isCopied:t,copyToClipboard:n=>{n&&navigator.clipboard.writeText(n).then(()=>{r(!0),setTimeout(()=>r(!1),e)})}}},ss=qe.unstable_memoizeMarkdownComponents({h1:({className:e,...t})=>u.jsx("h1",{className:$("cuadra-mb-6 cuadra-scroll-m-20 cuadra-text-2xl cuadra-font-normal cuadra-tracking-tight last:cuadra-mb-0 font-brand",e),...t}),h2:({className:e,...t})=>u.jsx("h2",{className:$("cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e),...t}),h3:({className:e,...t})=>u.jsx("h3",{className:$("cuadra-mb-3 cuadra-mt-5 cuadra-scroll-m-20 cuadra-text-lg cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e),...t}),h4:({className:e,...t})=>u.jsx("h4",{className:$("cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e),...t}),h5:({className:e,...t})=>u.jsx("h5",{className:$("cuadra-my-4 cuadra-text-lg cuadra-font-normal first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e),...t}),h6:({className:e,...t})=>u.jsx("h6",{className:$("cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand",e),...t}),p:({className:e,...t})=>u.jsx("p",{className:$("cuadra-mb-5 cuadra-mt-5 cuadra-leading-7 first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e),...t}),a:({className:e,...t})=>u.jsx("a",{className:$("cuadra-text-primary cuadra-font-medium cuadra-underline cuadra-underline-offset-4 font-brand",e),...t}),blockquote:({className:e,...t})=>u.jsx("blockquote",{className:$("cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand",e),...t}),ul:({className:e,...t})=>u.jsx("ul",{className:$("cuadra-my-5 cuadra-ml-6 cuadra-list-disc [&>li]:cuadra-mt-2 font-brand",e),...t}),ol:({className:e,...t})=>u.jsx("ol",{className:$("cuadra-my-5 cuadra-ml-6 cuadra-list-decimal [&>li]:cuadra-mt-2 font-brand",e),...t}),hr:({className:e,...t})=>u.jsx("hr",{className:$("cuadra-my-5 cuadra-border-b",e),...t}),table:({className:e,...t})=>u.jsx("table",{className:$("cuadra-my-5 cuadra-w-full cuadra-border-separate cuadra-border-spacing-0 cuadra-overflow-y-auto font-brand",e),...t}),th:({className:e,...t})=>u.jsx("th",{className:$("cuadra-bg-muted cuadra-px-4 cuadra-py-2 cuadra-text-left cuadra-font-normal first:cuadra-rounded-tl-lg last:cuadra-rounded-tr-lg [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand",e),...t}),td:({className:e,...t})=>u.jsx("td",{className:$("cuadra-border-b cuadra-border-l cuadra-px-4 cuadra-py-2 cuadra-text-left last:cuadra-border-r [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand",e),...t}),tr:({className:e,...t})=>u.jsx("tr",{className:$("cuadra-m-0 cuadra-border-b cuadra-p-0 first:cuadra-border-t [&:last-child>td:first-child]:cuadra-rounded-bl-lg [&:last-child>td:last-child]:cuadra-rounded-br-lg",e),...t}),sup:({className:e,...t})=>u.jsx("sup",{className:$("[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand",e),...t}),pre:({className:e,...t})=>u.jsx("pre",{className:$("cuadra-overflow-x-auto cuadra-whitespace-pre-wrap cuadra-break-words cuadra-rounded-b-lg !cuadra-rounded-t-none cuadra-bg-muted cuadra-p-4 cuadra-text-foreground font-brand",e),...t}),code:function({className:t,...r}){const a=qe.useIsMarkdownCodeBlock();return u.jsx("code",{className:$(!a&&"cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand",t),...r})},CodeHeader:ns});function et({className:e="",variant:t="default",...r}){const a="cuadra-inline-flex cuadra-items-center cuadra-rounded-md cuadra-px-3 cuadra-py-1.5 cuadra-text-xs cuadra-font-medium font-brand",n={default:"cuadra-border cuadra-border-border cuadra-bg-muted cuadra-text-muted-foreground",subtle:"cuadra-border cuadra-border-border/50 cuadra-bg-muted/50 cuadra-text-muted-foreground",outline:"cuadra-border cuadra-border-border cuadra-bg-background cuadra-text-foreground",ghost:"cuadra-text-muted-foreground"};return u.jsx("div",{className:`${a} ${n[t]||n.default} ${e}`,...r})}function os(e){const t=new Map;for(const r of e){const a=t.get(r.filename);(!a||r.score>a.score)&&t.set(r.filename,r)}return Array.from(t.values()).sort((r,a)=>a.score-r.score)}function hr({sources:e,maxVisible:t=3}){if(!e||e.length===0)return null;const r=os(e),a=r.slice(0,t),n=r.length-t;return u.jsxs("div",{className:"cuadra-mt-4 cuadra-pt-3 cuadra-border-t cuadra-border-border",children:[u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1.5 cuadra-mb-2.5",children:[u.jsx(Mt,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground"}),u.jsx("span",{className:"cuadra-text-xs cuadra-font-medium cuadra-text-muted-foreground font-brand",children:"Sources"})]}),u.jsxs("div",{className:"cuadra-flex cuadra-flex-wrap cuadra-gap-2",children:[a.map((s,i)=>u.jsx(ls,{source:s},s.sourceId||i)),n>0&&u.jsxs(et,{variant:"subtle",children:["+",n," more"]})]})]})}function cs(e){switch(e.split(".").pop()?.toLowerCase()){case"csv":case"xlsx":case"xls":return Ur;case"md":case"txt":return Or;default:return Mt}}function ls({source:e}){const{filename:t,score:r}=e,a=cs(t);return u.jsxs(et,{className:"cuadra-gap-2 cuadra-cursor-default",title:r<1?`${Math.round(r*100)}% relevant`:void 0,children:[u.jsx(a,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-shrink-0 cuadra-opacity-60"}),u.jsx("span",{className:"cuadra-truncate cuadra-max-w-[180px]",children:t}),r<1&&r>0&&u.jsxs("span",{className:"cuadra-opacity-50 cuadra-text-[10px] cuadra-tabular-nums",children:[Math.round(r*100),"%"]})]})}const us=y.forwardRef(function({welcomeTitle:t="What shall we explore today?",welcomeSubtitle:r,extraTopPadding:a,suggestions:n,inputPlaceholder:s="Reply...",enableAttachments:i=!1,preMadeResponseDelay:c=1e3,streamingSpeed:o=50,safeArea:l=!1,composerBorder:f=!1,models:d,selectedModelId:m,onModelChange:g,showChatHeader:h=!1},w){const x=T.useThreadRuntime(),b=T.useAssistantApi(),[C,v]=y.useState(!1),[P,N]=y.useState(null),[I,q]=y.useState(!1),M=y.useSyncExternalStore(de.subscribe,de.getSnapshot);y.useEffect(()=>{if(M){const A=setTimeout(()=>de.clear(),4e3);return()=>clearTimeout(A)}},[M]);const U=T.useThread(A=>{const R=A.messages;return!R||R.length===0}),p=U&&!C,L=y.useCallback((A,R,k)=>{if(!I)try{const j=k?.streamingSpeed??o,_=k?.delay??c;Ft(A,R,j,_),b.composer().setText(A),setTimeout(()=>{b.composer().send()},10)}catch{}},[I,o,c,b]),W=y.useCallback(A=>{try{b.composer().setText(A),setTimeout(()=>{b.composer().send()},10)}catch{}},[b]),H=y.useCallback(async A=>{if(!(I||!x))try{if(A.response){const R=A.responseDelay??c;await L(A.prompt,A.response,{delay:R,streamingSpeed:o})}else W(A.prompt)}catch{}},[x,I,c,o,L,W]),K=y.useCallback(async()=>{try{const R=window.__cuadraThreadListRuntime?.threadList;R?.switchToNewThread&&await R.switchToNewThread()}catch{}},[]);return y.useImperativeHandle(w,()=>({sendMessage:W,sendPreMadeQA:L,clearChat:K}),[W,L,K]),y.useEffect(()=>{if(!x){v(!1);return}try{const A=x?.store;if(!A){v(!1);return}const R=A.subscribe?.(j=>{const _=j?.threadId,F=j?.messages||[],D=j?.isLoadingHistory||!1,S=F.length;_&&_!==P&&N(_),v(D&&S===0)}),k=A.getState?.();if(k){const j=k?.threadId,_=k?.messages||[],F=k?.isLoadingHistory||!1,D=_.length;j&&j!==P&&N(j),v(F&&D===0)}return()=>{R&&R()}}catch{v(!1)}},[x,P]),u.jsxs(T.ThreadPrimitive.Root,{className:"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full cuadra-relative",children:[h&&u.jsx(xs,{}),u.jsxs(T.ComposerPrimitive.AttachmentDropzone,{disabled:!i,className:`cuadra-flex-1 cuadra-flex cuadra-flex-col cuadra-min-h-0 cuadra-relative ${p?"cuadra-justify-center":""}`,children:[u.jsx("div",{className:"cuadra-dropzone-overlay cuadra-pointer-events-none cuadra-absolute cuadra-inset-0 cuadra-z-50 cuadra-flex cuadra-items-center cuadra-justify-center cuadra-rounded-lg cuadra-transition-opacity cuadra-duration-200",style:{opacity:0},children:u.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-3",children:[u.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-14 cuadra-rounded-2xl",style:{backgroundColor:"var(--cuadra-primary)",color:"white"},children:u.jsx(Yr,{className:"cuadra-h-6 cuadra-w-6"})}),u.jsx("p",{className:"cuadra-text-sm cuadra-font-medium cuadra-text-foreground font-brand",children:"Drop files here"})]})}),u.jsx(T.ThreadPrimitive.Viewport,{className:`cuadra-w-full cuadra-bg-inherit cuadra-relative scrollbar-thin ${p?"cuadra-flex-none":"cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto"}`,style:{paddingTop:p?"0":a||(h?"0.5rem":"2rem")},children:C?u.jsx("div",{className:"cuadra-absolute cuadra-inset-0 cuadra-flex cuadra-items-center cuadra-justify-center",children:u.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-3",children:[u.jsx(At,{className:"cuadra-h-5 cuadra-w-5 cuadra-animate-spin cuadra-text-muted-foreground"}),u.jsx("p",{className:"cuadra-text-sm cuadra-text-muted-foreground font-brand",children:"Loading messages..."})]})}):u.jsxs("div",{className:"cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full cuadra-px-4",children:[u.jsx(T.ThreadPrimitive.Empty,{children:u.jsx(ds,{title:t,subtitle:r})}),u.jsx(T.ThreadPrimitive.Messages,{components:{UserMessage:hs,AssistantMessage:ps}})]})}),u.jsx("div",{className:`cuadra-w-full cuadra-px-4 cuadra-pt-2 ${p?"cuadra-pb-2":"cuadra-pb-4"}`,style:l?{paddingBottom:"calc(env(safe-area-inset-bottom) + 1rem)"}:void 0,children:u.jsxs("div",{className:"cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full",children:[M&&u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-mb-2 cuadra-px-3 cuadra-py-2 cuadra-rounded-lg cuadra-text-xs font-brand cuadra-animate-in cuadra-fade-in cuadra-slide-in-from-bottom-2",style:{backgroundColor:"var(--cuadra-muted)",color:"var(--cuadra-foreground)",opacity:.85},children:[u.jsx(Er,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-flex-shrink-0 cuadra-text-muted-foreground"}),u.jsx("span",{className:"cuadra-flex-1 cuadra-text-muted-foreground",children:M.message}),u.jsx("button",{type:"button",onClick:()=>de.clear(),className:"cuadra-flex-shrink-0 cuadra-p-0.5 cuadra-rounded hover:cuadra-bg-black/5 cuadra-transition-colors","aria-label":"Dismiss",children:u.jsx(ut,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})]}),i&&u.jsx(T.ComposerPrimitive.Attachments,{components:{Attachment:()=>{const A=T.useAssistantState(({attachment:R})=>R);return A?u.jsxs("div",{className:"cuadra-relative cuadra-inline-flex cuadra-items-center cuadra-gap-2 cuadra-mb-2 cuadra-px-3 cuadra-py-1.5 cuadra-rounded-lg cuadra-transition-colors",style:{backgroundColor:"var(--cuadra-muted)",border:"1px solid rgba(0,0,0,0.06)"},children:[u.jsx(Nt,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground",strokeWidth:1.5}),u.jsx("span",{className:"cuadra-text-xs cuadra-text-foreground font-brand",children:A.name||"Attachment"}),u.jsx(T.AttachmentPrimitive.Remove,{asChild:!0,children:u.jsx("button",{type:"button",className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-4 cuadra-rounded-full hover:cuadra-bg-background/60 cuadra-transition-colors cuadra-ml-1","aria-label":"Remove attachment",children:u.jsx(ut,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})})]}):null}}}),u.jsxs(T.ComposerPrimitive.Root,{className:"cuadra-relative cuadra-w-full cuadra-rounded-2xl cuadra-transition-shadow cuadra-duration-300 cuadra-flex cuadra-flex-col",style:{backgroundColor:"var(--cuadra-composer)",boxShadow:"var(--cuadra-composer-shadow)",border:f?"1px solid hsl(var(--cuadra-border))":"none"},children:[u.jsx(T.ComposerPrimitive.Input,{asChild:!0,children:u.jsx("textarea",{rows:1,placeholder:s,className:"cuadra-flex cuadra-min-h-[44px] cuadra-w-full cuadra-rounded-t-2xl cuadra-border-0 cuadra-bg-transparent cuadra-px-4 cuadra-pt-3.5 cuadra-pb-1 cuadra-text-base cuadra-text-foreground placeholder:cuadra-text-muted-foreground focus-visible:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-resize-none font-brand",style:{fontSize:"1rem",lineHeight:"1.5"}})}),u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-px-3 cuadra-pb-2.5 cuadra-pt-1",children:[u.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1",children:i&&u.jsx(T.ComposerPrimitive.AddAttachment,{multiple:!0,asChild:!0,children:u.jsxs("button",{type:"button",className:"cuadra-group cuadra-relative cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-8 cuadra-rounded-lg hover:cuadra-bg-muted/60 cuadra-transition-colors","aria-label":"Attach files",children:[u.jsx(_t,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground",strokeWidth:1.5}),u.jsx("span",{className:"cuadra-pointer-events-none cuadra-absolute cuadra-bottom-full cuadra-left-1/2 cuadra--translate-x-1/2 cuadra-mb-1.5 cuadra-whitespace-nowrap cuadra-rounded-md cuadra-px-2.5 cuadra-py-1 cuadra-text-xs cuadra-text-foreground cuadra-opacity-0 group-hover:cuadra-opacity-100 cuadra-transition-opacity cuadra-duration-150 cuadra-delay-300 font-brand",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"},children:"Attach files"})]})})}),u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[d&&d.length>0&&u.jsx(gs,{models:d,selectedModelId:m,onModelChange:g,threadIsEmpty:U,onNewChat:K}),u.jsx(T.ComposerPrimitive.Send,{asChild:!0,children:u.jsx("button",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-8 cuadra-rounded-full cuadra-transition-all cuadra-duration-200 hover:cuadra-opacity-90 disabled:cuadra-opacity-30 disabled:cuadra-cursor-not-allowed",style:{backgroundColor:"var(--cuadra-primary)",color:"white"},"aria-label":"Send message",type:"button",children:u.jsx(Mr,{className:"cuadra-h-4 cuadra-w-4",strokeWidth:2})})})]})]})]})]})}),p&&n&&n.length>0&&u.jsx("div",{className:"cuadra-flex cuadra-flex-wrap cuadra-justify-center cuadra-gap-2 cuadra-px-4 cuadra-pb-6 cuadra-pt-1 cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full",children:n.map((A,R)=>u.jsx("button",{type:"button",onClick:()=>H(A),disabled:I,className:"cuadra-px-3.5 cuadra-py-2 cuadra-rounded-full cuadra-text-sm cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-all cuadra-duration-200 font-brand cuadra-cursor-pointer disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed",style:{backgroundColor:"var(--cuadra-composer)",boxShadow:"0 0 0 1px rgba(0,0,0,0.06)"},children:A.prompt},`suggestion-${R}`))})]})]})});function ds({title:e,subtitle:t}){return u.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-text-center cuadra-py-6",children:[u.jsx("h2",{className:"cuadra-text-4xl cuadra-font-normal cuadra-text-muted-foreground cuadra-tracking-tight",style:{fontFamily:"var(--cuadra-font-logo), Outfit, -apple-system, sans-serif"},children:e}),t&&u.jsx("p",{className:"cuadra-text-base cuadra-text-muted-foreground/70 cuadra-mt-3 cuadra-max-w-lg cuadra-whitespace-pre-line",children:t})]})}function hs(){return u.jsx(T.MessagePrimitive.Root,{className:"cuadra-flex cuadra-w-full cuadra-justify-end cuadra-py-2.5",children:u.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-end cuadra-gap-2 cuadra-max-w-[80%]",children:[u.jsx(T.MessagePrimitive.Attachments,{components:{Attachment:()=>{const e=T.useAssistantState(({attachment:s})=>s);if(!e)return null;const t=e.type==="image",r=e.file,a=e.content?.find(s=>s.type==="image"),n=r?URL.createObjectURL(r):a?.image;return u.jsx("div",{className:"cuadra-mb-1",children:t&&n?u.jsx("img",{src:n,alt:e.name||"Attachment",className:"cuadra-rounded-2xl cuadra-max-h-64 cuadra-max-w-full cuadra-object-contain",style:{border:"1px solid rgba(0,0,0,0.06)"}}):u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-rounded-xl cuadra-px-3 cuadra-py-2",style:{backgroundColor:"var(--cuadra-muted)",border:"1px solid rgba(0,0,0,0.06)"},children:[u.jsx(Nt,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground"}),u.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground font-brand",children:e.name||"Attachment"})]})})}}}),u.jsx("div",{className:"cuadra-break-words cuadra-text-foreground font-brand",style:{borderRadius:"1.25rem",backgroundColor:"var(--cuadra-muted)",paddingLeft:"1rem",paddingRight:"1rem",paddingTop:"0.625rem",paddingBottom:"0.625rem",wordBreak:"break-word",fontSize:"0.9375rem",lineHeight:"1.625"},children:u.jsx(T.MessagePrimitive.Parts,{components:{Text:({text:e})=>u.jsx(Ze,{content:e||""})}})})]})})}function fs({text:e}){const[t,r]=y.useState(!1),a=T.useAssistantState(({message:n})=>n?.status?.type==="running");return e?a?u.jsx("div",{className:"cuadra-mb-3 cuadra-py-1",children:u.jsx("div",{className:"cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand cuadra-animate-text-shimmer",children:e})}):u.jsxs("div",{className:"cuadra-mb-3",children:[u.jsxs("button",{type:"button",onClick:()=>r(!t),className:"cuadra-flex cuadra-items-center cuadra-gap-1.5 cuadra-py-1 cuadra-text-sm cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-colors font-brand",children:[u.jsx(Ke,{className:`cuadra-h-3.5 cuadra-w-3.5 cuadra-shrink-0 cuadra-transition-transform cuadra-duration-200 ${t?"":"cuadra--rotate-90"}`}),u.jsx("span",{children:"Reasoning"})]}),u.jsx("div",{className:`cuadra-overflow-hidden cuadra-transition-all cuadra-duration-200 cuadra-ease-out ${t?"cuadra-max-h-[2000px] cuadra-opacity-100":"cuadra-max-h-0 cuadra-opacity-0"}`,children:u.jsx("div",{className:"cuadra-pl-5 cuadra-pt-2 cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand",children:u.jsx(Ze,{content:e})})})]}):null}function ms(){return u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2.5 cuadra-text-muted-foreground cuadra-text-sm font-brand cuadra-py-3",children:[u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1",children:[u.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"0ms",backgroundColor:"var(--cuadra-primary)",opacity:.7}}),u.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"150ms",backgroundColor:"var(--cuadra-primary)",opacity:.5}}),u.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"300ms",backgroundColor:"var(--cuadra-primary)",opacity:.3}})]}),u.jsx("span",{children:"Thinking..."})]})}function ps(){const e=T.useAssistantState(({message:i})=>i?.status?.type==="running"),t=T.useAssistantState(({message:i})=>{const c=i?.content;return!c||!Array.isArray(c)?!1:c.some(o=>!!(o.type==="text"&&o.text&&o.text.length>0||o.type==="reasoning"&&o.text&&o.text.length>0))}),r=y.useRef(!1),[a,n]=y.useState(null);y.useEffect(()=>{if(e&&t&&!r.current){const i=ee.getCurrentMessageId();i&&(r.current=!0,n(i))}},[e,t]);const s=y.useSyncExternalStore(i=>ee.subscribe(i),()=>{if(a){const i=ee.getForMessage(a);return i.sources?.length?i.sources:null}if(e&&t){const i=ee.getCurrentMessageId();if(i){const c=ee.getForMessage(i);return c.sources?.length?c.sources:null}}return null},()=>null);return u.jsx(T.MessagePrimitive.Root,{className:"cuadra-flex cuadra-w-full cuadra-justify-start cuadra-py-2.5",children:u.jsxs("div",{className:"cuadra-text-foreground cuadra-max-w-full cuadra-break-words font-brand",style:{fontSize:"0.9375rem",lineHeight:"1.75"},children:[u.jsx(T.MessagePrimitive.Parts,{components:{Text:({text:i})=>u.jsx(Ze,{content:i||""}),Reasoning:({text:i})=>u.jsx(fs,{text:i||""})}}),e&&!t&&u.jsx(ms,{}),s&&s.length>0&&u.jsx(hr,{sources:s})]})})}function Te({label:e,children:t}){return u.jsxs("span",{className:"cuadra-relative cuadra-inline-flex cuadra-group/tip",children:[t,u.jsx("span",{className:"cuadra-absolute cuadra-bottom-full cuadra-left-1/2 cuadra-mb-1.5 cuadra-hidden group-hover/tip:cuadra-flex cuadra-items-center cuadra-whitespace-nowrap cuadra-rounded-md cuadra-px-2 cuadra-py-1 cuadra-text-[10px] cuadra-pointer-events-none cuadra-z-50 font-brand",style:{backgroundColor:"var(--cuadra-popover)",color:"var(--cuadra-foreground)",boxShadow:"0 2px 8px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)",transform:"translateX(-50%)"},children:e})]})}function gs({models:e,selectedModelId:t,onModelChange:r,threadIsEmpty:a,onNewChat:n}){const[s,i]=y.useState(!1),c=e.find(l=>l.id===t)||e[0];if(!c)return null;const o=async l=>{i(!1),!a&&l!==t&&await n?.(),r?.(l)};return u.jsxs("div",{className:"cuadra-relative",children:[u.jsxs("button",{type:"button",onClick:()=>i(!s),className:"cuadra-flex cuadra-items-center cuadra-gap-1 cuadra-px-2.5 cuadra-py-1.5 cuadra-rounded-lg cuadra-text-xs cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-colors font-brand",children:[u.jsx("span",{children:c.name}),c.supportsReasoning&&u.jsx(Te,{label:"Reasoning",children:u.jsx(ct,{className:"cuadra-h-3 cuadra-w-3"})}),c.supportsVision&&u.jsx(Te,{label:"Vision",children:u.jsx(lt,{className:"cuadra-h-3 cuadra-w-3"})}),u.jsx(Ke,{className:"cuadra-h-3 cuadra-w-3"})]}),s&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:()=>i(!1)}),u.jsx("div",{className:"cuadra-absolute cuadra-bottom-full cuadra-right-0 cuadra-mb-2 cuadra-z-50 cuadra-rounded-xl cuadra-min-w-[200px] cuadra-py-1",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 4px 24px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)"},children:e.map(l=>u.jsxs("button",{type:"button",className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-justify-between cuadra-gap-3 cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted/60 cuadra-transition-colors font-brand",onClick:()=>o(l.id),children:[u.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-min-w-0",children:[u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1.5",children:[u.jsx("span",{className:"cuadra-text-foreground cuadra-truncate",children:l.name}),l.supportsReasoning&&u.jsx(Te,{label:"Reasoning",children:u.jsx(ct,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})}),l.supportsVision&&u.jsx(Te,{label:"Vision",children:u.jsx(lt,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})})]}),l.description&&u.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground",children:l.description})]}),l.id===t&&u.jsx(It,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-primary cuadra-flex-shrink-0"})]},l.id))})]})]})}function xs(){const e=T.useAssistantState(({threadListItem:n})=>n?.title??null),[t,r]=y.useState(!1),a=e||"Untitled chat";return u.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-px-3 cuadra-py-2 cuadra-min-h-[48px]",children:u.jsxs("div",{className:"cuadra-relative",children:[u.jsxs("button",{type:"button",onClick:()=>r(!t),className:"cuadra-flex cuadra-items-center cuadra-gap-1 cuadra-text-sm cuadra-text-foreground hover:cuadra-bg-muted/60 cuadra-rounded-lg cuadra-px-2 cuadra-py-1.5 cuadra-transition-colors font-brand",children:[u.jsx("span",{className:"cuadra-font-medium cuadra-truncate cuadra-max-w-[200px]",children:a}),u.jsx(Ke,{className:`cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground cuadra-flex-shrink-0 cuadra-transition-transform cuadra-duration-200 ${t?"cuadra-rotate-180":""}`})]}),t&&u.jsx(ys,{onClose:()=>r(!1)})]})})}function ys({onClose:e}){return u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:e}),u.jsx("div",{className:"cuadra-absolute cuadra-left-0 cuadra-top-full cuadra-mt-1 cuadra-z-50 cuadra-w-[300px] cuadra-rounded-xl cuadra-overflow-hidden cuadra-flex cuadra-flex-col",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 4px 24px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)"},children:u.jsxs(T.ThreadListPrimitive.Root,{className:"cuadra-flex cuadra-flex-col",children:[u.jsx("div",{className:"cuadra-px-2 cuadra-py-1.5",children:u.jsxs(T.ThreadListPrimitive.New,{className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-gap-2.5 cuadra-px-3 cuadra-py-2 cuadra-rounded-lg cuadra-text-sm cuadra-text-foreground hover:cuadra-bg-muted cuadra-transition-colors cuadra-cursor-pointer font-brand",onClick:e,children:[u.jsx(_t,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"New Chat"]})}),u.jsx(bs,{onSelect:e})]})})]})}function bs({onSelect:e}){const t=T.useAssistantState(({threads:n})=>n?.threadIds??[]),r=T.useAssistantState(({threads:n})=>n?.newThreadId);return t.some(n=>n!==r)?u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"cuadra-mx-3 cuadra-my-0.5",style:{borderTop:"1px solid rgba(0,0,0,0.06)"}}),u.jsx("div",{className:"cuadra-overflow-y-auto cuadra-px-2 cuadra-pb-1.5 scrollbar-thin",style:{maxHeight:"340px"},children:u.jsx(T.ThreadListPrimitive.Items,{components:{ThreadListItem:n=>u.jsx(ws,{...n,onSelect:e})}})})]}):null}function ws({onSelect:e}){const t=T.useThreadListItem(),r=T.useThreadListItemRuntime(),a=T.useAssistantRuntime(),n=T.useThread(x=>x.threadId),s=t?.id===n,[i,c]=y.useState(!1),[o,l]=y.useState(!1),[f,d]=y.useState(t?.title||""),[m,g]=y.useState(!1),h=async()=>{if(!t?.remoteId||!f||f===t.title){l(!1);return}try{g(!0),await r.rename(f)}catch{}finally{g(!1),l(!1)}},w=async x=>{x.stopPropagation();try{await r.delete(),s&&await a.switchToNewThread()}catch(b){console.error("[CuadraChat] Failed to delete thread:",b)}};return y.useEffect(()=>{t?.title&&!o&&d(t.title)},[t?.title,o]),t?u.jsxs(T.ThreadListItemPrimitive.Root,{className:`cuadra-relative cuadra-flex cuadra-items-center cuadra-rounded-lg cuadra-transition-colors cuadra-cursor-pointer ${s?"cuadra-bg-muted":"hover:cuadra-bg-muted/60"}`,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:[o?u.jsx("div",{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0",onClick:x=>x.stopPropagation(),onMouseDown:x=>x.stopPropagation(),onKeyDown:x=>x.stopPropagation(),onKeyUp:x=>x.stopPropagation(),onKeyPress:x=>x.stopPropagation(),children:u.jsx("input",{className:"cuadra-w-full cuadra-bg-transparent cuadra-border-0 cuadra-border-b cuadra-text-sm cuadra-text-foreground cuadra-py-0.5 cuadra-px-0 cuadra-outline-none font-brand",style:{borderBottomColor:"var(--cuadra-primary)",borderBottomWidth:"1.5px"},value:f,onChange:x=>d(x.target.value),onKeyDown:x=>{x.stopPropagation(),x.key==="Enter"&&h(),x.key==="Escape"&&(l(!1),d(t.title||""))},onBlur:()=>void h(),disabled:m,autoFocus:!0})}):u.jsx(T.ThreadListItemPrimitive.Trigger,{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0 cuadra-cursor-pointer",onClick:()=>e?.(),children:u.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground cuadra-truncate cuadra-block cuadra-text-left font-brand",children:t.title||"Chat"})}),(i||s)&&!o&&u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-0.5 cuadra-mr-1.5 cuadra-flex-shrink-0",children:[u.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-background/60 cuadra-transition-colors",onClick:x=>{x.stopPropagation(),l(!0),d(t.title||"Chat")},title:"Rename",children:u.jsx(Wr,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})}),u.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-destructive/10 cuadra-transition-colors",onClick:w,title:"Delete",children:u.jsx(Qr,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-destructive"})})]})]}):null}const Oe=({children:e,className:t="",paddingX:r="px-0",paddingY:a="py-0",borderSizePx:n=2,style:s,contentStyle:i})=>u.jsx("div",{className:`cuadra-relative cuadra-bg-background md:cuadra-rounded-lg cuadra-overflow-hidden cuadra-flex cuadra-flex-col ${r} ${a} ${t}`,style:{border:n>0?`${n}px solid var(--cuadra-primary)`:"none",...s,...i},children:e}),ks=y.createContext(void 0),Be=({children:e,value:t})=>u.jsx(ks.Provider,{value:t,children:e});function Cs(){y.useEffect(()=>{if(document.querySelector("style[data-cuadra-uikit]"))return;const t=document.createElement("div");t.className="cuadra-flex",document.body.appendChild(t);const r=window.getComputedStyle(t).display==="flex";if(document.body.removeChild(t),r)return;const a=document.createElement("link");a.setAttribute("data-cuadra-uikit","true"),a.rel="stylesheet",a.type="text/css";const n=["/node_modules/@cuadra-ai/uikit/dist/uikit.css",new URL("../dist/uikit.css",typeof document>"u"?require("url").pathToFileURL(__filename).href:fe&&fe.tagName.toUpperCase()==="SCRIPT"&&fe.src||new URL("index.cjs",document.baseURI).href).href];let s=!1;for(const i of n)if(a.href=i,a.onload=()=>{s=!0},a.onerror=()=>{},document.head.appendChild(a),s)break},[])}const vs=y.forwardRef(function({config:t},r){Cs();const a=y.useRef(null),n=y.useRef(!1),{baseUrl:s,proxyUrl:i,sessionToken:c,mode:o="multiChat",modelMode:l="fixed",modelId:f,onModelChange:d,ephemeral:m=!1,systemPrompt:g,enableReasoning:h=!1,initialThreadId:w,welcomeTitle:x,welcomeSubtitle:b,extraTopPadding:C,suggestions:v,inputPlaceholder:P,preMadeResponseDelay:N=1e3,streamingSpeed:I=50,initialMessage:q,initialPreMadeQA:M,theme:U="system",onError:p,onChatCreated:L,onUserMessage:W,onThreadIdUpdate:H,enableAttachments:K=!1,supportsVision:A,onBeforeRequest:R,mockResponseOnBlocked:k}=t;y.useImperativeHandle(r,()=>({sendMessage:E=>{a.current?.sendMessage(E)},sendPreMadeQA:(E,Z,ie)=>{a.current?.sendPreMadeQA(E,Z,ie)},clearChat:()=>{a.current?.clearChat()}}),[]),y.useEffect(()=>{if(n.current)return;const E=setTimeout(()=>{M?(n.current=!0,a.current?.sendPreMadeQA(M.question,M.answer,{delay:N,streamingSpeed:I})):q&&(n.current=!0,a.current?.sendMessage(q))},500);return()=>clearTimeout(E)},[q,M,N,I]);const j=i||s||"",_=!!i,F=y.useMemo(()=>new Et(j,c||void 0,_),[j,c,_]),[D,S]=y.useState(null),[O,Y]=y.useState(!1),[J,ge]=y.useState(null),[Ee,X]=y.useState(!1);y.useEffect(()=>{o==="multiChat"&&X(!0)},[o]);const ne=y.useCallback(async()=>{if(l==="selector"){Y(!0),ge(null);try{const E=await F.listModels();S(E)}catch(E){ge(E instanceof Error?E:new Error("Failed to load models"))}finally{Y(!1)}}},[F,l]);y.useEffect(()=>{l==="selector"&&ne()},[l,ne]),y.useEffect(()=>(typeof window<"u"&&(window.__cuadraUIKitRefetchModels=ne),()=>{typeof window<"u"&&delete window.__cuadraUIKitRefetchModels}),[ne]);const[Q,rt]=y.useState(l==="fixed"&&f||null),at=y.useRef(Q),ke=y.useCallback(E=>{const Z=at.current;rt(E),at.current=E,d?.(E),Z!==null&&Z!==E&&o==="multiChat"&&setTimeout(()=>{const ie=window.__cuadraThreadListRuntime;if(ie?.threads?.switchToNewThread)try{ie.threads.switchToNewThread()}catch{}else if(ie?.threads?.createThread)try{ie.threads.createThread()}catch{}else if(ie?.switchToNewThread)try{ie.switchToNewThread()}catch{}},100)},[d,o]);y.useEffect(()=>{if(l==="selector"&&D?.items&&D.items.length>0&&!Q){const E=D.items[0];if(E?.id){const Z=E.id;rt(Z),d?.(Z)}}},[l,D?.items,Q,d]);const xr=l==="fixed"?!!f:!!Q,yr=y.useMemo(()=>A!==void 0?A:l==="selector"&&Q&&D?.items?D.items.find(Z=>Z.id===Q)?.supportsVision??!0:!0,[A,l,Q,D?.items]),Re=y.useMemo(()=>(D?.items||[]).filter(E=>E?.id&&E?.displayName).map(E=>({id:E.id,name:E.displayName,supportsVision:E.supportsVision??!1,supportsReasoning:E.supportsReasoning??!1})),[D]),Le=y.useMemo(()=>({currentModelId:Q||"",models:Re,modelsLoading:O,modelsError:J,onModelChange:ke,refetchModels:ne}),[Q,Re,O,J,ke,ne]);return l==="selector"&&O||o==="multiChat"&&Ee?u.jsx(Be,{value:Le,children:u.jsx(Oe,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",borderSizePx:t.borderless?0:2,children:u.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:u.jsx(At,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"})})})}):l==="selector"&&!xr&&J?u.jsx(Be,{value:Le,children:u.jsx(Oe,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",children:u.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:u.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2",children:u.jsx("p",{className:"cuadra-text-sm cuadra-text-destructive font-brand",children:"Failed to load models"})})})})}):u.jsx("div",{className:"cuadra-uikit cuadra-h-full cuadra-w-full",style:{height:"100%",width:"100%"},children:u.jsx(Be,{value:Le,children:u.jsx(Sa,{baseUrl:_?j:s||j,sessionToken:c,isProxyMode:_,mode:o,modelMode:l,modelId:Q||f||void 0,onModelChange:ke,ephemeral:m,systemPrompt:g,enableReasoning:h,initialThreadId:w,enableAttachments:K,supportsVision:yr,onError:p,onChatCreated:L,onUserMessage:W,onThreadIdUpdate:H,onBeforeRequest:R,mockResponseOnBlocked:k,onChatsLoaded:()=>{o==="multiChat"&&X(!1)},children:u.jsx(Oe,{paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",className:`cuadra-h-full ${t.containerClass||""}`,borderSizePx:t.borderless?0:2,style:{height:"100%"},children:u.jsx("div",{className:"cuadra-h-full cuadra-flex cuadra-relative",style:{height:"100%"},children:u.jsx("div",{className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:u.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0",children:u.jsx(us,{ref:a,welcomeTitle:x,welcomeSubtitle:b,extraTopPadding:C,suggestions:v,inputPlaceholder:P,enableAttachments:K,preMadeResponseDelay:N,streamingSpeed:I,safeArea:t.safeArea,showChatHeader:o==="multiChat",models:l==="selector"?Re:void 0,selectedModelId:Q||void 0,onModelChange:l==="selector"?ke:void 0,theme:U})})})})})})})})});function fr(e,t=":root"){if(typeof document>"u")return;const r=document.documentElement,a=[];if(e.light){js(e.light,r);const n=jt(e.light);n&&a.push(`.cuadra-uikit { ${n} }`)}if(e.dark){const n=jt(e.dark);n&&(a.push(`.dark { ${n} }`),a.push(`.dark .cuadra-uikit { ${n} }`))}if(a.length>0){let n=document.getElementById("cuadra-theme-custom");n||(n=document.createElement("style"),n.id="cuadra-theme-custom",document.head.appendChild(n)),n.textContent=a.join(`
21
- `)}}const Ts={background:"background",foreground:"foreground",card:"card",cardForeground:"card-foreground",popover:"popover",popoverForeground:"popover-foreground",primary:"primary",primaryForeground:"primary-foreground",primaryLight:"primary-light",primaryLighter:"primary-lighter",secondary:"secondary",secondaryForeground:"secondary-foreground",muted:"muted",mutedForeground:"muted-foreground",accent:"accent",accentForeground:"accent-foreground",border:"border",input:"input",ring:"ring",destructive:"destructive",destructiveForeground:"destructive-foreground",success:"success",successForeground:"success-foreground",info:"info",infoForeground:"info-foreground",warning:"warning",warningForeground:"warning-foreground"};function mr(e){const t=Ts[e];return t?`--cuadra-${t}`:`--cuadra-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function js(e,t){Object.entries(e).forEach(([r,a])=>{if(a){const n=mr(r);t.style.setProperty(n,a)}})}function jt(e){return Object.entries(e).map(([t,r])=>r?`${mr(t)}: ${r};`:"").filter(Boolean).join(" ")}function Ss(){if(typeof document>"u")return;const e=document.documentElement;Array.from(e.style).filter(n=>n.startsWith("--cuadra-")).forEach(n=>e.style.removeProperty(n));const r=document.getElementById("cuadra-theme-custom");r&&r.remove();const a=document.getElementById("cuadra-theme-dark");a&&a.remove()}function Is({onReset:e,error:t}){return u.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-h-full cuadra-p-6 cuadra-text-center",children:[u.jsx("div",{className:"cuadra-mb-4",children:u.jsx("svg",{className:"cuadra-w-12 cuadra-h-12 cuadra-text-destructive cuadra-mx-auto",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:u.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),u.jsx("h3",{className:"cuadra-text-lg cuadra-font-medium cuadra-text-foreground cuadra-mb-2",children:"Something went wrong"}),u.jsx("p",{className:"cuadra-text-sm cuadra-text-muted-foreground cuadra-mb-4 cuadra-max-w-sm",children:t?.message||"An unexpected error occurred. Please try again."}),u.jsx("button",{onClick:e,className:"cuadra-px-4 cuadra-py-2 cuadra-text-sm cuadra-font-medium cuadra-rounded-md cuadra-transition-colors",style:{backgroundColor:"var(--cuadra-primary)",color:"hsl(var(--cuadra-primary-foreground))"},children:"Try Again"})]})}class tt extends y.Component{constructor(r){super(r);z(this,"reset",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,a){this.props.onError?.(r,a)}render(){if(this.state.hasError){const{fallback:r}=this.props,{error:a}=this.state;return typeof r=="function"?r(a,this.reset):r||u.jsx(Is,{error:a,onReset:this.reset})}return this.props.children}}function Ms(e,t){const r=a=>u.jsx(tt,{...t,children:u.jsx(e,{...a})});return r.displayName=`withErrorBoundary(${e.displayName||e.name||"Component"})`,r}const pe=y.createContext(null);pe.displayName="CuadraChatContext";function As(){const e=y.useContext(pe);if(e===null)throw new Error("useCuadraChat must be used within a CuadraChatProvider. Wrap your component tree with <CuadraChatProvider>...</CuadraChatProvider>");return{controls:e.controls,isReady:e.controls!==null}}function Ns(){const e=y.useContext(pe);return e===null?null:{controls:e.controls,isReady:e.controls!==null}}function _s({children:e}){const[t,r]=y.useState(null),a=y.useCallback(i=>{r(i)},[]),n=y.useCallback(()=>{r(null)},[]),s=y.useMemo(()=>({controls:t,registerControls:a,unregisterControls:n}),[t,a,n]);return u.jsx(pe.Provider,{value:s,children:e})}function pr(e){return"connection"in e&&typeof e.connection=="object"}function gr(e){return pr(e)?Ps(e):Es(e)}function Ps(e){return{connection:{baseUrl:e.connection.baseUrl||"",proxyUrl:e.connection.proxyUrl||"",sessionToken:e.connection.sessionToken??null},chat:{mode:e.chat?.mode??"multiChat",modelMode:e.chat?.modelMode??"fixed",modelId:e.chat?.modelId??"",systemPrompt:e.chat?.systemPrompt??"",ephemeral:e.chat?.ephemeral??!1,enableReasoning:e.chat?.enableReasoning??!1,enableAttachments:e.chat?.enableAttachments??!1,supportsVision:e.chat?.supportsVision,initialThreadId:e.chat?.initialThreadId},ui:{theme:e.ui?.theme??"system",customTheme:e.ui?.customTheme,showThemeToggle:e.ui?.showThemeToggle??!0,language:e.ui?.language,welcomeTitle:e.ui?.welcomeTitle??"Hi, how can I help you today?",welcomeSubtitle:e.ui?.welcomeSubtitle??"Start exploring our platform and discover what you can build.",suggestions:e.ui?.suggestions,inputPlaceholder:e.ui?.inputPlaceholder??"Type your message...",extraTopPadding:e.ui?.extraTopPadding,borderless:e.ui?.borderless,safeArea:e.ui?.safeArea,orgName:e.ui?.orgName,primaryColor:e.ui?.primaryColor},preMade:{responseDelay:e.preMade?.responseDelay??1e3,streamingSpeed:e.preMade?.streamingSpeed??50},initial:{message:e.initial?.message,preMadeQA:e.initial?.preMadeQA},interceptors:{onBeforeRequest:e.interceptors?.onBeforeRequest,mockResponseOnBlocked:e.interceptors?.mockResponseOnBlocked},callbacks:{onChatCreated:e.callbacks?.onChatCreated,onError:e.callbacks?.onError,onUserMessage:e.callbacks?.onUserMessage,onModelChange:e.callbacks?.onModelChange,onThreadIdUpdate:e.callbacks?.onThreadIdUpdate,onLogout:e.callbacks?.onLogout},className:e.className,errorFallback:e.errorFallback}}function Es(e){return typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[CuadraUIKit] Using legacy flat props format. Consider migrating to grouped props for better organization.
22
- See: https://docs.cuadra.ai/guides/uikit-migration`),{connection:{baseUrl:e.baseUrl||"",proxyUrl:e.proxyUrl||"",sessionToken:e.sessionToken??null},chat:{mode:e.mode??"multiChat",modelMode:e.modelMode??"fixed",modelId:e.modelId??"",systemPrompt:e.systemPrompt??"",ephemeral:e.ephemeral??!1,enableReasoning:e.enableReasoning??!1,enableAttachments:e.enableAttachments??!1,supportsVision:e.supportsVision,initialThreadId:e.initialThreadId},ui:{theme:e.theme??"system",customTheme:e.customTheme,showThemeToggle:e.showThemeToggle??!0,language:e.language,welcomeTitle:e.welcomeTitle??"Hi, how can I help you today?",welcomeSubtitle:e.welcomeSubtitle??"Start exploring our platform and discover what you can build.",suggestions:e.suggestions,inputPlaceholder:e.inputPlaceholder??"Type your message...",extraTopPadding:e.extraTopPadding,borderless:!1,safeArea:!1,orgName:void 0,primaryColor:void 0},preMade:{responseDelay:e.preMadeResponseDelay??1e3,streamingSpeed:e.streamingSpeed??50},initial:{message:e.initialMessage,preMadeQA:e.initialPreMadeQA},interceptors:{onBeforeRequest:e.onBeforeRequest,mockResponseOnBlocked:e.mockResponseOnBlocked},callbacks:{onChatCreated:e.onChatCreated,onError:e.onError,onUserMessage:e.onUserMessage,onModelChange:e.onModelChange,onThreadIdUpdate:e.onThreadIdUpdate,onLogout:e.onLogout},className:e.className,errorFallback:e.errorFallback}}const Rs=y.forwardRef(function({config:t},r){const a=y.useRef(null),n=y.useContext(pe);y.useEffect(()=>{t.ui.customTheme&&fr(t.ui.customTheme)},[t.ui.customTheme]),y.useEffect(()=>{if(t.ui.primaryColor&&typeof document<"u"){const c=document.documentElement,o=l=>{const f=l.replace("#",""),d=parseInt(f.slice(0,2),16)/255,m=parseInt(f.slice(2,4),16)/255,g=parseInt(f.slice(4,6),16)/255,h=Math.max(d,m,g),w=Math.min(d,m,g);let x=0,b=0;const C=(h+w)/2;if(h!==w){const v=h-w;switch(b=C>.5?v/(2-h-w):v/(h+w),h){case d:x=((m-g)/v+(m<g?6:0))/6;break;case m:x=((g-d)/v+2)/6;break;case g:x=((d-m)/v+4)/6;break}}return`${Math.round(x*360)} ${Math.round(b*100)}% ${Math.round(C*100)}%`};try{const l=o(t.ui.primaryColor);c.style.setProperty("--primary",l),c.style.setProperty("--cuadra-primary",`hsl(${l})`)}catch{}return()=>{c.style.removeProperty("--primary"),c.style.removeProperty("--cuadra-primary")}}},[t.ui.primaryColor]);const s=y.useMemo(()=>({sendMessage:c=>a.current?.sendMessage(c),sendPreMadeQA:(c,o,l)=>a.current?.sendPreMadeQA(c,o,l),clearChat:()=>a.current?.clearChat()}),[]);y.useImperativeHandle(r,()=>s,[]),y.useEffect(()=>{if(n)return n.registerControls(s),()=>n.unregisterControls()},[n,s]),y.useEffect(()=>(typeof window<"u"&&(process.env.NODE_ENV==="development"&&console.warn("[CuadraUIKit] window.__cuadraChatControls is deprecated. Use CuadraChatProvider and useCuadraChat() hook instead. See: https://docs.cuadra.ai/guides/uikit-migration"),window.__cuadraChatControls=s),()=>{typeof window<"u"&&delete window.__cuadraChatControls}),[s]);const i={baseUrl:t.connection.baseUrl||void 0,proxyUrl:t.connection.proxyUrl||void 0,sessionToken:t.connection.sessionToken,mode:t.chat.mode,modelMode:t.chat.modelMode,modelId:t.chat.modelId||void 0,systemPrompt:t.chat.systemPrompt||void 0,ephemeral:t.chat.ephemeral,enableReasoning:t.chat.enableReasoning,enableAttachments:t.chat.enableAttachments,supportsVision:t.chat.supportsVision,initialThreadId:t.chat.initialThreadId,theme:t.ui.theme,showThemeToggle:t.ui.showThemeToggle,language:t.ui.language,welcomeTitle:t.ui.welcomeTitle,welcomeSubtitle:t.ui.welcomeSubtitle,suggestions:t.ui.suggestions,inputPlaceholder:t.ui.inputPlaceholder,extraTopPadding:t.ui.extraTopPadding,containerClass:t.className,borderless:t.ui.borderless,safeArea:t.ui.safeArea,orgName:t.ui.orgName,primaryColor:t.ui.primaryColor,preMadeResponseDelay:t.preMade.responseDelay,streamingSpeed:t.preMade.streamingSpeed,initialMessage:t.initial.message,initialPreMadeQA:t.initial.preMadeQA,onBeforeRequest:t.interceptors.onBeforeRequest,mockResponseOnBlocked:t.interceptors.mockResponseOnBlocked,onChatCreated:t.callbacks.onChatCreated,onError:t.callbacks.onError,onUserMessage:t.callbacks.onUserMessage,onModelChange:t.callbacks.onModelChange,onThreadIdUpdate:t.callbacks.onThreadIdUpdate,onLogout:t.callbacks.onLogout};return u.jsx(vs,{ref:a,config:i})}),Ls=y.forwardRef(function(t,r){const a=gr(t),n=a.errorFallback;return u.jsx(tt,{fallback:n,onError:(s,i)=>{a.callbacks.onError?.(s),process.env.NODE_ENV==="development"&&console.error("[CuadraChat] Error caught by boundary:",s,i)},children:u.jsx(Rs,{ref:r,config:a})})});exports.AttachmentValidationError=le;exports.Badge=et;exports.CuadraChat=Ls;exports.CuadraChatContext=pe;exports.CuadraChatProvider=_s;exports.CuadraErrorBoundary=tt;exports.SourceCitations=hr;exports.applyTheme=fr;exports.createAttachmentAdapter=Qe;exports.escapeHtml=aa;exports.generateSecureUUID=Pt;exports.isV2Props=pr;exports.isValidUrl=ea;exports.normalizeCuadraChatProps=gr;exports.removeTheme=Ss;exports.sanitizeSystemPrompt=Zr;exports.streamingMetadataStore=ee;exports.useCuadraChat=As;exports.useCuadraChatOptional=Ns;exports.validateBaseUrl=ta;exports.withErrorBoundary=Ms;
15
+ `});return d(),m(),f+`
16
+ `+(i===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
17
+ `))+1))}const n="#".repeat(i),c=t.enter("headingAtx"),o=t.enter("phrasing");s.move(n+" ");let u=t.containerPhrasing(e,{before:"# ",after:`
18
+ `,...s.current()});return/^[\t ]/.test(u)&&(u=we(u.charCodeAt(0))+u.slice(1)),u=u?n+" "+u:n,t.options.closeAtx&&(u+=" "+n),o(),c(),u}Jt.peek=Vn;function Jt(e){return e.value||""}function Vn(){return"<"}Xt.peek=Wn;function Xt(e,r,t,a){const i=tt(t),s=i==='"'?"Quote":"Apostrophe",n=t.enter("image");let c=t.enter("label");const o=t.createTracker(a);let u=o.move("![");return u+=o.move(t.safe(e.alt,{before:u,after:"]",...o.current()})),u+=o.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=t.enter("destinationLiteral"),u+=o.move("<"),u+=o.move(t.safe(e.url,{before:u,after:">",...o.current()})),u+=o.move(">")):(c=t.enter("destinationRaw"),u+=o.move(t.safe(e.url,{before:u,after:e.title?" ":")",...o.current()}))),c(),e.title&&(c=t.enter(`title${s}`),u+=o.move(" "+i),u+=o.move(t.safe(e.title,{before:u,after:i,...o.current()})),u+=o.move(i),c()),u+=o.move(")"),n(),u}function Wn(){return"!"}Zt.peek=Hn;function Zt(e,r,t,a){const i=e.referenceType,s=t.enter("imageReference");let n=t.enter("label");const c=t.createTracker(a);let o=c.move("![");const u=t.safe(e.alt,{before:o,after:"]",...c.current()});o+=c.move(u+"]["),n();const m=t.stack;t.stack=[],n=t.enter("reference");const d=t.safe(t.associationId(e),{before:o,after:"]",...c.current()});return n(),t.stack=m,s(),i==="full"||!u||u!==d?o+=c.move(d+"]"):i==="shortcut"?o=o.slice(0,-1):o+=c.move("]"),o}function Hn(){return"!"}er.peek=Kn;function er(e,r,t){let a=e.value||"",i="`",s=-1;for(;new RegExp("(^|[^`])"+i+"([^`]|$)").test(a);)i+="`";for(/[^ \r\n]/.test(a)&&(/^[ \r\n]/.test(a)&&/[ \r\n]$/.test(a)||/^`|`$/.test(a))&&(a=" "+a+" ");++s<t.unsafe.length;){const n=t.unsafe[s],c=t.compilePattern(n);let o;if(n.atBreak)for(;o=c.exec(a);){let u=o.index;a.charCodeAt(u)===10&&a.charCodeAt(u-1)===13&&u--,a=a.slice(0,u)+" "+a.slice(o.index+1)}}return i+a+i}function Kn(){return"`"}function tr(e,r){const t=Gt(e);return!!(!r.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(t===e.url||"mailto:"+t===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}rr.peek=Qn;function rr(e,r,t,a){const i=tt(t),s=i==='"'?"Quote":"Apostrophe",n=t.createTracker(a);let c,o;if(tr(e,t)){const m=t.stack;t.stack=[],c=t.enter("autolink");let d=n.move("<");return d+=n.move(t.containerPhrasing(e,{before:d,after:">",...n.current()})),d+=n.move(">"),c(),t.stack=m,d}c=t.enter("link"),o=t.enter("label");let u=n.move("[");return u+=n.move(t.containerPhrasing(e,{before:u,after:"](",...n.current()})),u+=n.move("]("),o(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(o=t.enter("destinationLiteral"),u+=n.move("<"),u+=n.move(t.safe(e.url,{before:u,after:">",...n.current()})),u+=n.move(">")):(o=t.enter("destinationRaw"),u+=n.move(t.safe(e.url,{before:u,after:e.title?" ":")",...n.current()}))),o(),e.title&&(o=t.enter(`title${s}`),u+=n.move(" "+i),u+=n.move(t.safe(e.title,{before:u,after:i,...n.current()})),u+=n.move(i),o()),u+=n.move(")"),c(),u}function Qn(e,r,t){return tr(e,t)?"<":"["}ar.peek=Gn;function ar(e,r,t,a){const i=e.referenceType,s=t.enter("linkReference");let n=t.enter("label");const c=t.createTracker(a);let o=c.move("[");const u=t.containerPhrasing(e,{before:o,after:"]",...c.current()});o+=c.move(u+"]["),n();const m=t.stack;t.stack=[],n=t.enter("reference");const d=t.safe(t.associationId(e),{before:o,after:"]",...c.current()});return n(),t.stack=m,s(),i==="full"||!u||u!==d?o+=c.move(d+"]"):i==="shortcut"?o=o.slice(0,-1):o+=c.move("]"),o}function Gn(){return"["}function rt(e){const r=e.options.bullet||"*";if(r!=="*"&&r!=="+"&&r!=="-")throw new Error("Cannot serialize items with `"+r+"` for `options.bullet`, expected `*`, `+`, or `-`");return r}function Yn(e){const r=rt(e),t=e.options.bulletOther;if(!t)return r==="*"?"-":"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(t===r)throw new Error("Expected `bullet` (`"+r+"`) and `bulletOther` (`"+t+"`) to be different");return t}function Jn(e){const r=e.options.bulletOrdered||".";if(r!=="."&&r!==")")throw new Error("Cannot serialize items with `"+r+"` for `options.bulletOrdered`, expected `.` or `)`");return r}function nr(e){const r=e.options.rule||"*";if(r!=="*"&&r!=="-"&&r!=="_")throw new Error("Cannot serialize rules with `"+r+"` for `options.rule`, expected `*`, `-`, or `_`");return r}function Xn(e,r,t,a){const i=t.enter("list"),s=t.bulletCurrent;let n=e.ordered?Jn(t):rt(t);const c=e.ordered?n==="."?")":".":Yn(t);let o=r&&t.bulletLastUsed?n===t.bulletLastUsed:!1;if(!e.ordered){const m=e.children?e.children[0]:void 0;if((n==="*"||n==="-")&&m&&(!m.children||!m.children[0])&&t.stack[t.stack.length-1]==="list"&&t.stack[t.stack.length-2]==="listItem"&&t.stack[t.stack.length-3]==="list"&&t.stack[t.stack.length-4]==="listItem"&&t.indexStack[t.indexStack.length-1]===0&&t.indexStack[t.indexStack.length-2]===0&&t.indexStack[t.indexStack.length-3]===0&&(o=!0),nr(t)===n&&m){let d=-1;for(;++d<e.children.length;){const f=e.children[d];if(f&&f.type==="listItem"&&f.children&&f.children[0]&&f.children[0].type==="thematicBreak"){o=!0;break}}}}o&&(n=c),t.bulletCurrent=n;const u=t.containerFlow(e,a);return t.bulletLastUsed=n,t.bulletCurrent=s,i(),u}function Zn(e){const r=e.options.listItemIndent||"one";if(r!=="tab"&&r!=="one"&&r!=="mixed")throw new Error("Cannot serialize items with `"+r+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return r}function ei(e,r,t,a){const i=Zn(t);let s=t.bulletCurrent||rt(t);r&&r.type==="list"&&r.ordered&&(s=(typeof r.start=="number"&&r.start>-1?r.start:1)+(t.options.incrementListMarker===!1?0:r.children.indexOf(e))+s);let n=s.length+1;(i==="tab"||i==="mixed"&&(r&&r.type==="list"&&r.spread||e.spread))&&(n=Math.ceil(n/4)*4);const c=t.createTracker(a);c.move(s+" ".repeat(n-s.length)),c.shift(n);const o=t.enter("listItem"),u=t.indentLines(t.containerFlow(e,c.current()),m);return o(),u;function m(d,f,x){return f?(x?"":" ".repeat(n))+d:(x?s:s+" ".repeat(n-s.length))+d}}function ti(e,r,t,a){const i=t.enter("paragraph"),s=t.enter("phrasing"),n=t.containerPhrasing(e,a);return s(),i(),n}const ri=_e(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function ai(e,r,t,a){return(e.children.some(function(n){return ri(n)})?t.containerPhrasing:t.containerFlow).call(t,e,a)}function ni(e){const r=e.options.strong||"*";if(r!=="*"&&r!=="_")throw new Error("Cannot serialize strong with `"+r+"` for `options.strong`, expected `*`, or `_`");return r}ir.peek=ii;function ir(e,r,t,a){const i=ni(t),s=t.enter("strong"),n=t.createTracker(a),c=n.move(i+i);let o=n.move(t.containerPhrasing(e,{after:i,before:c,...n.current()}));const u=o.charCodeAt(0),m=Ae(a.before.charCodeAt(a.before.length-1),u,i);m.inside&&(o=we(u)+o.slice(1));const d=o.charCodeAt(o.length-1),f=Ae(a.after.charCodeAt(0),d,i);f.inside&&(o=o.slice(0,-1)+we(d));const x=n.move(i+i);return s(),t.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+o+x}function ii(e,r,t){return t.options.strong||"*"}function si(e,r,t,a){return t.safe(e.value,a)}function oi(e){const r=e.options.ruleRepetition||3;if(r<3)throw new Error("Cannot serialize rules with repetition `"+r+"` for `options.ruleRepetition`, expected `3` or more");return r}function ci(e,r,t){const a=(nr(t)+(t.options.ruleSpaces?" ":"")).repeat(oi(t));return t.options.ruleSpaces?a.slice(0,-1):a}const sr={blockquote:Mn,break:kt,code:Rn,definition:Dn,emphasis:Qt,hardBreak:kt,heading:qn,html:Jt,image:Xt,imageReference:Zt,inlineCode:er,link:rr,linkReference:ar,list:Xn,listItem:ei,paragraph:ti,root:ai,strong:ir,text:si,thematicBreak:ci};function ui(){return{enter:{table:li,tableData:vt,tableHeader:vt,tableRow:hi},exit:{codeText:fi,table:di,tableData:qe,tableHeader:qe,tableRow:qe}}}function li(e){const r=e._align;this.enter({type:"table",align:r.map(function(t){return t==="none"?null:t}),children:[]},e),this.data.inTable=!0}function di(e){this.exit(e),this.data.inTable=void 0}function hi(e){this.enter({type:"tableRow",children:[]},e)}function qe(e){this.exit(e)}function vt(e){this.enter({type:"tableCell",children:[]},e)}function fi(e){let r=this.resume();this.data.inTable&&(r=r.replace(/\\([\\|])/g,mi));const t=this.stack[this.stack.length-1];t.type,t.value=r,this.exit(e)}function mi(e,r){return r==="|"?r:e}function pi(e){const r=e||{},t=r.tableCellPadding,a=r.tablePipeAlign,i=r.stringLength,s=t?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
19
+ `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:n,tableCell:o,tableRow:c}};function n(x,h,w,b){return u(m(x,w,b),x.align)}function c(x,h,w,b){const g=d(x,w,b),C=u([g]);return C.slice(0,C.indexOf(`
20
+ `))}function o(x,h,w,b){const g=w.enter("tableCell"),C=w.enter("phrasing"),v=w.containerPhrasing(x,{...b,before:s,after:s});return C(),g(),v}function u(x,h){return Sn(x,{align:h,alignDelimiters:a,padding:t,stringLength:i})}function m(x,h,w){const b=x.children;let g=-1;const C=[],v=h.enter("table");for(;++g<b.length;)C[g]=d(b[g],h,w);return v(),C}function d(x,h,w){const b=x.children;let g=-1;const C=[],v=h.enter("tableRow");for(;++g<b.length;)C[g]=o(b[g],x,h,w);return v(),C}function f(x,h,w){let b=sr.inlineCode(x,h,w);return w.stack.includes("tableCell")&&(b=b.replace(/\|/g,"\\$&")),b}}function gi(){return{exit:{taskListCheckValueChecked:jt,taskListCheckValueUnchecked:jt,paragraph:yi}}}function xi(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:bi}}}function jt(e){const r=this.stack[this.stack.length-2];r.type,r.checked=e.type==="taskListCheckValueChecked"}function yi(e){const r=this.stack[this.stack.length-2];if(r&&r.type==="listItem"&&typeof r.checked=="boolean"){const t=this.stack[this.stack.length-1];t.type;const a=t.children[0];if(a&&a.type==="text"){const i=r.children;let s=-1,n;for(;++s<i.length;){const c=i[s];if(c.type==="paragraph"){n=c;break}}n===t&&(a.value=a.value.slice(1),a.value.length===0?t.children.shift():t.position&&a.position&&typeof a.position.start.offset=="number"&&(a.position.start.column++,a.position.start.offset++,t.position.start=Object.assign({},a.position.start)))}}this.exit(e)}function bi(e,r,t,a){const i=e.children[0],s=typeof e.checked=="boolean"&&i&&i.type==="paragraph",n="["+(e.checked?"x":" ")+"] ",c=t.createTracker(a);s&&c.move(n);let o=sr.listItem(e,r,t,{...a,...c.current()});return s&&(o=o.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),o;function u(m){return m+n}}function wi(){return[Qa(),gn(),wn(),ui(),gi()]}function ki(e){return{extensions:[Ga(),xn(e),kn(),pi(e),xi()]}}function Te(e,r,t,a){const i=e.length;let s=0,n;if(r<0?r=-r>i?0:i+r:r=r>i?i:r,t=t>0?t:0,a.length<1e4)n=Array.from(a),n.unshift(r,t),e.splice(...n);else for(t&&e.splice(r,t);s<a.length;)n=a.slice(s,s+1e4),n.unshift(r,0),e.splice(...n),s+=1e4,r+=1e4}const Tt={}.hasOwnProperty;function Ci(e){const r={};let t=-1;for(;++t<e.length;)vi(r,e[t]);return r}function vi(e,r){let t;for(t in r){const i=(Tt.call(e,t)?e[t]:void 0)||(e[t]={}),s=r[t];let n;if(s)for(n in s){Tt.call(i,n)||(i[n]=[]);const c=s[n];ji(i[n],Array.isArray(c)?c:c?[c]:[])}}}function ji(e,r){let t=-1;const a=[];for(;++t<r.length;)(r[t].add==="after"?e:a).push(r[t]);Te(e,0,0,a)}const Ti={tokenize:Pi,partial:!0},or={tokenize:_i,partial:!0},cr={tokenize:Ei,partial:!0},ur={tokenize:Ri,partial:!0},Si={tokenize:Li,partial:!0},lr={name:"wwwAutolink",tokenize:Ai,previous:hr},dr={name:"protocolAutolink",tokenize:Ni,previous:fr},ae={name:"emailAutolink",tokenize:Mi,previous:mr},G={};function Ii(){return{text:G}}let se=48;for(;se<123;)G[se]=ae,se++,se===58?se=65:se===91&&(se=97);G[43]=ae;G[45]=ae;G[46]=ae;G[95]=ae;G[72]=[ae,dr];G[104]=[ae,dr];G[87]=[ae,lr];G[119]=[ae,lr];function Mi(e,r,t){const a=this;let i,s;return n;function n(d){return!Je(d)||!mr.call(a,a.previous)||at(a.events)?t(d):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(d))}function c(d){return Je(d)?(e.consume(d),c):d===64?(e.consume(d),o):t(d)}function o(d){return d===46?e.check(Si,m,u)(d):d===45||d===95||et(d)?(s=!0,e.consume(d),o):m(d)}function u(d){return e.consume(d),i=!0,o}function m(d){return s&&i&&be(a.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),r(d)):t(d)}}function Ai(e,r,t){const a=this;return i;function i(n){return n!==87&&n!==119||!hr.call(a,a.previous)||at(a.events)?t(n):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(Ti,e.attempt(or,e.attempt(cr,s),t),t)(n))}function s(n){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),r(n)}}function Ni(e,r,t){const a=this;let i="",s=!1;return n;function n(d){return(d===72||d===104)&&fr.call(a,a.previous)&&!at(a.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),i+=String.fromCodePoint(d),e.consume(d),c):t(d)}function c(d){if(be(d)&&i.length<5)return i+=String.fromCodePoint(d),e.consume(d),c;if(d===58){const f=i.toLowerCase();if(f==="http"||f==="https")return e.consume(d),o}return t(d)}function o(d){return d===47?(e.consume(d),s?u:(s=!0,o)):t(d)}function u(d){return d===null||Ra(d)||V(d)||oe(d)||Ne(d)?t(d):e.attempt(or,e.attempt(cr,m),t)(d)}function m(d){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),r(d)}}function Pi(e,r,t){let a=0;return i;function i(n){return(n===87||n===119)&&a<3?(a++,e.consume(n),i):n===46&&a===3?(e.consume(n),s):t(n)}function s(n){return n===null?t(n):r(n)}}function _i(e,r,t){let a,i,s;return n;function n(u){return u===46||u===95?e.check(ur,o,c)(u):u===null||V(u)||oe(u)||u!==45&&Ne(u)?o(u):(s=!0,e.consume(u),n)}function c(u){return u===95?a=!0:(i=a,a=void 0),e.consume(u),n}function o(u){return i||a||!s?t(u):r(u)}}function Ei(e,r){let t=0,a=0;return i;function i(n){return n===40?(t++,e.consume(n),i):n===41&&a<t?s(n):n===33||n===34||n===38||n===39||n===41||n===42||n===44||n===46||n===58||n===59||n===60||n===63||n===93||n===95||n===126?e.check(ur,r,s)(n):n===null||V(n)||oe(n)?r(n):(e.consume(n),i)}function s(n){return n===41&&a++,e.consume(n),i}}function Ri(e,r,t){return a;function a(c){return c===33||c===34||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===63||c===95||c===126?(e.consume(c),a):c===38?(e.consume(c),s):c===93?(e.consume(c),i):c===60||c===null||V(c)||oe(c)?r(c):t(c)}function i(c){return c===null||c===40||c===91||V(c)||oe(c)?r(c):a(c)}function s(c){return be(c)?n(c):t(c)}function n(c){return c===59?(e.consume(c),a):be(c)?(e.consume(c),n):t(c)}}function Li(e,r,t){return a;function a(s){return e.consume(s),i}function i(s){return et(s)?t(s):r(s)}}function hr(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||V(e)}function fr(e){return!be(e)}function mr(e){return!(e===47||Je(e))}function Je(e){return e===43||e===45||e===46||e===95||et(e)}function at(e){let r=e.length,t=!1;for(;r--;){const a=e[r][1];if((a.type==="labelLink"||a.type==="labelImage")&&!a._balanced){t=!0;break}if(a._gfmAutolinkLiteralWalkedInto){t=!1;break}}return e.length>0&&!t&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),t}function Di(e,r,t){const a=[];let i=-1;for(;++i<e.length;){const s=e[i].resolveAll;s&&!a.includes(s)&&(r=s(r,t),a.push(s))}return r}function re(e,r,t,a){const i=a?a-1:Number.POSITIVE_INFINITY;let s=0;return n;function n(o){return te(o)?(e.enter(t),c(o)):r(o)}function c(o){return te(o)&&s++<i?(e.consume(o),c):(e.exit(t),r(o))}}const Fi={partial:!0,tokenize:Ui};function Ui(e,r,t){return a;function a(s){return te(s)?re(e,i,"linePrefix")(s):i(s)}function i(s){return s===null||fe(s)?r(s):t(s)}}const zi={tokenize:Ki,partial:!0};function $i(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Vi,continuation:{tokenize:Wi},exit:Hi}},text:{91:{name:"gfmFootnoteCall",tokenize:qi},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Oi,resolveTo:Bi}}}}function Oi(e,r,t){const a=this;let i=a.events.length;const s=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let n;for(;i--;){const o=a.events[i][1];if(o.type==="labelImage"){n=o;break}if(o.type==="gfmFootnoteCall"||o.type==="labelLink"||o.type==="label"||o.type==="image"||o.type==="link")break}return c;function c(o){if(!n||!n._balanced)return t(o);const u=ke(a.sliceSerialize({start:n.end,end:a.now()}));return u.codePointAt(0)!==94||!s.includes(u.slice(1))?t(o):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(o),e.exit("gfmFootnoteCallLabelMarker"),r(o))}}function Bi(e,r){let t=e.length;for(;t--;)if(e[t][1].type==="labelImage"&&e[t][0]==="enter"){e[t][1];break}e[t+1][1].type="data",e[t+3][1].type="gfmFootnoteCallLabelMarker";const a={type:"gfmFootnoteCall",start:Object.assign({},e[t+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:"gfmFootnoteCallMarker",start:Object.assign({},e[t+3][1].end),end:Object.assign({},e[t+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;const s={type:"gfmFootnoteCallString",start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},n={type:"chunkString",contentType:"string",start:Object.assign({},s.start),end:Object.assign({},s.end)},c=[e[t+1],e[t+2],["enter",a,r],e[t+3],e[t+4],["enter",i,r],["exit",i,r],["enter",s,r],["enter",n,r],["exit",n,r],["exit",s,r],e[e.length-2],e[e.length-1],["exit",a,r]];return e.splice(t,e.length-t+1,...c),e}function qi(e,r,t){const a=this,i=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let s=0,n;return c;function c(d){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),o}function o(d){return d!==94?t(d):(e.enter("gfmFootnoteCallMarker"),e.consume(d),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(d){if(s>999||d===93&&!n||d===null||d===91||V(d))return t(d);if(d===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return i.includes(ke(a.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),r):t(d)}return V(d)||(n=!0),s++,e.consume(d),d===92?m:u}function m(d){return d===91||d===92||d===93?(e.consume(d),s++,u):u(d)}}function Vi(e,r,t){const a=this,i=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let s,n=0,c;return o;function o(h){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(h),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(h){return h===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(h),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",m):t(h)}function m(h){if(n>999||h===93&&!c||h===null||h===91||V(h))return t(h);if(h===93){e.exit("chunkString");const w=e.exit("gfmFootnoteDefinitionLabelString");return s=ke(a.sliceSerialize(w)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(h),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return V(h)||(c=!0),n++,e.consume(h),h===92?d:m}function d(h){return h===91||h===92||h===93?(e.consume(h),n++,m):m(h)}function f(h){return h===58?(e.enter("definitionMarker"),e.consume(h),e.exit("definitionMarker"),i.includes(s)||i.push(s),re(e,x,"gfmFootnoteDefinitionWhitespace")):t(h)}function x(h){return r(h)}}function Wi(e,r,t){return e.check(Fi,r,e.attempt(zi,r,t))}function Hi(e){e.exit("gfmFootnoteDefinition")}function Ki(e,r,t){const a=this;return re(e,i,"gfmFootnoteDefinitionIndent",5);function i(s){const n=a.events[a.events.length-1];return n&&n[1].type==="gfmFootnoteDefinitionIndent"&&n[2].sliceSerialize(n[1],!0).length===4?r(s):t(s)}}function Qi(e){let t=(e||{}).singleTilde;const a={name:"strikethrough",tokenize:s,resolveAll:i};return t==null&&(t=!0),{text:{126:a},insideSpan:{null:[a]},attentionMarkers:{null:[126]}};function i(n,c){let o=-1;for(;++o<n.length;)if(n[o][0]==="enter"&&n[o][1].type==="strikethroughSequenceTemporary"&&n[o][1]._close){let u=o;for(;u--;)if(n[u][0]==="exit"&&n[u][1].type==="strikethroughSequenceTemporary"&&n[u][1]._open&&n[o][1].end.offset-n[o][1].start.offset===n[u][1].end.offset-n[u][1].start.offset){n[o][1].type="strikethroughSequence",n[u][1].type="strikethroughSequence";const m={type:"strikethrough",start:Object.assign({},n[u][1].start),end:Object.assign({},n[o][1].end)},d={type:"strikethroughText",start:Object.assign({},n[u][1].end),end:Object.assign({},n[o][1].start)},f=[["enter",m,c],["enter",n[u][1],c],["exit",n[u][1],c],["enter",d,c]],x=c.parser.constructs.insideSpan.null;x&&Te(f,f.length,0,Di(x,n.slice(u+1,o),c)),Te(f,f.length,0,[["exit",d,c],["enter",n[o][1],c],["exit",n[o][1],c],["exit",m,c]]),Te(n,u-1,o-u+3,f),o=u+f.length-2;break}}for(o=-1;++o<n.length;)n[o][1].type==="strikethroughSequenceTemporary"&&(n[o][1].type="data");return n}function s(n,c,o){const u=this.previous,m=this.events;let d=0;return f;function f(h){return u===126&&m[m.length-1][1].type!=="characterEscape"?o(h):(n.enter("strikethroughSequenceTemporary"),x(h))}function x(h){const w=Me(u);if(h===126)return d>1?o(h):(n.consume(h),d++,x);if(d<2&&!t)return o(h);const b=n.exit("strikethroughSequenceTemporary"),g=Me(h);return b._open=!g||g===2&&!!w,b._close=!w||w===2&&!!g,c(h)}}}class Gi{constructor(){this.map=[]}add(r,t,a){Yi(this,r,t,a)}consume(r){if(this.map.sort(function(s,n){return s[0]-n[0]}),this.map.length===0)return;let t=this.map.length;const a=[];for(;t>0;)t-=1,a.push(r.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),r.length=this.map[t][0];a.push(r.slice()),r.length=0;let i=a.pop();for(;i;){for(const s of i)r.push(s);i=a.pop()}this.map.length=0}}function Yi(e,r,t,a){let i=0;if(!(t===0&&a.length===0)){for(;i<e.map.length;){if(e.map[i][0]===r){e.map[i][1]+=t,e.map[i][2].push(...a);return}i+=1}e.map.push([r,t,a])}}function Ji(e,r){let t=!1;const a=[];for(;r<e.length;){const i=e[r];if(t){if(i[0]==="enter")i[1].type==="tableContent"&&a.push(e[r+1][1].type==="tableDelimiterMarker"?"left":"none");else if(i[1].type==="tableContent"){if(e[r-1][1].type==="tableDelimiterMarker"){const s=a.length-1;a[s]=a[s]==="left"?"center":"right"}}else if(i[1].type==="tableDelimiterRow")break}else i[0]==="enter"&&i[1].type==="tableDelimiterRow"&&(t=!0);r+=1}return a}function Xi(){return{flow:{null:{name:"table",tokenize:Zi,resolveAll:es}}}}function Zi(e,r,t){const a=this;let i=0,s=0,n;return c;function c(p){let L=a.events.length-1;for(;L>-1;){const K=a.events[L][1].type;if(K==="lineEnding"||K==="linePrefix")L--;else break}const W=L>-1?a.events[L][1].type:null,H=W==="tableHead"||W==="tableRow"?I:o;return H===I&&a.parser.lazy[a.now().line]?t(p):H(p)}function o(p){return e.enter("tableHead"),e.enter("tableRow"),u(p)}function u(p){return p===124||(n=!0,s+=1),m(p)}function m(p){return p===null?t(p):fe(p)?s>1?(s=0,a.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),x):t(p):te(p)?re(e,m,"whitespace")(p):(s+=1,n&&(n=!1,i+=1),p===124?(e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),n=!0,m):(e.enter("data"),d(p)))}function d(p){return p===null||p===124||V(p)?(e.exit("data"),m(p)):(e.consume(p),p===92?f:d)}function f(p){return p===92||p===124?(e.consume(p),d):d(p)}function x(p){return a.interrupt=!1,a.parser.lazy[a.now().line]?t(p):(e.enter("tableDelimiterRow"),n=!1,te(p)?re(e,h,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(p):h(p))}function h(p){return p===45||p===58?b(p):p===124?(n=!0,e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),w):N(p)}function w(p){return te(p)?re(e,b,"whitespace")(p):b(p)}function b(p){return p===58?(s+=1,n=!0,e.enter("tableDelimiterMarker"),e.consume(p),e.exit("tableDelimiterMarker"),g):p===45?(s+=1,g(p)):p===null||fe(p)?_(p):N(p)}function g(p){return p===45?(e.enter("tableDelimiterFiller"),C(p)):N(p)}function C(p){return p===45?(e.consume(p),C):p===58?(n=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(p),e.exit("tableDelimiterMarker"),v):(e.exit("tableDelimiterFiller"),v(p))}function v(p){return te(p)?re(e,_,"whitespace")(p):_(p)}function _(p){return p===124?h(p):p===null||fe(p)?!n||i!==s?N(p):(e.exit("tableDelimiterRow"),e.exit("tableHead"),r(p)):N(p)}function N(p){return t(p)}function I(p){return e.enter("tableRow"),q(p)}function q(p){return p===124?(e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),q):p===null||fe(p)?(e.exit("tableRow"),r(p)):te(p)?re(e,q,"whitespace")(p):(e.enter("data"),M(p))}function M(p){return p===null||p===124||V(p)?(e.exit("data"),q(p)):(e.consume(p),p===92?U:M)}function U(p){return p===92||p===124?(e.consume(p),M):M(p)}}function es(e,r){let t=-1,a=!0,i=0,s=[0,0,0,0],n=[0,0,0,0],c=!1,o=0,u,m,d;const f=new Gi;for(;++t<e.length;){const x=e[t],h=x[1];x[0]==="enter"?h.type==="tableHead"?(c=!1,o!==0&&(St(f,r,o,u,m),m=void 0,o=0),u={type:"table",start:Object.assign({},h.start),end:Object.assign({},h.end)},f.add(t,0,[["enter",u,r]])):h.type==="tableRow"||h.type==="tableDelimiterRow"?(a=!0,d=void 0,s=[0,0,0,0],n=[0,t+1,0,0],c&&(c=!1,m={type:"tableBody",start:Object.assign({},h.start),end:Object.assign({},h.end)},f.add(t,0,[["enter",m,r]])),i=h.type==="tableDelimiterRow"?2:m?3:1):i&&(h.type==="data"||h.type==="tableDelimiterMarker"||h.type==="tableDelimiterFiller")?(a=!1,n[2]===0&&(s[1]!==0&&(n[0]=n[1],d=je(f,r,s,i,void 0,d),s=[0,0,0,0]),n[2]=t)):h.type==="tableCellDivider"&&(a?a=!1:(s[1]!==0&&(n[0]=n[1],d=je(f,r,s,i,void 0,d)),s=n,n=[s[1],t,0,0])):h.type==="tableHead"?(c=!0,o=t):h.type==="tableRow"||h.type==="tableDelimiterRow"?(o=t,s[1]!==0?(n[0]=n[1],d=je(f,r,s,i,t,d)):n[1]!==0&&(d=je(f,r,n,i,t,d)),i=0):i&&(h.type==="data"||h.type==="tableDelimiterMarker"||h.type==="tableDelimiterFiller")&&(n[3]=t)}for(o!==0&&St(f,r,o,u,m),f.consume(r.events),t=-1;++t<r.events.length;){const x=r.events[t];x[0]==="enter"&&x[1].type==="table"&&(x[1]._align=Ji(r.events,t))}return e}function je(e,r,t,a,i,s){const n=a===1?"tableHeader":a===2?"tableDelimiter":"tableData",c="tableContent";t[0]!==0&&(s.end=Object.assign({},de(r.events,t[0])),e.add(t[0],0,[["exit",s,r]]));const o=de(r.events,t[1]);if(s={type:n,start:Object.assign({},o),end:Object.assign({},o)},e.add(t[1],0,[["enter",s,r]]),t[2]!==0){const u=de(r.events,t[2]),m=de(r.events,t[3]),d={type:c,start:Object.assign({},u),end:Object.assign({},m)};if(e.add(t[2],0,[["enter",d,r]]),a!==2){const f=r.events[t[2]],x=r.events[t[3]];if(f[1].end=Object.assign({},x[1].end),f[1].type="chunkText",f[1].contentType="text",t[3]>t[2]+1){const h=t[2]+1,w=t[3]-t[2]-1;e.add(h,w,[])}}e.add(t[3]+1,0,[["exit",d,r]])}return i!==void 0&&(s.end=Object.assign({},de(r.events,i)),e.add(i,0,[["exit",s,r]]),s=void 0),s}function St(e,r,t,a,i){const s=[],n=de(r.events,t);i&&(i.end=Object.assign({},n),s.push(["exit",i,r])),a.end=Object.assign({},n),s.push(["exit",a,r]),e.add(t+1,0,s)}function de(e,r){const t=e[r],a=t[0]==="enter"?"start":"end";return t[1][a]}const ts={name:"tasklistCheck",tokenize:as};function rs(){return{text:{91:ts}}}function as(e,r,t){const a=this;return i;function i(o){return a.previous!==null||!a._gfmTasklistFirstContentOfListItem?t(o):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(o),e.exit("taskListCheckMarker"),s)}function s(o){return V(o)?(e.enter("taskListCheckValueUnchecked"),e.consume(o),e.exit("taskListCheckValueUnchecked"),n):o===88||o===120?(e.enter("taskListCheckValueChecked"),e.consume(o),e.exit("taskListCheckValueChecked"),n):t(o)}function n(o){return o===93?(e.enter("taskListCheckMarker"),e.consume(o),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):t(o)}function c(o){return fe(o)?r(o):te(o)?e.check({tokenize:ns},r,t)(o):t(o)}}function ns(e,r,t){return re(e,a,"whitespace");function a(i){return i===null?t(i):r(i)}}function is(e){return Ci([Ii(),$i(),Qi(e),Xi(),rs()])}const ss={};function os(e){const r=this,t=e||ss,a=r.data(),i=a.micromarkExtensions||(a.micromarkExtensions=[]),s=a.fromMarkdownExtensions||(a.fromMarkdownExtensions=[]),n=a.toMarkdownExtensions||(a.toMarkdownExtensions=[]);i.push(is(t)),s.push(wi()),n.push(ki(t))}function $(...e){return e.filter(Boolean).join(" ")}const cs=({content:e})=>l.jsx(He.MarkdownTextPrimitive,{remarkPlugins:[os],className:"cuadra-aui-md",components:ds,children:e}),nt=y.memo(cs),us=({language:e,code:r})=>{const{isCopied:t,copyToClipboard:a}=ls(),i=()=>{!r||t||a(r)};return l.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-gap-4 cuadra-mt-4 cuadra-rounded-t-lg cuadra-bg-muted/50 cuadra-border-b cuadra-border-border cuadra-px-4 cuadra-py-2 cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-font-brand",children:[l.jsx("span",{className:"cuadra-lowercase [&>span]:cuadra-text-xs cuadra-font-brand",children:e}),l.jsxs("button",{onClick:i,className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-muted cuadra-transition-colors","aria-label":"Copy code",children:[!t&&l.jsx(Ur,{className:"cuadra-h-4 cuadra-w-4"}),t&&l.jsx(Ke,{className:"cuadra-h-4 cuadra-w-4"})]})]})},ls=({copiedDuration:e=3e3}={})=>{const[r,t]=y.useState(!1);return{isCopied:r,copyToClipboard:i=>{i&&navigator.clipboard.writeText(i).then(()=>{t(!0),setTimeout(()=>t(!1),e)})}}},ds=He.unstable_memoizeMarkdownComponents({h1:({className:e,...r})=>l.jsx("h1",{className:$("cuadra-mb-6 cuadra-scroll-m-20 cuadra-text-2xl cuadra-font-normal cuadra-tracking-tight last:cuadra-mb-0 font-brand",e),...r}),h2:({className:e,...r})=>l.jsx("h2",{className:$("cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e),...r}),h3:({className:e,...r})=>l.jsx("h3",{className:$("cuadra-mb-3 cuadra-mt-5 cuadra-scroll-m-20 cuadra-text-lg cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e),...r}),h4:({className:e,...r})=>l.jsx("h4",{className:$("cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e),...r}),h5:({className:e,...r})=>l.jsx("h5",{className:$("cuadra-my-4 cuadra-text-lg cuadra-font-normal first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e),...r}),h6:({className:e,...r})=>l.jsx("h6",{className:$("cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand",e),...r}),p:({className:e,...r})=>l.jsx("p",{className:$("cuadra-mb-5 cuadra-mt-5 cuadra-leading-7 first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e),...r}),a:({className:e,...r})=>l.jsx("a",{className:$("cuadra-text-primary cuadra-font-medium cuadra-underline cuadra-underline-offset-4 font-brand",e),...r}),blockquote:({className:e,...r})=>l.jsx("blockquote",{className:$("cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand",e),...r}),ul:({className:e,...r})=>l.jsx("ul",{className:$("cuadra-my-5 cuadra-ml-6 cuadra-list-disc [&>li]:cuadra-mt-2 font-brand",e),...r}),ol:({className:e,...r})=>l.jsx("ol",{className:$("cuadra-my-5 cuadra-ml-6 cuadra-list-decimal [&>li]:cuadra-mt-2 font-brand",e),...r}),hr:({className:e,...r})=>l.jsx("hr",{className:$("cuadra-my-5 cuadra-border-b",e),...r}),table:({className:e,...r})=>l.jsx("table",{className:$("cuadra-my-5 cuadra-w-full cuadra-border-separate cuadra-border-spacing-0 cuadra-overflow-y-auto font-brand",e),...r}),th:({className:e,...r})=>l.jsx("th",{className:$("cuadra-bg-muted cuadra-px-4 cuadra-py-2 cuadra-text-left cuadra-font-normal first:cuadra-rounded-tl-lg last:cuadra-rounded-tr-lg [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand",e),...r}),td:({className:e,...r})=>l.jsx("td",{className:$("cuadra-border-b cuadra-border-l cuadra-px-4 cuadra-py-2 cuadra-text-left last:cuadra-border-r [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand",e),...r}),tr:({className:e,...r})=>l.jsx("tr",{className:$("cuadra-m-0 cuadra-border-b cuadra-p-0 first:cuadra-border-t [&:last-child>td:first-child]:cuadra-rounded-bl-lg [&:last-child>td:last-child]:cuadra-rounded-br-lg",e),...r}),sup:({className:e,...r})=>l.jsx("sup",{className:$("[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand",e),...r}),pre:({className:e,...r})=>l.jsx("pre",{className:$("cuadra-overflow-x-auto cuadra-whitespace-pre-wrap cuadra-break-words cuadra-rounded-b-lg !cuadra-rounded-t-none cuadra-bg-muted cuadra-p-4 cuadra-text-foreground font-brand",e),...r}),code:function({className:r,...t}){const a=He.useIsMarkdownCodeBlock();return l.jsx("code",{className:$(!a&&"cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand",r),...t})},CodeHeader:us});function it({className:e="",variant:r="default",...t}){const a="cuadra-inline-flex cuadra-items-center cuadra-rounded-md cuadra-px-3 cuadra-py-1.5 cuadra-text-xs cuadra-font-medium font-brand",i={default:"cuadra-border cuadra-border-border cuadra-bg-muted cuadra-text-muted-foreground",subtle:"cuadra-border cuadra-border-border/50 cuadra-bg-muted/50 cuadra-text-muted-foreground",outline:"cuadra-border cuadra-border-border cuadra-bg-background cuadra-text-foreground",ghost:"cuadra-text-muted-foreground"};return l.jsx("div",{className:`${a} ${i[r]||i.default} ${e}`,...t})}function hs(e){const r=new Map;for(const t of e){const a=r.get(t.filename);(!a||t.score>a.score)&&r.set(t.filename,t)}return Array.from(r.values()).sort((t,a)=>a.score-t.score)}function pr({sources:e,maxVisible:r=3}){if(!e||e.length===0)return null;const t=hs(e),a=t.slice(0,r),i=t.length-r;return l.jsxs("div",{className:"cuadra-mt-4 cuadra-pt-3 cuadra-border-t cuadra-border-border",children:[l.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1.5 cuadra-mb-2.5",children:[l.jsx(Nt,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground"}),l.jsx("span",{className:"cuadra-text-xs cuadra-font-medium cuadra-text-muted-foreground font-brand",children:"Sources"})]}),l.jsxs("div",{className:"cuadra-flex cuadra-flex-wrap cuadra-gap-2",children:[a.map((s,n)=>l.jsx(ms,{source:s},s.sourceId||n)),i>0&&l.jsxs(it,{variant:"subtle",children:["+",i," more"]})]})]})}function fs(e){switch(e.split(".").pop()?.toLowerCase()){case"csv":case"xlsx":case"xls":return qr;case"md":case"txt":return Hr;default:return Nt}}function ms({source:e}){const{filename:r,score:t}=e,a=fs(r);return l.jsxs(it,{className:"cuadra-gap-2 cuadra-cursor-default",title:t<1?`${Math.round(t*100)}% relevant`:void 0,children:[l.jsx(a,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-shrink-0 cuadra-opacity-60"}),l.jsx("span",{className:"cuadra-truncate cuadra-max-w-[180px]",children:r}),t<1&&t>0&&l.jsxs("span",{className:"cuadra-opacity-50 cuadra-text-[10px] cuadra-tabular-nums",children:[Math.round(t*100),"%"]})]})}const ps=y.forwardRef(function({welcomeTitle:r="What shall we explore today?",welcomeSubtitle:t,extraTopPadding:a,suggestions:i,inputPlaceholder:s="Reply...",enableAttachments:n=!1,preMadeResponseDelay:c=1e3,streamingSpeed:o=50,safeArea:u=!1,composerBorder:m=!1,models:d,selectedModelId:f,onModelChange:x,showChatHeader:h=!1},w){const b=j.useThreadRuntime(),g=j.useAssistantApi(),[C,v]=y.useState(!1),[_,N]=y.useState(null),[I,q]=y.useState(!1),M=y.useSyncExternalStore(he.subscribe,he.getSnapshot);y.useEffect(()=>{if(M){const A=setTimeout(()=>he.clear(),4e3);return()=>clearTimeout(A)}},[M]);const U=j.useThread(A=>{const R=A.messages;return!R||R.length===0}),p=U&&!C,L=y.useCallback((A,R,k)=>{if(!I)try{const T=k?.streamingSpeed??o,P=k?.delay??c;$t(A,R,T,P),g.composer().setText(A),setTimeout(()=>{g.composer().send()},10)}catch{}},[I,o,c,g]),W=y.useCallback(A=>{try{g.composer().setText(A),setTimeout(()=>{g.composer().send()},10)}catch{}},[g]),H=y.useCallback(async A=>{if(!(I||!b))try{if(A.response){const R=A.responseDelay??c;await L(A.prompt,A.response,{delay:R,streamingSpeed:o})}else W(A.prompt)}catch{}},[b,I,c,o,L,W]),K=y.useCallback(async()=>{try{const R=window.__cuadraThreadListRuntime?.threadList;R?.switchToNewThread&&await R.switchToNewThread()}catch{}},[]);return y.useImperativeHandle(w,()=>({sendMessage:W,sendPreMadeQA:L,clearChat:K}),[W,L,K]),y.useEffect(()=>{if(!b){v(!1);return}try{const A=b?.store;if(!A){v(!1);return}const R=A.subscribe?.(T=>{const P=T?.threadId,F=T?.messages||[],D=T?.isLoadingHistory||!1,S=F.length;P&&P!==_&&N(P),v(D&&S===0)}),k=A.getState?.();if(k){const T=k?.threadId,P=k?.messages||[],F=k?.isLoadingHistory||!1,D=P.length;T&&T!==_&&N(T),v(F&&D===0)}return()=>{R&&R()}}catch{v(!1)}},[b,_]),l.jsxs(j.ThreadPrimitive.Root,{className:"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full cuadra-relative",children:[h&&l.jsx(Cs,{}),l.jsxs(j.ComposerPrimitive.AttachmentDropzone,{disabled:!n,className:`cuadra-flex-1 cuadra-flex cuadra-flex-col cuadra-min-h-0 cuadra-relative ${p?"cuadra-justify-center":""}`,children:[l.jsx("div",{className:"cuadra-dropzone-overlay cuadra-pointer-events-none cuadra-absolute cuadra-inset-0 cuadra-z-50 cuadra-flex cuadra-items-center cuadra-justify-center cuadra-rounded-lg cuadra-transition-opacity cuadra-duration-200",style:{opacity:0},children:l.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-3",children:[l.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-14 cuadra-rounded-2xl",style:{backgroundColor:"var(--cuadra-primary)",color:"white"},children:l.jsx(ta,{className:"cuadra-h-6 cuadra-w-6"})}),l.jsx("p",{className:"cuadra-text-sm cuadra-font-medium cuadra-text-foreground font-brand",children:"Drop files here"})]})}),l.jsx(j.ThreadPrimitive.Viewport,{className:`cuadra-w-full cuadra-bg-inherit cuadra-relative scrollbar-thin ${p?"cuadra-flex-none":"cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto"}`,style:{paddingTop:p?"0":a||(h?"0.5rem":"2rem")},children:C?l.jsx("div",{className:"cuadra-absolute cuadra-inset-0 cuadra-flex cuadra-items-center cuadra-justify-center",children:l.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-3",children:[l.jsx(Pt,{className:"cuadra-h-5 cuadra-w-5 cuadra-animate-spin cuadra-text-muted-foreground"}),l.jsx("p",{className:"cuadra-text-sm cuadra-text-muted-foreground font-brand",children:"Loading messages..."})]})}):l.jsxs("div",{className:"cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full cuadra-px-4",children:[l.jsx(j.ThreadPrimitive.Empty,{children:l.jsx(gs,{title:r,subtitle:t})}),l.jsx(j.ThreadPrimitive.Messages,{components:{UserMessage:xs,AssistantMessage:ws}})]})}),l.jsx("div",{className:`cuadra-w-full cuadra-px-4 cuadra-pt-2 ${p?"cuadra-pb-2":"cuadra-pb-4"}`,style:u?{paddingBottom:"calc(env(safe-area-inset-bottom) + 1rem)"}:void 0,children:l.jsxs("div",{className:"cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full",children:[M&&l.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-mb-2 cuadra-px-3 cuadra-py-2 cuadra-rounded-lg cuadra-text-xs font-brand cuadra-animate-in cuadra-fade-in cuadra-slide-in-from-bottom-2",style:{backgroundColor:"var(--cuadra-muted)",color:"var(--cuadra-foreground)",opacity:.85},children:[l.jsx(Dr,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-flex-shrink-0 cuadra-text-muted-foreground"}),l.jsx("span",{className:"cuadra-flex-1 cuadra-text-muted-foreground",children:M.message}),l.jsx("button",{type:"button",onClick:()=>he.clear(),className:"cuadra-flex-shrink-0 cuadra-p-0.5 cuadra-rounded hover:cuadra-bg-black/5 cuadra-transition-colors","aria-label":"Dismiss",children:l.jsx(Se,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})]}),n&&l.jsx(j.ComposerPrimitive.Attachments,{components:{Attachment:()=>{const A=j.useAssistantState(({attachment:R})=>R);return A?l.jsxs("div",{className:"cuadra-relative cuadra-inline-flex cuadra-items-center cuadra-gap-2 cuadra-mb-2 cuadra-px-3 cuadra-py-1.5 cuadra-rounded-lg cuadra-transition-colors",style:{backgroundColor:"var(--cuadra-muted)",border:"1px solid rgba(0,0,0,0.06)"},children:[l.jsx(_t,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground",strokeWidth:1.5}),l.jsx("span",{className:"cuadra-text-xs cuadra-text-foreground font-brand",children:A.name||"Attachment"}),l.jsx(j.AttachmentPrimitive.Remove,{asChild:!0,children:l.jsx("button",{type:"button",className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-4 cuadra-rounded-full hover:cuadra-bg-background/60 cuadra-transition-colors cuadra-ml-1","aria-label":"Remove attachment",children:l.jsx(Se,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})})]}):null}}}),l.jsxs(j.ComposerPrimitive.Root,{className:"cuadra-relative cuadra-w-full cuadra-rounded-2xl cuadra-transition-shadow cuadra-duration-300 cuadra-flex cuadra-flex-col",style:{backgroundColor:"var(--cuadra-composer)",boxShadow:"var(--cuadra-composer-shadow)",border:m?"1px solid hsl(var(--cuadra-border))":"none"},children:[l.jsx(j.ComposerPrimitive.Input,{asChild:!0,children:l.jsx("textarea",{rows:1,placeholder:s,className:"cuadra-flex cuadra-min-h-[44px] cuadra-w-full cuadra-rounded-t-2xl cuadra-border-0 cuadra-bg-transparent cuadra-px-4 cuadra-pt-3.5 cuadra-pb-1 cuadra-text-base cuadra-text-foreground placeholder:cuadra-text-muted-foreground focus-visible:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-resize-none font-brand",style:{fontSize:"1rem",lineHeight:"1.5"}})}),l.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-px-3 cuadra-pb-2.5 cuadra-pt-1",children:[l.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1",children:n&&l.jsx(j.ComposerPrimitive.AddAttachment,{multiple:!0,asChild:!0,children:l.jsxs("button",{type:"button",className:"cuadra-group cuadra-relative cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-8 cuadra-rounded-lg hover:cuadra-bg-muted/60 cuadra-transition-colors","aria-label":"Attach files",children:[l.jsx(Qe,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground",strokeWidth:1.5}),l.jsx("span",{className:"cuadra-pointer-events-none cuadra-absolute cuadra-bottom-full cuadra-left-1/2 cuadra--translate-x-1/2 cuadra-mb-1.5 cuadra-whitespace-nowrap cuadra-rounded-md cuadra-px-2.5 cuadra-py-1 cuadra-text-xs cuadra-text-foreground cuadra-opacity-0 group-hover:cuadra-opacity-100 cuadra-transition-opacity cuadra-duration-150 cuadra-delay-300 font-brand",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"},children:"Attach files"})]})})}),l.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[d&&d.length>0&&l.jsx(ks,{models:d,selectedModelId:f,onModelChange:x,threadIsEmpty:U,onNewChat:K}),l.jsx(j.ComposerPrimitive.Send,{asChild:!0,children:l.jsx("button",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-8 cuadra-rounded-full cuadra-transition-all cuadra-duration-200 hover:cuadra-opacity-90 disabled:cuadra-opacity-30 disabled:cuadra-cursor-not-allowed",style:{backgroundColor:"var(--cuadra-primary)",color:"white"},"aria-label":"Send message",type:"button",children:l.jsx(Pr,{className:"cuadra-h-4 cuadra-w-4",strokeWidth:2})})})]})]})]})]})}),p&&i&&i.length>0&&l.jsx("div",{className:"cuadra-flex cuadra-flex-wrap cuadra-justify-center cuadra-gap-2 cuadra-px-4 cuadra-pb-6 cuadra-pt-1 cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full",children:i.map((A,R)=>l.jsx("button",{type:"button",onClick:()=>H(A),disabled:I,className:"cuadra-px-3.5 cuadra-py-2 cuadra-rounded-full cuadra-text-sm cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-all cuadra-duration-200 font-brand cuadra-cursor-pointer disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed",style:{backgroundColor:"var(--cuadra-composer)",boxShadow:"0 0 0 1px rgba(0,0,0,0.06)"},children:A.prompt},`suggestion-${R}`))})]})]})});function gs({title:e,subtitle:r}){return l.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-text-center cuadra-py-6",children:[l.jsx("h2",{className:"cuadra-text-4xl cuadra-font-normal cuadra-text-foreground/80 cuadra-tracking-tight",style:{fontFamily:"var(--cuadra-font-logo), Outfit, -apple-system, sans-serif"},children:e}),r&&l.jsx("p",{className:"cuadra-text-base cuadra-text-muted-foreground cuadra-mt-3 cuadra-max-w-lg cuadra-whitespace-pre-line",children:r})]})}function xs(){return l.jsx(j.MessagePrimitive.Root,{className:"cuadra-flex cuadra-w-full cuadra-justify-end cuadra-py-2.5",children:l.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-end cuadra-gap-2 cuadra-max-w-[80%]",children:[l.jsx(j.MessagePrimitive.Attachments,{components:{Attachment:()=>{const e=j.useAssistantState(({attachment:s})=>s);if(!e)return null;const r=e.type==="image",t=e.file,a=e.content?.find(s=>s.type==="image"),i=t?URL.createObjectURL(t):a?.image;return l.jsx("div",{className:"cuadra-mb-1",children:r&&i?l.jsx("img",{src:i,alt:e.name||"Attachment",className:"cuadra-rounded-2xl cuadra-max-h-64 cuadra-max-w-full cuadra-object-contain",style:{border:"1px solid rgba(0,0,0,0.06)"}}):l.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-rounded-xl cuadra-px-3 cuadra-py-2",style:{backgroundColor:"var(--cuadra-muted)",border:"1px solid rgba(0,0,0,0.06)"},children:[l.jsx(_t,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground"}),l.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground font-brand",children:e.name||"Attachment"})]})})}}}),l.jsx("div",{className:"cuadra-break-words cuadra-text-foreground font-brand",style:{borderRadius:"1.25rem",backgroundColor:"var(--cuadra-muted)",paddingLeft:"1rem",paddingRight:"1rem",paddingTop:"0.625rem",paddingBottom:"0.625rem",wordBreak:"break-word",fontSize:"0.9375rem",lineHeight:"1.625"},children:l.jsx(j.MessagePrimitive.Parts,{components:{Text:({text:e})=>l.jsx(nt,{content:e||""})}})})]})})}function ys({text:e}){const[r,t]=y.useState(!1),a=j.useAssistantState(({message:i})=>i?.status?.type==="running");return e?a?l.jsx("div",{className:"cuadra-mb-3 cuadra-py-1",children:l.jsx("div",{className:"cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand cuadra-animate-text-shimmer",children:e})}):l.jsxs("div",{className:"cuadra-mb-3",children:[l.jsxs("button",{type:"button",onClick:()=>t(!r),className:"cuadra-flex cuadra-items-center cuadra-gap-1.5 cuadra-py-1 cuadra-text-sm cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-colors font-brand",children:[l.jsx(Xe,{className:`cuadra-h-3.5 cuadra-w-3.5 cuadra-shrink-0 cuadra-transition-transform cuadra-duration-200 ${r?"":"cuadra--rotate-90"}`}),l.jsx("span",{children:"Reasoning"})]}),l.jsx("div",{className:`cuadra-overflow-hidden cuadra-transition-all cuadra-duration-200 cuadra-ease-out ${r?"cuadra-max-h-[2000px] cuadra-opacity-100":"cuadra-max-h-0 cuadra-opacity-0"}`,children:l.jsx("div",{className:"cuadra-pl-5 cuadra-pt-2 cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand",children:l.jsx(nt,{content:e})})})]}):null}function bs(){return l.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2.5 cuadra-text-muted-foreground cuadra-text-sm font-brand cuadra-py-3",children:[l.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1",children:[l.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"0ms",backgroundColor:"var(--cuadra-primary)",opacity:.7}}),l.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"150ms",backgroundColor:"var(--cuadra-primary)",opacity:.5}}),l.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"300ms",backgroundColor:"var(--cuadra-primary)",opacity:.3}})]}),l.jsx("span",{children:"Thinking..."})]})}function ws(){const e=j.useAssistantState(({message:n})=>n?.status?.type==="running"),r=j.useAssistantState(({message:n})=>{const c=n?.content;return!c||!Array.isArray(c)?!1:c.some(o=>!!(o.type==="text"&&o.text&&o.text.length>0||o.type==="reasoning"&&o.text&&o.text.length>0))}),t=y.useRef(!1),[a,i]=y.useState(null);y.useEffect(()=>{if(e&&r&&!t.current){const n=ee.getCurrentMessageId();n&&(t.current=!0,i(n))}},[e,r]);const s=y.useSyncExternalStore(n=>ee.subscribe(n),()=>{if(a){const n=ee.getForMessage(a);return n.sources?.length?n.sources:null}if(e&&r){const n=ee.getCurrentMessageId();if(n){const c=ee.getForMessage(n);return c.sources?.length?c.sources:null}}return null},()=>null);return l.jsx(j.MessagePrimitive.Root,{className:"cuadra-flex cuadra-w-full cuadra-justify-start cuadra-py-2.5",children:l.jsxs("div",{className:"cuadra-text-foreground cuadra-max-w-full cuadra-break-words font-brand",style:{fontSize:"0.9375rem",lineHeight:"1.75"},children:[l.jsx(j.MessagePrimitive.Parts,{components:{Text:({text:n})=>l.jsx(nt,{content:n||""}),Reasoning:({text:n})=>l.jsx(ys,{text:n||""})}}),e&&!r&&l.jsx(bs,{}),s&&s.length>0&&l.jsx(pr,{sources:s})]})})}function ce({label:e,children:r}){return l.jsxs("span",{className:"cuadra-relative cuadra-inline-flex cuadra-group/tip",children:[r,l.jsx("span",{className:"cuadra-absolute cuadra-bottom-full cuadra-left-1/2 cuadra-mb-1.5 cuadra-hidden group-hover/tip:cuadra-flex cuadra-items-center cuadra-whitespace-nowrap cuadra-rounded-md cuadra-px-2 cuadra-py-1 cuadra-text-[10px] cuadra-pointer-events-none cuadra-z-50 font-brand",style:{backgroundColor:"var(--cuadra-popover)",color:"var(--cuadra-foreground)",boxShadow:"0 2px 8px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)",transform:"translateX(-50%)"},children:e})]})}function ks({models:e,selectedModelId:r,onModelChange:t,threadIsEmpty:a,onNewChat:i}){const[s,n]=y.useState(!1),c=e.find(u=>u.id===r)||e[0];if(!c)return null;const o=async u=>{n(!1),!a&&u!==r&&await i?.(),t?.(u)};return l.jsxs("div",{className:"cuadra-relative",children:[l.jsxs("button",{type:"button",onClick:()=>n(!s),className:"cuadra-flex cuadra-items-center cuadra-gap-1 cuadra-px-2.5 cuadra-py-1.5 cuadra-rounded-lg cuadra-text-xs cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-colors font-brand",children:[l.jsx("span",{children:c.name}),c.supportsReasoning&&l.jsx(ce,{label:"Reasoning",children:l.jsx(Fe,{className:"cuadra-h-3 cuadra-w-3"})}),c.supportsVision&&l.jsx(ce,{label:"Vision",children:l.jsx(Ue,{className:"cuadra-h-3 cuadra-w-3"})}),l.jsx(Xe,{className:"cuadra-h-3 cuadra-w-3"})]}),s&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"cuadra-hidden md:cuadra-block cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:()=>n(!1)}),l.jsxs("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-50 cuadra-flex cuadra-flex-col md:cuadra-hidden",style:{backgroundColor:"var(--cuadra-popover)"},children:[l.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-px-4 cuadra-py-3 cuadra-min-h-[48px]",style:{borderBottom:"1px solid rgba(0,0,0,0.06)"},children:[l.jsx("span",{className:"cuadra-text-sm cuadra-font-semibold cuadra-text-foreground font-brand",children:"Select Model"}),l.jsx("button",{type:"button",onClick:()=>n(!1),className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-p-1.5 cuadra-rounded-lg cuadra-text-muted-foreground hover:cuadra-bg-muted/60 cuadra-transition-colors",children:l.jsx(Se,{className:"cuadra-h-5 cuadra-w-5"})})]}),l.jsx("div",{className:"cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto cuadra-py-1",children:e.map(u=>l.jsxs("button",{type:"button",className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-justify-between cuadra-gap-3 cuadra-px-4 cuadra-py-3 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted/60 cuadra-transition-colors cuadra-border-b cuadra-border-border/40 last:cuadra-border-b-0 font-brand",onClick:()=>o(u.id),children:[l.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-min-w-0",children:[l.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1.5",children:[l.jsx("span",{className:"cuadra-text-foreground cuadra-truncate",children:u.name}),u.supportsReasoning&&l.jsx(ce,{label:"Reasoning",children:l.jsx(Fe,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})}),u.supportsVision&&l.jsx(ce,{label:"Vision",children:l.jsx(Ue,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})})]}),u.description&&l.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground",children:u.description})]}),u.id===r&&l.jsx(Ke,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-primary cuadra-flex-shrink-0"})]},u.id))})]}),l.jsx("div",{className:"cuadra-hidden md:cuadra-block cuadra-absolute cuadra-bottom-full cuadra-right-0 cuadra-mb-2 cuadra-z-50 cuadra-rounded-xl cuadra-min-w-[200px] cuadra-py-1",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 4px 24px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)"},children:e.map(u=>l.jsxs("button",{type:"button",className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-justify-between cuadra-gap-3 cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted/60 cuadra-transition-colors font-brand",onClick:()=>o(u.id),children:[l.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-min-w-0",children:[l.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1.5",children:[l.jsx("span",{className:"cuadra-text-foreground cuadra-truncate",children:u.name}),u.supportsReasoning&&l.jsx(ce,{label:"Reasoning",children:l.jsx(Fe,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})}),u.supportsVision&&l.jsx(ce,{label:"Vision",children:l.jsx(Ue,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})})]}),u.description&&l.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground",children:u.description})]}),u.id===r&&l.jsx(Ke,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-primary cuadra-flex-shrink-0"})]},u.id))})]})]})}function Cs(){const e=j.useAssistantState(({threadListItem:i})=>i?.title??null),[r,t]=y.useState(!1),a=e||"Untitled chat";return l.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-px-3 cuadra-py-2 cuadra-min-h-[48px] cuadra-justify-end md:cuadra-justify-start",children:l.jsxs("div",{className:"cuadra-relative",children:[l.jsxs("button",{type:"button",onClick:()=>t(!r),className:"cuadra-hidden md:cuadra-flex cuadra-items-center cuadra-gap-1 cuadra-text-sm cuadra-text-foreground hover:cuadra-bg-muted/60 cuadra-rounded-lg cuadra-px-2 cuadra-py-1.5 cuadra-transition-colors font-brand",children:[l.jsx("span",{className:"cuadra-font-medium cuadra-truncate cuadra-max-w-[200px]",children:a}),l.jsx(Xe,{className:`cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground cuadra-flex-shrink-0 cuadra-transition-transform cuadra-duration-200 ${r?"cuadra-rotate-180":""}`})]}),l.jsx("button",{type:"button",onClick:()=>t(!r),className:"cuadra-flex md:cuadra-hidden cuadra-items-center cuadra-justify-center cuadra-text-foreground hover:cuadra-bg-muted/60 cuadra-rounded-lg cuadra-p-2 cuadra-transition-colors",children:l.jsx(Gr,{className:"cuadra-h-5 cuadra-w-5"})}),r&&l.jsx(vs,{onClose:()=>t(!1)})]})})}function vs({onClose:e}){return l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"cuadra-hidden md:cuadra-block cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:e}),l.jsxs("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-50 cuadra-flex cuadra-flex-col md:cuadra-hidden",style:{backgroundColor:"var(--cuadra-popover)"},children:[l.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-px-4 cuadra-py-3 cuadra-min-h-[48px]",style:{borderBottom:"1px solid rgba(0,0,0,0.06)"},children:[l.jsx("span",{className:"cuadra-text-sm cuadra-font-semibold cuadra-text-foreground font-brand",children:"Chats"}),l.jsx("button",{type:"button",onClick:e,className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-p-1.5 cuadra-rounded-lg cuadra-text-muted-foreground hover:cuadra-bg-muted/60 cuadra-transition-colors",children:l.jsx(Se,{className:"cuadra-h-5 cuadra-w-5"})})]}),l.jsxs(j.ThreadListPrimitive.Root,{className:"cuadra-flex cuadra-flex-col cuadra-flex-1 cuadra-min-h-0",children:[l.jsx("div",{className:"cuadra-px-3 cuadra-py-2",children:l.jsxs(j.ThreadListPrimitive.New,{className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-gap-2.5 cuadra-px-3 cuadra-py-2.5 cuadra-rounded-lg cuadra-text-sm cuadra-text-foreground hover:cuadra-bg-muted cuadra-transition-colors cuadra-cursor-pointer font-brand",onClick:e,children:[l.jsx(Qe,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"New Chat"]})}),l.jsx(It,{onSelect:e,fullHeight:!0})]})]}),l.jsx("div",{className:"cuadra-hidden md:cuadra-flex cuadra-absolute cuadra-left-0 cuadra-top-full cuadra-mt-1 cuadra-z-50 cuadra-w-[300px] cuadra-rounded-xl cuadra-overflow-hidden cuadra-flex-col",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 4px 24px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)"},children:l.jsxs(j.ThreadListPrimitive.Root,{className:"cuadra-flex cuadra-flex-col",children:[l.jsx("div",{className:"cuadra-px-2 cuadra-py-1.5",children:l.jsxs(j.ThreadListPrimitive.New,{className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-gap-2.5 cuadra-px-3 cuadra-py-2 cuadra-rounded-lg cuadra-text-sm cuadra-text-foreground hover:cuadra-bg-muted cuadra-transition-colors cuadra-cursor-pointer font-brand",onClick:e,children:[l.jsx(Qe,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"New Chat"]})}),l.jsx(It,{onSelect:e})]})})]})}function It({onSelect:e,fullHeight:r}){const t=j.useAssistantState(({threads:s})=>s?.threadIds??[]),a=j.useAssistantState(({threads:s})=>s?.newThreadId);return t.some(s=>s!==a)?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"cuadra-mx-3 cuadra-my-0.5",style:{borderTop:"1px solid rgba(0,0,0,0.06)"}}),l.jsx("div",{className:`cuadra-overflow-y-auto scrollbar-thin ${r?"cuadra-flex-1 cuadra-min-h-0 cuadra-px-3 cuadra-pb-3 cuadra-flex cuadra-flex-col cuadra-gap-2":"cuadra-px-2 cuadra-pb-1.5"}`,style:r?void 0:{maxHeight:"340px"},children:l.jsx(j.ThreadListPrimitive.Items,{components:{ThreadListItem:s=>l.jsx(js,{...s,onSelect:e,fullHeight:r})}})})]}):null}function js({onSelect:e,fullHeight:r}){const t=j.useThreadListItem(),a=j.useThreadListItemRuntime(),i=j.useAssistantRuntime(),s=j.useThread(g=>g.threadId),n=t?.id===s,[c,o]=y.useState(!1),[u,m]=y.useState(!1),[d,f]=y.useState(t?.title||""),[x,h]=y.useState(!1),w=async()=>{if(!t?.remoteId||!d||d===t.title){m(!1);return}try{h(!0),await a.rename(d)}catch{}finally{h(!1),m(!1)}},b=async g=>{g.stopPropagation();try{await a.delete(),n&&await i.switchToNewThread()}catch(C){console.error("[CuadraChat] Failed to delete thread:",C)}};return y.useEffect(()=>{t?.title&&!u&&f(t.title)},[t?.title,u]),t?r?l.jsxs(j.ThreadListItemPrimitive.Root,{className:`cuadra-relative cuadra-flex cuadra-items-center cuadra-rounded-xl cuadra-transition-colors cuadra-cursor-pointer ${n?"cuadra-bg-primary/10 cuadra-ring-1 cuadra-ring-primary/20":"cuadra-bg-muted/40"}`,children:[u?l.jsx("div",{className:"cuadra-flex-1 cuadra-px-4 cuadra-py-3.5 cuadra-min-w-0",onClick:g=>g.stopPropagation(),onMouseDown:g=>g.stopPropagation(),onKeyDown:g=>g.stopPropagation(),onKeyUp:g=>g.stopPropagation(),onKeyPress:g=>g.stopPropagation(),children:l.jsx("input",{className:"cuadra-w-full cuadra-bg-transparent cuadra-border-0 cuadra-border-b cuadra-text-sm cuadra-text-foreground cuadra-py-0.5 cuadra-px-0 cuadra-outline-none font-brand",style:{borderBottomColor:"var(--cuadra-primary)",borderBottomWidth:"1.5px"},value:d,onChange:g=>f(g.target.value),onKeyDown:g=>{g.stopPropagation(),g.key==="Enter"&&w(),g.key==="Escape"&&(m(!1),f(t.title||""))},onBlur:()=>void w(),disabled:x,autoFocus:!0})}):l.jsx(j.ThreadListItemPrimitive.Trigger,{className:"cuadra-flex-1 cuadra-px-4 cuadra-py-3.5 cuadra-min-w-0 cuadra-cursor-pointer",onClick:()=>e?.(),children:l.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground cuadra-truncate cuadra-block cuadra-text-left font-brand",children:t.title||"Chat"})}),!u&&l.jsx(Ts,{onRename:()=>{m(!0),f(t.title||"Chat")},onDelete:b})]}):l.jsxs(j.ThreadListItemPrimitive.Root,{className:`cuadra-relative cuadra-flex cuadra-items-center cuadra-rounded-lg cuadra-transition-colors cuadra-cursor-pointer cuadra-border-b cuadra-border-border/40 last:cuadra-border-b-0 ${n?"cuadra-bg-muted":"hover:cuadra-bg-muted/60"}`,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),children:[u?l.jsx("div",{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0",onClick:g=>g.stopPropagation(),onMouseDown:g=>g.stopPropagation(),onKeyDown:g=>g.stopPropagation(),onKeyUp:g=>g.stopPropagation(),onKeyPress:g=>g.stopPropagation(),children:l.jsx("input",{className:"cuadra-w-full cuadra-bg-transparent cuadra-border-0 cuadra-border-b cuadra-text-sm cuadra-text-foreground cuadra-py-0.5 cuadra-px-0 cuadra-outline-none font-brand",style:{borderBottomColor:"var(--cuadra-primary)",borderBottomWidth:"1.5px"},value:d,onChange:g=>f(g.target.value),onKeyDown:g=>{g.stopPropagation(),g.key==="Enter"&&w(),g.key==="Escape"&&(m(!1),f(t.title||""))},onBlur:()=>void w(),disabled:x,autoFocus:!0})}):l.jsx(j.ThreadListItemPrimitive.Trigger,{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0 cuadra-cursor-pointer",onClick:()=>e?.(),children:l.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground cuadra-truncate cuadra-block cuadra-text-left font-brand",children:t.title||"Chat"})}),(c||n)&&!u&&l.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-0.5 cuadra-mr-1.5 cuadra-flex-shrink-0",children:[l.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-background/60 cuadra-transition-colors",onClick:g=>{g.stopPropagation(),m(!0),f(t.title||"Chat")},title:"Rename",children:l.jsx(Et,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})}),l.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-destructive/10 cuadra-transition-colors",onClick:b,title:"Delete",children:l.jsx(Rt,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-destructive"})})]})]}):null}function Ts({onRename:e,onDelete:r}){const[t,a]=y.useState(!1);return l.jsxs("div",{className:"cuadra-relative cuadra-flex-shrink-0 cuadra-mr-2",children:[l.jsx("button",{type:"button",className:"cuadra-p-2 cuadra-rounded-lg cuadra-text-muted-foreground hover:cuadra-bg-background/60 cuadra-transition-colors",onClick:i=>{i.stopPropagation(),a(!t)},children:l.jsx($r,{className:"cuadra-h-4 cuadra-w-4"})}),t&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-50",onClick:i=>{i.stopPropagation(),a(!1)}}),l.jsxs("div",{className:"cuadra-absolute cuadra-right-0 cuadra-top-full cuadra-mt-1 cuadra-z-[60] cuadra-w-36 cuadra-rounded-xl cuadra-py-1 cuadra-overflow-hidden",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 4px 24px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)"},children:[l.jsxs("button",{type:"button",className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-gap-2.5 cuadra-px-3 cuadra-py-2.5 cuadra-text-sm cuadra-text-foreground hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:i=>{i.stopPropagation(),a(!1),e()},children:[l.jsx(Et,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"Rename"]}),l.jsxs("button",{type:"button",className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-gap-2.5 cuadra-px-3 cuadra-py-2.5 cuadra-text-sm cuadra-text-destructive hover:cuadra-bg-destructive/10 cuadra-transition-colors font-brand",onClick:i=>{i.stopPropagation(),a(!1),r(i)},children:[l.jsx(Rt,{className:"cuadra-h-4 cuadra-w-4"}),"Delete"]})]})]})]})}const Ve=({children:e,className:r="",paddingX:t="px-0",paddingY:a="py-0",borderSizePx:i=2,style:s,contentStyle:n})=>l.jsx("div",{className:`cuadra-relative cuadra-bg-background md:cuadra-rounded-lg cuadra-overflow-hidden cuadra-flex cuadra-flex-col ${t} ${a} ${r}`,style:{border:i>0?`${i}px solid var(--cuadra-primary)`:"none",...s,...n},children:e}),Ss=y.createContext(void 0),We=({children:e,value:r})=>l.jsx(Ss.Provider,{value:r,children:e});function Is(){y.useEffect(()=>{if(document.querySelector("style[data-cuadra-uikit]"))return;const r=document.createElement("div");r.className="cuadra-flex",document.body.appendChild(r);const t=window.getComputedStyle(r).display==="flex";if(document.body.removeChild(r),t)return;const a=document.createElement("link");a.setAttribute("data-cuadra-uikit","true"),a.rel="stylesheet",a.type="text/css";const i=["/node_modules/@cuadra-ai/uikit/dist/uikit.css",new URL("../dist/uikit.css",typeof document>"u"?require("url").pathToFileURL(__filename).href:me&&me.tagName.toUpperCase()==="SCRIPT"&&me.src||new URL("index.cjs",document.baseURI).href).href];let s=!1;for(const n of i)if(a.href=n,a.onload=()=>{s=!0},a.onerror=()=>{},document.head.appendChild(a),s)break},[])}const Ms=y.forwardRef(function({config:r},t){Is();const a=y.useRef(null),i=y.useRef(!1),{baseUrl:s,proxyUrl:n,sessionToken:c,mode:o="multiChat",modelMode:u="fixed",modelId:m,onModelChange:d,ephemeral:f=!1,systemPrompt:x,enableReasoning:h=!1,initialThreadId:w,welcomeTitle:b,welcomeSubtitle:g,extraTopPadding:C,suggestions:v,inputPlaceholder:_,preMadeResponseDelay:N=1e3,streamingSpeed:I=50,initialMessage:q,initialPreMadeQA:M,theme:U="system",onError:p,onChatCreated:L,onUserMessage:W,onThreadIdUpdate:H,enableAttachments:K=!1,supportsVision:A,onBeforeRequest:R,mockResponseOnBlocked:k}=r;y.useImperativeHandle(t,()=>({sendMessage:E=>{a.current?.sendMessage(E)},sendPreMadeQA:(E,Z,ie)=>{a.current?.sendPreMadeQA(E,Z,ie)},clearChat:()=>{a.current?.clearChat()}}),[]),y.useEffect(()=>{if(i.current)return;const E=setTimeout(()=>{M?(i.current=!0,a.current?.sendPreMadeQA(M.question,M.answer,{delay:N,streamingSpeed:I})):q&&(i.current=!0,a.current?.sendMessage(q))},500);return()=>clearTimeout(E)},[q,M,N,I]);const T=n||s||"",P=!!n,F=y.useMemo(()=>new Dt(T,c||void 0,P),[T,c,P]),[D,S]=y.useState(null),[B,Y]=y.useState(!1),[J,xe]=y.useState(null),[Re,X]=y.useState(!1);y.useEffect(()=>{o==="multiChat"&&X(!0)},[o]);const ne=y.useCallback(async()=>{if(u==="selector"){Y(!0),xe(null);try{const E=await F.listModels();S(E)}catch(E){xe(E instanceof Error?E:new Error("Failed to load models"))}finally{Y(!1)}}},[F,u]);y.useEffect(()=>{u==="selector"&&ne()},[u,ne]),y.useEffect(()=>(typeof window<"u"&&(window.__cuadraUIKitRefetchModels=ne),()=>{typeof window<"u"&&delete window.__cuadraUIKitRefetchModels}),[ne]);const[Q,ot]=y.useState(u==="fixed"&&m||null),ct=y.useRef(Q),Ce=y.useCallback(E=>{const Z=ct.current;ot(E),ct.current=E,d?.(E),Z!==null&&Z!==E&&o==="multiChat"&&setTimeout(()=>{const ie=window.__cuadraThreadListRuntime;if(ie?.threads?.switchToNewThread)try{ie.threads.switchToNewThread()}catch{}else if(ie?.threads?.createThread)try{ie.threads.createThread()}catch{}else if(ie?.switchToNewThread)try{ie.switchToNewThread()}catch{}},100)},[d,o]);y.useEffect(()=>{if(u==="selector"&&D?.items&&D.items.length>0&&!Q){const E=D.items[0];if(E?.id){const Z=E.id;ot(Z),d?.(Z)}}},[u,D?.items,Q,d]);const wr=u==="fixed"?!!m:!!Q,kr=y.useMemo(()=>A!==void 0?A:u==="selector"&&Q&&D?.items?D.items.find(Z=>Z.id===Q)?.supportsVision??!0:!0,[A,u,Q,D?.items]),Le=y.useMemo(()=>(D?.items||[]).filter(E=>E?.id&&E?.displayName).map(E=>({id:E.id,name:E.displayName,supportsVision:E.supportsVision??!1,supportsReasoning:E.supportsReasoning??!1})),[D]),De=y.useMemo(()=>({currentModelId:Q||"",models:Le,modelsLoading:B,modelsError:J,onModelChange:Ce,refetchModels:ne}),[Q,Le,B,J,Ce,ne]);return u==="selector"&&B||o==="multiChat"&&Re?l.jsx(We,{value:De,children:l.jsx(Ve,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",borderSizePx:r.borderless?0:2,children:l.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:l.jsx(Pt,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"})})})}):u==="selector"&&!wr&&J?l.jsx(We,{value:De,children:l.jsx(Ve,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",children:l.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:l.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2",children:l.jsx("p",{className:"cuadra-text-sm cuadra-text-destructive font-brand",children:"Failed to load models"})})})})}):l.jsx("div",{className:"cuadra-uikit cuadra-h-full cuadra-w-full",style:{height:"100%",width:"100%"},children:l.jsx(We,{value:De,children:l.jsx(Pa,{baseUrl:P?T:s||T,sessionToken:c,isProxyMode:P,mode:o,modelMode:u,modelId:Q||m||void 0,onModelChange:Ce,ephemeral:f,systemPrompt:x,enableReasoning:h,initialThreadId:w,enableAttachments:K,supportsVision:kr,onError:p,onChatCreated:L,onUserMessage:W,onThreadIdUpdate:H,onBeforeRequest:R,mockResponseOnBlocked:k,onChatsLoaded:()=>{o==="multiChat"&&X(!1)},children:l.jsx(Ve,{paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",className:`cuadra-h-full ${r.containerClass||""}`,borderSizePx:r.borderless?0:2,style:{height:"100%"},children:l.jsx("div",{className:"cuadra-h-full cuadra-flex cuadra-relative",style:{height:"100%"},children:l.jsx("div",{className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:l.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0",children:l.jsx(ps,{ref:a,welcomeTitle:b,welcomeSubtitle:g,extraTopPadding:C,suggestions:v,inputPlaceholder:_,enableAttachments:K,preMadeResponseDelay:N,streamingSpeed:I,safeArea:r.safeArea,showChatHeader:o==="multiChat",models:u==="selector"?Le:void 0,selectedModelId:Q||void 0,onModelChange:u==="selector"?Ce:void 0,theme:U})})})})})})})})});function gr(e,r=":root"){if(typeof document>"u")return;const t=document.documentElement,a=[];if(e.light){Ns(e.light,t);const i=Mt(e.light);i&&a.push(`.cuadra-uikit { ${i} }`)}if(e.dark){const i=Mt(e.dark);i&&(a.push(`.dark { ${i} }`),a.push(`.dark .cuadra-uikit { ${i} }`))}if(a.length>0){let i=document.getElementById("cuadra-theme-custom");i||(i=document.createElement("style"),i.id="cuadra-theme-custom",document.head.appendChild(i)),i.textContent=a.join(`
21
+ `)}}const As={background:"background",foreground:"foreground",card:"card",cardForeground:"card-foreground",popover:"popover",popoverForeground:"popover-foreground",primary:"primary",primaryForeground:"primary-foreground",primaryLight:"primary-light",primaryLighter:"primary-lighter",secondary:"secondary",secondaryForeground:"secondary-foreground",muted:"muted",mutedForeground:"muted-foreground",accent:"accent",accentForeground:"accent-foreground",border:"border",input:"input",ring:"ring",destructive:"destructive",destructiveForeground:"destructive-foreground",success:"success",successForeground:"success-foreground",info:"info",infoForeground:"info-foreground",warning:"warning",warningForeground:"warning-foreground"};function xr(e){const r=As[e];return r?`--cuadra-${r}`:`--cuadra-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function Ns(e,r){Object.entries(e).forEach(([t,a])=>{if(a){const i=xr(t);r.style.setProperty(i,a)}})}function Mt(e){return Object.entries(e).map(([r,t])=>t?`${xr(r)}: ${t};`:"").filter(Boolean).join(" ")}function Ps(){if(typeof document>"u")return;const e=document.documentElement;Array.from(e.style).filter(i=>i.startsWith("--cuadra-")).forEach(i=>e.style.removeProperty(i));const t=document.getElementById("cuadra-theme-custom");t&&t.remove();const a=document.getElementById("cuadra-theme-dark");a&&a.remove()}function _s({onReset:e,error:r}){return l.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-h-full cuadra-p-6 cuadra-text-center",children:[l.jsx("div",{className:"cuadra-mb-4",children:l.jsx("svg",{className:"cuadra-w-12 cuadra-h-12 cuadra-text-destructive cuadra-mx-auto",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),l.jsx("h3",{className:"cuadra-text-lg cuadra-font-medium cuadra-text-foreground cuadra-mb-2",children:"Something went wrong"}),l.jsx("p",{className:"cuadra-text-sm cuadra-text-muted-foreground cuadra-mb-4 cuadra-max-w-sm",children:r?.message||"An unexpected error occurred. Please try again."}),l.jsx("button",{onClick:e,className:"cuadra-px-4 cuadra-py-2 cuadra-text-sm cuadra-font-medium cuadra-rounded-md cuadra-transition-colors",style:{backgroundColor:"var(--cuadra-primary)",color:"hsl(var(--cuadra-primary-foreground))"},children:"Try Again"})]})}class st extends y.Component{constructor(t){super(t);z(this,"reset",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,a){this.props.onError?.(t,a)}render(){if(this.state.hasError){const{fallback:t}=this.props,{error:a}=this.state;return typeof t=="function"?t(a,this.reset):t||l.jsx(_s,{error:a,onReset:this.reset})}return this.props.children}}function Es(e,r){const t=a=>l.jsx(st,{...r,children:l.jsx(e,{...a})});return t.displayName=`withErrorBoundary(${e.displayName||e.name||"Component"})`,t}const ge=y.createContext(null);ge.displayName="CuadraChatContext";function Rs(){const e=y.useContext(ge);if(e===null)throw new Error("useCuadraChat must be used within a CuadraChatProvider. Wrap your component tree with <CuadraChatProvider>...</CuadraChatProvider>");return{controls:e.controls,isReady:e.controls!==null}}function Ls(){const e=y.useContext(ge);return e===null?null:{controls:e.controls,isReady:e.controls!==null}}function Ds({children:e}){const[r,t]=y.useState(null),a=y.useCallback(n=>{t(n)},[]),i=y.useCallback(()=>{t(null)},[]),s=y.useMemo(()=>({controls:r,registerControls:a,unregisterControls:i}),[r,a,i]);return l.jsx(ge.Provider,{value:s,children:e})}function yr(e){return"connection"in e&&typeof e.connection=="object"}function br(e){return yr(e)?Fs(e):Us(e)}function Fs(e){return{connection:{baseUrl:e.connection.baseUrl||"",proxyUrl:e.connection.proxyUrl||"",sessionToken:e.connection.sessionToken??null},chat:{mode:e.chat?.mode??"multiChat",modelMode:e.chat?.modelMode??"fixed",modelId:e.chat?.modelId??"",systemPrompt:e.chat?.systemPrompt??"",ephemeral:e.chat?.ephemeral??!1,enableReasoning:e.chat?.enableReasoning??!1,enableAttachments:e.chat?.enableAttachments??!1,supportsVision:e.chat?.supportsVision,initialThreadId:e.chat?.initialThreadId},ui:{theme:e.ui?.theme??"system",customTheme:e.ui?.customTheme,showThemeToggle:e.ui?.showThemeToggle??!0,language:e.ui?.language,welcomeTitle:e.ui?.welcomeTitle??"Hi, how can I help you today?",welcomeSubtitle:e.ui?.welcomeSubtitle??"Start exploring our platform and discover what you can build.",suggestions:e.ui?.suggestions,inputPlaceholder:e.ui?.inputPlaceholder??"Type your message...",extraTopPadding:e.ui?.extraTopPadding,borderless:e.ui?.borderless,safeArea:e.ui?.safeArea,orgName:e.ui?.orgName,primaryColor:e.ui?.primaryColor},preMade:{responseDelay:e.preMade?.responseDelay??1e3,streamingSpeed:e.preMade?.streamingSpeed??50},initial:{message:e.initial?.message,preMadeQA:e.initial?.preMadeQA},interceptors:{onBeforeRequest:e.interceptors?.onBeforeRequest,mockResponseOnBlocked:e.interceptors?.mockResponseOnBlocked},callbacks:{onChatCreated:e.callbacks?.onChatCreated,onError:e.callbacks?.onError,onUserMessage:e.callbacks?.onUserMessage,onModelChange:e.callbacks?.onModelChange,onThreadIdUpdate:e.callbacks?.onThreadIdUpdate,onLogout:e.callbacks?.onLogout},className:e.className,errorFallback:e.errorFallback}}function Us(e){return typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[CuadraUIKit] Using legacy flat props format. Consider migrating to grouped props for better organization.
22
+ See: https://docs.cuadra.ai/guides/uikit-migration`),{connection:{baseUrl:e.baseUrl||"",proxyUrl:e.proxyUrl||"",sessionToken:e.sessionToken??null},chat:{mode:e.mode??"multiChat",modelMode:e.modelMode??"fixed",modelId:e.modelId??"",systemPrompt:e.systemPrompt??"",ephemeral:e.ephemeral??!1,enableReasoning:e.enableReasoning??!1,enableAttachments:e.enableAttachments??!1,supportsVision:e.supportsVision,initialThreadId:e.initialThreadId},ui:{theme:e.theme??"system",customTheme:e.customTheme,showThemeToggle:e.showThemeToggle??!0,language:e.language,welcomeTitle:e.welcomeTitle??"Hi, how can I help you today?",welcomeSubtitle:e.welcomeSubtitle??"Start exploring our platform and discover what you can build.",suggestions:e.suggestions,inputPlaceholder:e.inputPlaceholder??"Type your message...",extraTopPadding:e.extraTopPadding,borderless:!1,safeArea:!1,orgName:void 0,primaryColor:void 0},preMade:{responseDelay:e.preMadeResponseDelay??1e3,streamingSpeed:e.streamingSpeed??50},initial:{message:e.initialMessage,preMadeQA:e.initialPreMadeQA},interceptors:{onBeforeRequest:e.onBeforeRequest,mockResponseOnBlocked:e.mockResponseOnBlocked},callbacks:{onChatCreated:e.onChatCreated,onError:e.onError,onUserMessage:e.onUserMessage,onModelChange:e.onModelChange,onThreadIdUpdate:e.onThreadIdUpdate,onLogout:e.onLogout},className:e.className,errorFallback:e.errorFallback}}const zs=y.forwardRef(function({config:r},t){const a=y.useRef(null),i=y.useContext(ge);y.useEffect(()=>{r.ui.customTheme&&gr(r.ui.customTheme)},[r.ui.customTheme]),y.useEffect(()=>{if(r.ui.primaryColor&&typeof document<"u"){const c=document.documentElement,o=u=>{const m=u.replace("#",""),d=parseInt(m.slice(0,2),16)/255,f=parseInt(m.slice(2,4),16)/255,x=parseInt(m.slice(4,6),16)/255,h=Math.max(d,f,x),w=Math.min(d,f,x);let b=0,g=0;const C=(h+w)/2;if(h!==w){const v=h-w;switch(g=C>.5?v/(2-h-w):v/(h+w),h){case d:b=((f-x)/v+(f<x?6:0))/6;break;case f:b=((x-d)/v+2)/6;break;case x:b=((d-f)/v+4)/6;break}}return`${Math.round(b*360)} ${Math.round(g*100)}% ${Math.round(C*100)}%`};try{const u=o(r.ui.primaryColor);c.style.setProperty("--primary",u),c.style.setProperty("--cuadra-primary",`hsl(${u})`)}catch{}return()=>{c.style.removeProperty("--primary"),c.style.removeProperty("--cuadra-primary")}}},[r.ui.primaryColor]);const s=y.useMemo(()=>({sendMessage:c=>a.current?.sendMessage(c),sendPreMadeQA:(c,o,u)=>a.current?.sendPreMadeQA(c,o,u),clearChat:()=>a.current?.clearChat()}),[]);y.useImperativeHandle(t,()=>s,[]),y.useEffect(()=>{if(i)return i.registerControls(s),()=>i.unregisterControls()},[i,s]),y.useEffect(()=>(typeof window<"u"&&(process.env.NODE_ENV==="development"&&console.warn("[CuadraUIKit] window.__cuadraChatControls is deprecated. Use CuadraChatProvider and useCuadraChat() hook instead. See: https://docs.cuadra.ai/guides/uikit-migration"),window.__cuadraChatControls=s),()=>{typeof window<"u"&&delete window.__cuadraChatControls}),[s]);const n={baseUrl:r.connection.baseUrl||void 0,proxyUrl:r.connection.proxyUrl||void 0,sessionToken:r.connection.sessionToken,mode:r.chat.mode,modelMode:r.chat.modelMode,modelId:r.chat.modelId||void 0,systemPrompt:r.chat.systemPrompt||void 0,ephemeral:r.chat.ephemeral,enableReasoning:r.chat.enableReasoning,enableAttachments:r.chat.enableAttachments,supportsVision:r.chat.supportsVision,initialThreadId:r.chat.initialThreadId,theme:r.ui.theme,showThemeToggle:r.ui.showThemeToggle,language:r.ui.language,welcomeTitle:r.ui.welcomeTitle,welcomeSubtitle:r.ui.welcomeSubtitle,suggestions:r.ui.suggestions,inputPlaceholder:r.ui.inputPlaceholder,extraTopPadding:r.ui.extraTopPadding,containerClass:r.className,borderless:r.ui.borderless,safeArea:r.ui.safeArea,orgName:r.ui.orgName,primaryColor:r.ui.primaryColor,preMadeResponseDelay:r.preMade.responseDelay,streamingSpeed:r.preMade.streamingSpeed,initialMessage:r.initial.message,initialPreMadeQA:r.initial.preMadeQA,onBeforeRequest:r.interceptors.onBeforeRequest,mockResponseOnBlocked:r.interceptors.mockResponseOnBlocked,onChatCreated:r.callbacks.onChatCreated,onError:r.callbacks.onError,onUserMessage:r.callbacks.onUserMessage,onModelChange:r.callbacks.onModelChange,onThreadIdUpdate:r.callbacks.onThreadIdUpdate,onLogout:r.callbacks.onLogout};return l.jsx(Ms,{ref:a,config:n})}),$s=y.forwardRef(function(r,t){const a=br(r),i=a.errorFallback;return l.jsx(st,{fallback:i,onError:(s,n)=>{a.callbacks.onError?.(s),process.env.NODE_ENV==="development"&&console.error("[CuadraChat] Error caught by boundary:",s,n)},children:l.jsx(zs,{ref:t,config:a})})});exports.AttachmentValidationError=le;exports.Badge=it;exports.CuadraChat=$s;exports.CuadraChatContext=ge;exports.CuadraChatProvider=Ds;exports.CuadraErrorBoundary=st;exports.SourceCitations=pr;exports.applyTheme=gr;exports.createAttachmentAdapter=Ze;exports.escapeHtml=ca;exports.generateSecureUUID=Lt;exports.isV2Props=yr;exports.isValidUrl=ia;exports.normalizeCuadraChatProps=br;exports.removeTheme=Ps;exports.sanitizeSystemPrompt=na;exports.streamingMetadataStore=ee;exports.useCuadraChat=Rs;exports.useCuadraChatOptional=Ls;exports.validateBaseUrl=sa;exports.withErrorBoundary=Es;
23
23
  //# sourceMappingURL=index.cjs.map