@cuadra-ai/uikit 0.4.21 → 0.4.23

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 vr=Object.defineProperty;var jr=(e,t,r)=>t in e?vr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var D=(e,t,r)=>jr(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("react/jsx-runtime"),y=require("react"),j=require("@assistant-ui/react");require("@assistant-ui/react-markdown/styles/dot.css");const Ve=require("@assistant-ui/react-markdown");var me=typeof document<"u"?document.currentScript:null;let xe=!1,st=!1;function ot(){if(st||(st=!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{}Tr()}function Tr(){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:me&&me.tagName.toUpperCase()==="SCRIPT"&&me.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",ot):ot());const Sr=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Ir=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,r,a)=>a?a.toUpperCase():r.toLowerCase()),ct=e=>{const t=Ir(e);return t.charAt(0).toUpperCase()+t.slice(1)},It=(...e)=>e.filter((t,r,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===r).join(" ").trim(),Mr=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var Ar={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 Nr=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,...Ar,width:t,height:t,stroke:e,strokeWidth:a?Number(r)*24/Number(t):r,className:It("lucide",n),...!s&&!Mr(c)&&{"aria-hidden":"true"},...c},[...i.map(([l,m])=>y.createElement(l,m)),...Array.isArray(s)?s:[s]]));const B=(e,t)=>{const r=y.forwardRef(({className:a,...n},s)=>y.createElement(Nr,{ref:s,iconNode:t,className:It(`lucide-${Sr(ct(e))}`,`lucide-${e}`,a),...n}));return r.displayName=ct(e),r};const Pr=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],_r=B("arrow-up",Pr);const Er=[["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"}]],ut=B("brain",Er);const Rr=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],We=B("check",Rr);const Lr=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Ye=B("chevron-down",Lr);const Dr=[["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"}]],Fr=B("circle-alert",Dr);const Ur=[["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"}]],zr=B("copy",Ur);const $r=[["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"}]],Or=B("ellipsis-vertical",$r);const Br=[["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",Br);const qr=[["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"}]],Vr=B("file-spreadsheet",qr);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:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Mt=B("file-text",Wr);const Hr=[["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"}]],Kr=B("file-type",Hr);const Qr=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],At=B("loader-circle",Qr);const Gr=[["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"}]],Yr=B("message-square",Gr);const Jr=[["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",Jr);const Xr=[["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"}]],Pt=B("pencil",Xr);const Zr=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],He=B("plus",Zr);const ea=[["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"}]],_t=B("trash-2",ea);const ta=[["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"}]],ra=B("upload",ta);const aa=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ie=B("x",aa),na=[/\[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 ia(e){if(!e||typeof e!="string")return"";let t=e;for(const r of na)t=t.replace(r,"");return t=t.replace(/\n{3,}/g,`
1
+ "use strict";var vr=Object.defineProperty;var jr=(e,t,r)=>t in e?vr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var D=(e,t,r)=>jr(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("react/jsx-runtime"),x=require("react"),j=require("@assistant-ui/react");require("@assistant-ui/react-markdown/styles/dot.css");const Ve=require("@assistant-ui/react-markdown");var me=typeof document<"u"?document.currentScript:null;let xe=!1,st=!1;function ot(){if(st||(st=!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{}Tr()}function Tr(){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:me&&me.tagName.toUpperCase()==="SCRIPT"&&me.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",ot):ot());const Sr=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Mr=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,r,a)=>a?a.toUpperCase():r.toLowerCase()),ct=e=>{const t=Mr(e);return t.charAt(0).toUpperCase()+t.slice(1)},Mt=(...e)=>e.filter((t,r,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===r).join(" ").trim(),Ir=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var Ar={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 Nr=x.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:a,className:n="",children:s,iconNode:i,...c},o)=>x.createElement("svg",{ref:o,...Ar,width:t,height:t,stroke:e,strokeWidth:a?Number(r)*24/Number(t):r,className:Mt("lucide",n),...!s&&!Ir(c)&&{"aria-hidden":"true"},...c},[...i.map(([l,m])=>x.createElement(l,m)),...Array.isArray(s)?s:[s]]));const B=(e,t)=>{const r=x.forwardRef(({className:a,...n},s)=>x.createElement(Nr,{ref:s,iconNode:t,className:Mt(`lucide-${Sr(ct(e))}`,`lucide-${e}`,a),...n}));return r.displayName=ct(e),r};const Pr=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],_r=B("arrow-up",Pr);const Er=[["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"}]],ut=B("brain",Er);const Rr=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],We=B("check",Rr);const Lr=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Ye=B("chevron-down",Lr);const Dr=[["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"}]],Fr=B("circle-alert",Dr);const Ur=[["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"}]],zr=B("copy",Ur);const $r=[["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"}]],Or=B("ellipsis-vertical",$r);const Br=[["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",Br);const qr=[["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"}]],Vr=B("file-spreadsheet",qr);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:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],It=B("file-text",Wr);const Hr=[["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"}]],Kr=B("file-type",Hr);const Qr=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],At=B("loader-circle",Qr);const Gr=[["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"}]],Yr=B("message-square",Gr);const Jr=[["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",Jr);const Xr=[["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"}]],Pt=B("pencil",Xr);const Zr=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],He=B("plus",Zr);const ea=[["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"}]],_t=B("trash-2",ea);const ta=[["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"}]],ra=B("upload",ta);const aa=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Me=B("x",aa),na=[/\[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 ia(e){if(!e||typeof e!="string")return"";let t=e;for(const r of na)t=t.replace(r,"");return t=t.replace(/\n{3,}/g,`
2
2
 
3
3
  `).replace(/ {2,}/g," ").trim(),t}function sa(e){if(!e||typeof e!="string")return!1;try{const t=new URL(e);return["http:","https:"].includes(t.protocol)}catch{return!1}}function oa(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:"&&!ca(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 ca(e){try{const t=new URL(e);return["localhost","127.0.0.1","[::1]"].includes(t.hostname)}catch{return!1}}function ua(e){if(!e||typeof e!="string")return"";const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"};return e.replace(/[&<>"'/]/g,r=>t[r]||r)}function Et(){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 Rt{constructor(t,r,a=!1){D(this,"baseUrl");D(this,"sessionToken",null);D(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 Et()}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 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 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*la(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(`
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 da(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 Lt(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:[]}}}const fa=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}},ha=()=>{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=fa(),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()}}))}}};class dt{constructor(t){D(this,"_controller");D(this,"_isClosed",!1);this._controller=t}append(t){return this._controller.enqueue({type:"text-delta",path:[],textDelta:t}),this}close(){this._isClosed||(this._isClosed=!0,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}}const Dt=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)}}),ft=()=>{let e;return[Dt({start(r){e=r}}),e]};class ht{constructor(t){D(this,"_controller");D(this,"_isClosed",!1);D(this,"_mergeTask");D(this,"_argsTextController");this._controller=t;const r=Dt({start:n=>{this._argsTextController=n}});let a=!1;this._mergeTask=r.pipeTo(new WritableStream({write:n=>{switch(n.type){case"text-delta":a=!0,this._controller.enqueue(n);break;case"part-finish":a||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: ${n.type}`)}}}))}get argsText(){return this._argsTextController}async setResponse(t){this._argsTextController.close(),await Promise.resolve(),this._controller.enqueue({type:"result",path:[],...t.artifact!==void 0?{artifact:t.artifact}:{},result:t.result,isError:t.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())}}const ma=e=>new ReadableStream({start(t){return e.start?.(new ht(t))},pull(t){return e.pull?.(new ht(t))},cancel(t){return e.cancel?.(t)}}),pa=()=>{let e;return[ma({start(r){e=r}}),e]};class Ft{constructor(){D(this,"value",-1)}up(){return++this.value}}class ga extends TransformStream{constructor(t){super({transform(r,a){a.enqueue({...r,path:[t,...r.path]})}})}}class qs extends TransformStream{constructor(t){super({transform(r,a){const{path:[n,...s]}=r;if(t!==n)throw new Error(`Path mismatch: expected ${t}, got ${n}`);a.enqueue({...r,path:s})}})}}class xa extends TransformStream{constructor(t){const r=new Ft,a=new Map;super({transform(n,s){n.type==="part-start"&&n.path.length===0&&a.set(r.up(),t.up());const[i,...c]=n.path;if(i===void 0){s.enqueue(n);return}const o=a.get(i);if(o===void 0)throw new Error("Path not found");s.enqueue({...n,path:[o,...c]})}})}}let ya=(e,t=21)=>(r=t)=>{let a="",n=r|0;for(;n--;)a+=e[Math.random()*e.length|0];return a};const ba=ya("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7);class Je{constructor(t){D(this,"_state");D(this,"_parentId");this._state=t||{merger:ha(),contentCounter:new Ft}}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 ga(this._state.contentCounter.value)))}merge(t){this._state.merger.addStream(t.pipeThrough(new xa(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]=ft();return this._addPart({type:"text"},t),r}addReasoningPart(){const[t,r]=ft();return this._addPart({type:"reasoning"},t),r}addToolCallPart(t){const r=typeof t=="string"?{toolName:t}:t,a=r.toolName,n=r.toolCallId??ba(),[s,i]=pa();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 Je(this._state);return r._parentId=t,r}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}}function wa(e){const t=new Je;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 pe=new Map,ye=new Map;let Ut;function Fe(e,t){const r=pe.get(e);if(r)return r;if(t)for(const a of t){const n=ye.get(a.id);if(n)return pe.set(e,n),n}return e}function ka(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:pe.get(r)||r,externalId:void 0}},async rename(r,a){const n=Fe(r);await e.updateChat(n,{title:a})},async archive(r){},async unarchive(r){},async delete(r){const a=Fe(r);await e.deleteChat(a)},async generateTitle(r,a){const n=Fe(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 wa(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){pe.set(r,a),t?.(r,a)},unstable_Provider:({children:r})=>{const a=j.useThreadListItem(),n=a?.remoteId,s=a?.isMain;y.useEffect(()=>{s&&(Ut=n)},[n,s]);const i=y.useMemo(()=>({async load(){if(!n)return{messages:[]};try{const o=await e.getChat(n);if(!o.messages||o.messages.length===0)return{messages:[]};const l=o.messages.map(d=>Lt(d)),m=l.map((d,h)=>({message:d,parentId:h>0?l[h-1].id:null}));for(const d of l)ye.set(d.id,n);return{messages:m}}catch{return{messages:[]}}},async append(o){}}),[n,e]),c=y.useMemo(()=>({history:i}),[i]);return u.jsx(j.RuntimeAdapterProvider,{adapters:c,children:r})}}}class Ca{constructor(){D(this,"messageMetadata",new Map);D(this,"currentMessageId",null);D(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 Z=new Ca,Ke=[];let ve=[];function zt(e,t,r=50,a=800){Ke.push({question:e,response:t,streamingSpeed:r,initialDelay:a})}function $t(e,t){const{modelId:r,getModelId:a,systemPrompt:n,ephemeral:s,enableReasoning:i,onChatCreated:c,onUserMessage:o,onThreadIdUpdate:l,onBeforeRequest:m,mockResponseOnBlocked:d}=t,h=()=>(a?a():r)??null;return{async*run(x){const{messages:f,abortSignal:b}=x,w=x.unstable_threadId,g=Ke.shift();if(g){o?.();const C=g.initialDelay??800;if(C>0&&await new Promise(M=>setTimeout(M,C)),b?.aborted)throw new Error("Request aborted");const T=g.response.split(" ");let R="";const U=g.streamingSpeed||50,q=`premade-${Date.now()}`;s&&c?.(q);for(let M=0;M<T.length;M++){if(b?.aborted)throw new Error("Request aborted");R+=(M===0?"":" ")+T[M],yield{content:[{type:"text",text:R}]},await new Promise(V=>setTimeout(V,U+Math.random()*(U*.5)))}yield{content:[{type:"text",text:R}]},ve.push({role:"user",content:g.question},{role:"assistant",content:g.response});return}let v;for(const C of f){const T=ye.get(C.id);if(T){v=T;break}}o?.();let k=f,S=-1;for(let C=f.length-1;C>=0;C--)if(f[C].role==="assistant"){S=C;break}(v||S>=0)&&S>=0&&(k=f.slice(S+1));const P=da(k);if(ve.length>0&&!v){const C=ve.map(T=>({role:T.role,content:T.content}));P.unshift(...C),ve=[]}const A=[];let z;for(let C=k.length-1;C>=0;C--)if(k[C].role==="user"){z=k[C];break}if(z&&"attachments"in z){const C=z.attachments;if(C&&C.length>0){for(const T of C)if(T.file)try{const R=await e.uploadFile(T.file);A.push(R.id)}catch{}}}const F={messages:P,chatId:v||null,systemPrompt:n,ephemeral:s,enableReasoning:i,stream:!0},Q=h();if(Q&&Q.trim()!==""&&(F.modelId=Q),A.length>0&&(F.fileIds=A),m&&!await m()){if(d){const T=typeof d=="function"?d():d,R=f.filter(V=>V.role==="user"),U=R.length>0?R[R.length-1]:void 0;let q="Message";U&&(typeof U.content=="string"?q=U.content:Array.isArray(U.content)&&(q=U.content.find(oe=>oe.type==="text")?.text||"Message")),zt(q,T,40,400);const M=Ke.shift();if(M){o?.();const V=M.initialDelay??400;if(V>0&&await new Promise(X=>setTimeout(X,V)),b?.aborted)throw new Error("Request aborted");const oe=M.response.split(" ");let ce="";const J=M.streamingSpeed||40,H=`mock-${Date.now()}`;s&&c?.(H);for(let X=0;X<oe.length;X++){if(b?.aborted)throw new Error("Request aborted");ce+=(X===0?"":" ")+oe[X],yield{content:[{type:"text",text:ce}]},await new Promise(Re=>setTimeout(Re,J+Math.random()*(J*.3)))}yield{content:[{type:"text",text:ce}]};return}}throw new Error("Request blocked")}const p=await e.createOrContinueChat(F,b);let _="",$="",G;const L=[];let K=0,ae=!1;const se=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;Z.clear(),Z.setCurrentMessage(se);const I=()=>{L.length!==K&&(K=L.length,Z.update({sources:L.length>0?[...L]:void 0}))},N=()=>{I();const C=[];return $&&C.push({type:"reasoning",text:$}),_&&C.push({type:"text",text:_}),C.length===0&&C.push({type:"text",text:""}),{content:C}};for await(const C of la(p,b)){if(b?.aborted)throw new Error("Request aborted");const T=C.id||C.chatId||C.messageId;if(T&&!G){G=T;const M=w||Ut;c?.(T);for(const V of f)ye.set(V.id,T);M&&!pe.has(M)&&pe.set(M,T),l&&M&&l(M,T)}const R=C.sources;if(R&&Array.isArray(R)&&R.length>0)for(const M of R)L.some(V=>V.sourceId===M.sourceId)||L.push({sourceId:M.sourceId,filename:M.filename||"Unknown",score:M.score??1,chunkId:M.chunkId,datasetId:M.datasetId});const U=C.reasoning;if(U&&U.length>0&&($+=U,yield N()),C.type)switch(C.type){case"source-document":C.sourceId&&L.push({sourceId:C.sourceId,filename:C.title||"Unknown",score:1});continue;case"reasoning-start":continue;case"reasoning-delta":C.delta&&($+=C.delta),(_||$)&&(yield N());continue;case"reasoning-end":(_||$)&&(yield N());continue;case"text-delta":C.delta&&($&&!ae&&!_&&(ae=!0,await new Promise(M=>setTimeout(M,400))),_+=C.delta),_&&(yield N());continue;case"error":throw new Error(C.errorText||"Stream error");case"text-start":case"text-end":case"start":case"start-step":case"finish-step":case"finish":continue}const q=C.delta;if(q!=null&&($&&!ae&&!_&&(ae=!0,await new Promise(M=>setTimeout(M,400))),_+=q),C.content&&(_+=C.content),C.message&&(_+=C.message.content||""),C.finished){(_||$||L.length>0)&&(yield N());break}(_||$||L.length>0)&&(yield N())}(_||$||L.length>0)&&(yield N())}}}class le extends Error{constructor(t,r,a){super(t),this.code=r,this.file=a,this.name="AttachmentValidationError"}}const va=["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"],ja=[".pdf",".doc",".docx",".xls",".xlsx",".txt",".md",".csv",".json",".jpg",".jpeg",".png",".gif",".webp",".svg"],Ta=10*1024*1024;function mt(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 Sa(e){return e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")).toLowerCase():""}function Ia(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 Ma(){return typeof crypto<"u"&&crypto.randomUUID?"attachment-"+crypto.randomUUID():"attachment-"+Date.now()+"-"+Math.random().toString(36).slice(2,11)}function Xe(e={}){const{validation:t={},supportsVision:r=!0,onValidationError:a,onAttachmentAdded:n,onAttachmentRemoved:s}=e,{maxFileSizeBytes:i=Ta,allowedMimeTypes:c=va,allowedExtensions:o=ja,validateContentType:l=!0}=t,m=o.join(",");function d(h){if(h.size>i){const f=new le('File "'+h.name+'" is too large ('+mt(h.size)+"). Maximum size is "+mt(i)+".","FILE_TOO_LARGE",h);throw a?.(f),f}if(!r&&h.type.startsWith("image/")){const f=new le("The current model does not support image inputs. Please select a model with vision capabilities to attach images.","VISION_NOT_SUPPORTED",h);throw a?.(f),f}const x=Sa(h.name);if(x&&!o.some(f=>f.toLowerCase()===x)){const f=new le('File type "'+x+'" is not allowed. Allowed types: '+o.join(", "),"INVALID_TYPE",h);throw a?.(f),f}if(h.type&&!c.some(f=>{if(f.endsWith("/*")){const b=f.slice(0,-1);return h.type.startsWith(b)}return h.type===f})){const f=new le('File type "'+h.type+'" is not allowed.',"INVALID_TYPE",h);throw a?.(f),f}if(l&&h.type&&x&&!Ia(h.type,x)){const f=new le('File extension "'+x+'" does not match content type "'+h.type+'".',"VALIDATION_FAILED",h);throw a?.(f),f}}return{accept:m,async add({file:h}){d(h);let x="file";h.type.startsWith("image/")?x="image":(h.type.includes("pdf")||h.type.includes("document")||h.type.includes("text")||h.name.endsWith(".pdf")||h.name.endsWith(".docx")||h.name.endsWith(".txt")||h.name.endsWith(".md")||h.name.endsWith(".csv")||h.name.endsWith(".json"))&&(x="document");const f={id:Ma(),type:x,name:h.name,contentType:h.type,file:h,status:{type:"requires-action",reason:"composer-send"}};return n?.(f),f},async remove(h){s?.(h.id)},async send(h){if(h.type==="image"&&h.file){const x=await new Promise((f,b)=>{const w=new FileReader;w.onload=()=>f(w.result),w.onerror=()=>b(new Error("Failed to read file")),w.readAsDataURL(h.file)});return{...h,status:{type:"complete"},content:[{type:"image",image:x}]}}return{...h,status:{type:"complete"},content:[]}}}}class Aa{constructor(){D(this,"current",null);D(this,"listeners",new Set);D(this,"getSnapshot",()=>this.current);D(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 fe=new Aa;function Na({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:m,onError:d,onChatCreated:h,onUserMessage:x,onThreadIdUpdate:f,onChatsLoaded:b,enableAttachments:w=!1,supportsVision:g=!0,onBeforeRequest:v,mockResponseOnBlocked:k}){const S=y.useMemo(()=>new Rt(t,r||void 0,a),[t,r,a]),[P,A]=y.useState(s||null);y.useEffect(()=>{s&&A(s)},[s]);const z=y.useCallback(p=>{h?.(p)},[h]),F=y.useCallback((p,_)=>{f?.(p,_)},[f]),Q=y.useMemo(()=>$t(S,{modelId:P||void 0,systemPrompt:o,ephemeral:c,enableReasoning:l,onChatCreated:z,onUserMessage:x,onBeforeRequest:v,mockResponseOnBlocked:k}),[S,P,o,c,l,z,x,v,k]);return n==="singleChat"?u.jsx(Pa,{client:S,initialThreadId:m,modelAdapter:Q,enableAttachments:w,supportsVision:g,onChatCreated:z,children:e}):u.jsx(Ea,{client:S,modelAdapterOptions:{modelId:P||void 0,systemPrompt:o,ephemeral:c,enableReasoning:l,onChatCreated:z,onUserMessage:x,onBeforeRequest:v,mockResponseOnBlocked:k},initialThreadId:m,onChatsLoaded:b,onThreadIdUpdate:F,onError:d,enableAttachments:w,supportsVision:g,children:e})}function Pa({client:e,initialThreadId:t,modelAdapter:r,enableAttachments:a,supportsVision:n=!0,onChatCreated:s,children:i}){const[c,o]=y.useState(void 0),[l,m]=y.useState(!!t);return y.useEffect(()=>{if(!t){m(!1);return}let d=!1;async function h(){try{const x=await e.getChat(t);if(d)return;if(x.messages&&x.messages.length>0){const f=x.messages.map(b=>Lt(b));for(const b of x.messages)ye.set(b.id,x.id);o(f)}s?.(x.id)}catch{}finally{d||m(!1)}}return h(),()=>{d=!0}},[e,t,s]),l?null:u.jsx(_a,{modelAdapter:r,initialMessages:c,enableAttachments:a,supportsVision:n,children:i})}function _a({modelAdapter:e,initialMessages:t,enableAttachments:r,supportsVision:a=!0,children:n}){const s=y.useMemo(()=>r?Xe({supportsVision:a,onValidationError:c=>{fe.push(c.message,c.code)}}):void 0,[r,a]),i=j.useLocalRuntime(e,{initialMessages:t,adapters:{...s&&{attachments:s}}});return u.jsx(j.AssistantRuntimeProvider,{runtime:i,children:n})}function Ea({client:e,modelAdapterOptions:t,initialThreadId:r,onChatsLoaded:a,onThreadIdUpdate:n,onError:s,enableAttachments:i,supportsVision:c,children:o}){const l=y.useMemo(()=>ka(e,(k,S)=>{n?.(k,S)}),[e,n]),m=y.useCallback((k,S)=>{l.updateRemoteId&&l.updateRemoteId(k,S),n?.(k,S)},[l,n]),d=y.useRef(a);d.current=a;const h=y.useMemo(()=>({...l,async list(){const k=await l.list();return d.current?.(),k}}),[l]);y.useEffect(()=>{window.__cuadraThreadListAdapter=h,window.__cuadraThreadListRuntime=null},[h]);const x=y.useRef(t.modelId);x.current=t.modelId;const f=y.useMemo(()=>{const{modelId:k,...S}=t;return S},[t.systemPrompt,t.ephemeral,t.enableReasoning,t.onChatCreated,t.onUserMessage,t.onBeforeRequest,t.mockResponseOnBlocked]),b=y.useMemo(()=>$t(e,{...f,getModelId:()=>x.current,onThreadIdUpdate:m}),[e,f,m]),w=y.useMemo(()=>i?Xe({supportsVision:c,onValidationError:k=>{fe.push(k.message,k.code)}}):void 0,[i,c]),g=y.useCallback(()=>j.useLocalRuntime(b,{adapters:{...w&&{attachments:w}}}),[b,w]),v=j.unstable_useRemoteThreadListRuntime({adapter:h,runtimeHook:g});return y.useEffect(()=>{window.__cuadraThreadListRuntime=v},[v]),u.jsx(j.AssistantRuntimeProvider,{runtime:v,children:o})}function pt(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 be=Pe(/[A-Za-z]/),Ze=Pe(/[\dA-Za-z]/);function Ra(e){return e!==null&&(e<32||e===127)}function he(e){return e!==null&&e<-2}function W(e){return e!==null&&(e<0||e===32)}function ee(e){return e===-2||e===-1||e===32}const Ne=Pe(/\p{P}|\p{S}/u),ie=Pe(/\s/);function Pe(e){return t;function t(r){return r!==null&&r>-1&&e.test(String.fromCharCode(r))}}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 t=[];let r=-1;for(;++r<e.length;)t[r]=_e(e[r]);return Ee(a);function a(...n){let s=-1;for(;++s<t.length;)if(t[s].apply(this,n))return!0;return!1}}function Fa(e){const t=e;return Ee(r);function r(a){const n=a;let s;for(s in e)if(n[s]!==t[s])return!1;return!0}}function Ua(e){return Ee(t);function t(r){return r&&r.type===e}}function Ee(e){return t;function t(r,a,n){return!!($a(r)&&e.call(this,r,typeof a=="number"?a:void 0,n||void 0))}}function za(){return!0}function $a(e){return e!==null&&typeof e=="object"&&"type"in e}const Ot=[],Oa=!0,Qe=!1,Ba="skip";function Bt(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,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(h,"name",{value:"node ("+(o.type+(x?"<"+x+">":""))+")"})}return h;function h(){let x=Ot,f,b,w;if((!t||s(o,l,m[m.length-1]||void 0))&&(x=qa(r(o,m)),x[0]===Qe))return x;if("children"in o&&o.children){const g=o;if(g.children&&x[0]!==Ba)for(b=(a?g.children.length:-1)+i,w=m.concat(g);b>-1&&b<g.children.length;){const v=g.children[b];if(f=c(v,b,w)(),f[0]===Qe)return f;b=typeof f[1]=="number"?f[1]:b+i}}return x}}}function qa(e){return Array.isArray(e)?e:typeof e=="number"?[Oa,e]:e==null?Ot:[e]}function Va(e,t,r){const n=_e((r||{}).ignore||[]),s=Wa(t);let i=-1;for(;++i<s.length;)Bt(e,"text",c);function c(l,m){let d=-1,h;for(;++d<m.length;){const x=m[d],f=h?h.children:void 0;if(n(x,f?f.indexOf(x):void 0,h))return;h=x}if(h)return o(l,m)}function o(l,m){const d=m[m.length-1],h=s[i][0],x=s[i][1];let f=0;const w=d.children.indexOf(l);let g=!1,v=[];h.lastIndex=0;let k=h.exec(l.value);for(;k;){const S=k.index,P={index:k.index,input:k.input,stack:[...m,l]};let A=x(...k,P);if(typeof A=="string"&&(A=A.length>0?{type:"text",value:A}:void 0),A===!1?h.lastIndex=S+1:(f!==S&&v.push({type:"text",value:l.value.slice(f,S)}),Array.isArray(A)?v.push(...A):A&&v.push(A),f=S+k[0].length,g=!0),!h.global)break;k=h.exec(l.value)}return g?(f<l.value.length&&v.push({type:"text",value:l.value.slice(f)}),d.children.splice(w,1,...v)):v=[l],w+v.length}}function Wa(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([Ha(n[0]),Ka(n[1])])}return t}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 Ue="phrasing",ze=["autolink","link","image","label"];function Qa(){return{transforms:[tn],enter:{literalAutolink:Ya,literalAutolinkEmail:$e,literalAutolinkHttp:$e,literalAutolinkWww:$e},exit:{literalAutolink:en,literalAutolinkEmail:Za,literalAutolinkHttp:Ja,literalAutolinkWww:Xa}}}function Ga(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Ue,notInConstruct:ze},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Ue,notInConstruct:ze},{character:":",before:"[ps]",after:"\\/",inConstruct:Ue,notInConstruct:ze}]}}function Ya(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function $e(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 t=this.stack[this.stack.length-1];t.type,t.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,t,r,a,n){let s="";if(!qt(n)||(/^w/i.test(t)&&(r=t+r,t="",s="http://"),!nn(r)))return!1;const i=sn(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 an(e,t,r,a){return!qt(a,!0)||/[-\d_]$/.test(r)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+r,children:[{type:"text",value:t+"@"+r}]}}function nn(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 sn(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=pt(e,"(");let s=pt(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 qt(e,t){const r=e.input.charCodeAt(e.index-1);return(e.index===0||ie(r)||Ne(r))&&(!t||r!==47)}function ke(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}Vt.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 t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=ke(this.sliceSerialize(e)).toLowerCase(),r.label=t}function fn(e){this.exit(e)}function hn(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=ke(this.sliceSerialize(e)).toLowerCase(),r.label=t}function mn(e){this.exit(e)}function pn(){return"["}function Vt(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 gn(){return{enter:{gfmFootnoteCallString:on,gfmFootnoteCall:cn,gfmFootnoteDefinitionLabelString:un,gfmFootnoteDefinition:ln},exit:{gfmFootnoteCallString:dn,gfmFootnoteCall:fn,gfmFootnoteDefinitionLabelString:hn,gfmFootnoteDefinition:mn}}}function xn(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:r,footnoteReference:Vt},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"),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((t?`
6
- `:" ")+s.indentLines(s.containerFlow(a,c.current()),t?Wt:yn))),l(),o}}function yn(e,t,r){return t===0?e:Wt(e,t,r)}function Wt(e,t,r){return(r?"":" ")+e}const bn=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Ht.peek=jn;function wn(){return{canContainEols:["delete"],enter:{strikethrough:Cn},exit:{strikethrough:vn}}}function kn(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:bn}],handlers:{delete:Ht}}}function Cn(e){this.enter({type:"delete",children:[]},e)}function vn(e){this.exit(e)}function Ht(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 jn(){return"~"}function Tn(e){return e.length}function Sn(e,t){const r=t||{},a=(r.align||[]).concat(),n=r.stringLength||Tn,s=[],i=[],c=[],o=[];let l=0,m=-1;for(;++m<e.length;){const b=[],w=[];let g=-1;for(e[m].length>l&&(l=e[m].length);++g<e[m].length;){const v=In(e[m][g]);if(r.alignDelimiters!==!1){const k=n(v);w[g]=k,(o[g]===void 0||k>o[g])&&(o[g]=k)}b.push(v)}i[m]=b,c[m]=w}let d=-1;if(typeof a=="object"&&"length"in a)for(;++d<l;)s[d]=gt(a[d]);else{const b=gt(a);for(;++d<l;)s[d]=b}d=-1;const h=[],x=[];for(;++d<l;){const b=s[d];let w="",g="";b===99?(w=":",g=":"):b===108?w=":":b===114&&(g=":");let v=r.alignDelimiters===!1?1:Math.max(1,o[d]-w.length-g.length);const k=w+"-".repeat(v)+g;r.alignDelimiters!==!1&&(v=w.length+v+g.length,v>o[d]&&(o[d]=v),x[d]=v),h[d]=k}i.splice(1,0,h),c.splice(1,0,x),m=-1;const f=[];for(;++m<i.length;){const b=i[m],w=c[m];d=-1;const g=[];for(;++d<l;){const v=b[d]||"";let k="",S="";if(r.alignDelimiters!==!1){const P=o[d]-(w[d]||0),A=s[d];A===114?k=" ".repeat(P):A===99?P%2?(k=" ".repeat(P/2+.5),S=" ".repeat(P/2-.5)):(k=" ".repeat(P/2),S=k):S=" ".repeat(P)}r.delimiterStart!==!1&&!d&&g.push("|"),r.padding!==!1&&!(r.alignDelimiters===!1&&v==="")&&(r.delimiterStart!==!1||d)&&g.push(" "),r.alignDelimiters!==!1&&g.push(k),g.push(v),r.alignDelimiters!==!1&&g.push(S),r.padding!==!1&&g.push(" "),(r.delimiterEnd!==!1||d!==l-1)&&g.push("|")}f.push(r.delimiterEnd===!1?g.join("").replace(/ +$/,""):g.join(""))}return f.join(`
7
- `)}function In(e){return e==null?"":String(e)}function gt(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 Mn(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()),An);return n(),i}function An(e,t,r){return">"+(r?"":" ")+e}function Nn(e,t){return xt(e,t.inConstruct,!0)&&!xt(e,t.notInConstruct,!1)}function xt(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 yt(e,t,r,a){let n=-1;for(;++n<r.unsafe.length;)if(r.unsafe[n].character===`
8
- `&&Nn(r.stack,r.unsafe[n]))return/[ \t]/.test(a.before)?"":" ";return`\\
9
- `}function Pn(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 _n(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 En(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 Rn(e,t,r,a){const n=En(r),s=e.value||"",i=n==="`"?"GraveAccent":"Tilde";if(_n(e,r)){const d=r.enter("codeIndented"),h=r.indentLines(s,Ln);return d(),h}const c=r.createTracker(a),o=n.repeat(Math.max(Pn(s,n)+1,3)),l=r.enter("codeFenced");let m=c.move(o);if(e.lang){const d=r.enter(`codeFencedLang${i}`);m+=c.move(r.safe(e.lang,{before:m,after:" ",encode:["`"],...c.current()})),d()}if(e.lang&&e.meta){const d=r.enter(`codeFencedMeta${i}`);m+=c.move(" "),m+=c.move(r.safe(e.meta,{before:m,after:`
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 da(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 Lt(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:[]}}}const fa=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}},ha=()=>{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=fa(),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()}}))}}};class dt{constructor(t){D(this,"_controller");D(this,"_isClosed",!1);this._controller=t}append(t){return this._controller.enqueue({type:"text-delta",path:[],textDelta:t}),this}close(){this._isClosed||(this._isClosed=!0,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}}const Dt=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)}}),ft=()=>{let e;return[Dt({start(r){e=r}}),e]};class ht{constructor(t){D(this,"_controller");D(this,"_isClosed",!1);D(this,"_mergeTask");D(this,"_argsTextController");this._controller=t;const r=Dt({start:n=>{this._argsTextController=n}});let a=!1;this._mergeTask=r.pipeTo(new WritableStream({write:n=>{switch(n.type){case"text-delta":a=!0,this._controller.enqueue(n);break;case"part-finish":a||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: ${n.type}`)}}}))}get argsText(){return this._argsTextController}async setResponse(t){this._argsTextController.close(),await Promise.resolve(),this._controller.enqueue({type:"result",path:[],...t.artifact!==void 0?{artifact:t.artifact}:{},result:t.result,isError:t.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())}}const ma=e=>new ReadableStream({start(t){return e.start?.(new ht(t))},pull(t){return e.pull?.(new ht(t))},cancel(t){return e.cancel?.(t)}}),pa=()=>{let e;return[ma({start(r){e=r}}),e]};class Ft{constructor(){D(this,"value",-1)}up(){return++this.value}}class ga extends TransformStream{constructor(t){super({transform(r,a){a.enqueue({...r,path:[t,...r.path]})}})}}class Vs extends TransformStream{constructor(t){super({transform(r,a){const{path:[n,...s]}=r;if(t!==n)throw new Error(`Path mismatch: expected ${t}, got ${n}`);a.enqueue({...r,path:s})}})}}class xa extends TransformStream{constructor(t){const r=new Ft,a=new Map;super({transform(n,s){n.type==="part-start"&&n.path.length===0&&a.set(r.up(),t.up());const[i,...c]=n.path;if(i===void 0){s.enqueue(n);return}const o=a.get(i);if(o===void 0)throw new Error("Path not found");s.enqueue({...n,path:[o,...c]})}})}}let ya=(e,t=21)=>(r=t)=>{let a="",n=r|0;for(;n--;)a+=e[Math.random()*e.length|0];return a};const ba=ya("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7);class Je{constructor(t){D(this,"_state");D(this,"_parentId");this._state=t||{merger:ha(),contentCounter:new Ft}}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 ga(this._state.contentCounter.value)))}merge(t){this._state.merger.addStream(t.pipeThrough(new xa(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]=ft();return this._addPart({type:"text"},t),r}addReasoningPart(){const[t,r]=ft();return this._addPart({type:"reasoning"},t),r}addToolCallPart(t){const r=typeof t=="string"?{toolName:t}:t,a=r.toolName,n=r.toolCallId??ba(),[s,i]=pa();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 Je(this._state);return r._parentId=t,r}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}}function wa(e){const t=new Je;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 pe=new Map,ye=new Map;let Ut;function Fe(e,t){const r=pe.get(e);if(r)return r;if(t)for(const a of t){const n=ye.get(a.id);if(n)return pe.set(e,n),n}return e}function ka(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:pe.get(r)||r,externalId:void 0}},async rename(r,a){const n=Fe(r);await e.updateChat(n,{title:a})},async archive(r){},async unarchive(r){},async delete(r){const a=Fe(r);await e.deleteChat(a)},async generateTitle(r,a){const n=Fe(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 wa(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){pe.set(r,a),t?.(r,a)},unstable_Provider:({children:r})=>{const a=j.useThreadListItem(),n=a?.remoteId,s=a?.isMain;x.useEffect(()=>{s&&(Ut=n)},[n,s]);const i=x.useMemo(()=>({async load(){if(!n)return{messages:[]};try{const o=await e.getChat(n);if(!o.messages||o.messages.length===0)return{messages:[]};const l=o.messages.map(d=>Lt(d)),m=l.map((d,h)=>({message:d,parentId:h>0?l[h-1].id:null}));for(const d of l)ye.set(d.id,n);return{messages:m}}catch{return{messages:[]}}},async append(o){}}),[n,e]),c=x.useMemo(()=>({history:i}),[i]);return u.jsx(j.RuntimeAdapterProvider,{adapters:c,children:r})}}}class Ca{constructor(){D(this,"messageMetadata",new Map);D(this,"currentMessageId",null);D(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 Z=new Ca,Ke=[];let ve=[];function zt(e,t,r=50,a=800){Ke.push({question:e,response:t,streamingSpeed:r,initialDelay:a})}function $t(e,t){const{modelId:r,getModelId:a,systemPrompt:n,ephemeral:s,enableReasoning:i,onChatCreated:c,onUserMessage:o,onThreadIdUpdate:l,onBeforeRequest:m,mockResponseOnBlocked:d}=t,h=()=>(a?a():r)??null;return{async*run(y){const{messages:f,abortSignal:b}=y,w=y.unstable_threadId,g=Ke.shift();if(g){o?.();const v=g.initialDelay??800;if(v>0&&await new Promise(I=>setTimeout(I,v)),b?.aborted)throw new Error("Request aborted");const T=g.response.split(" ");let R="";const U=g.streamingSpeed||50,q=`premade-${Date.now()}`;s&&c?.(q);for(let I=0;I<T.length;I++){if(b?.aborted)throw new Error("Request aborted");R+=(I===0?"":" ")+T[I],yield{content:[{type:"text",text:R}]},await new Promise(V=>setTimeout(V,U+Math.random()*(U*.5)))}yield{content:[{type:"text",text:R}]},ve.push({role:"user",content:g.question},{role:"assistant",content:g.response});return}let k;for(const v of f){const T=ye.get(v.id);if(T){k=T;break}}o?.();let C=f,S=-1;for(let v=f.length-1;v>=0;v--)if(f[v].role==="assistant"){S=v;break}(k||S>=0)&&S>=0&&(C=f.slice(S+1));const P=da(C);if(ve.length>0&&!k){const v=ve.map(T=>({role:T.role,content:T.content}));P.unshift(...v),ve=[]}const A=[];let z;for(let v=C.length-1;v>=0;v--)if(C[v].role==="user"){z=C[v];break}if(z&&"attachments"in z){const v=z.attachments;if(v&&v.length>0){for(const T of v)if(T.file)try{const R=await e.uploadFile(T.file);A.push(R.id)}catch{}}}const F={messages:P,chatId:k||null,systemPrompt:n,ephemeral:s,enableReasoning:i,stream:!0},Q=h();if(Q&&Q.trim()!==""&&(F.modelId=Q),A.length>0&&(F.fileIds=A),m&&!await m()){if(d){const T=typeof d=="function"?d():d,R=f.filter(V=>V.role==="user"),U=R.length>0?R[R.length-1]:void 0;let q="Message";U&&(typeof U.content=="string"?q=U.content:Array.isArray(U.content)&&(q=U.content.find(oe=>oe.type==="text")?.text||"Message")),zt(q,T,40,400);const I=Ke.shift();if(I){o?.();const V=I.initialDelay??400;if(V>0&&await new Promise(X=>setTimeout(X,V)),b?.aborted)throw new Error("Request aborted");const oe=I.response.split(" ");let ce="";const J=I.streamingSpeed||40,H=`mock-${Date.now()}`;s&&c?.(H);for(let X=0;X<oe.length;X++){if(b?.aborted)throw new Error("Request aborted");ce+=(X===0?"":" ")+oe[X],yield{content:[{type:"text",text:ce}]},await new Promise(Re=>setTimeout(Re,J+Math.random()*(J*.3)))}yield{content:[{type:"text",text:ce}]};return}}throw new Error("Request blocked")}const p=await e.createOrContinueChat(F,b);let _="",$="",G;const L=[];let K=0,ae=!1;const se=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;Z.clear(),Z.setCurrentMessage(se);const M=()=>{L.length!==K&&(K=L.length,Z.update({sources:L.length>0?[...L]:void 0}))},N=()=>{M();const v=[];return $&&v.push({type:"reasoning",text:$}),_&&v.push({type:"text",text:_}),v.length===0&&v.push({type:"text",text:""}),{content:v}};for await(const v of la(p,b)){if(b?.aborted)throw new Error("Request aborted");const T=v.id||v.chatId||v.messageId;if(T&&!G){G=T;const I=w||Ut;c?.(T);for(const V of f)ye.set(V.id,T);I&&!pe.has(I)&&pe.set(I,T),l&&I&&l(I,T)}const R=v.sources;if(R&&Array.isArray(R)&&R.length>0)for(const I of R)L.some(V=>V.sourceId===I.sourceId)||L.push({sourceId:I.sourceId,filename:I.filename||"Unknown",score:I.score??1,chunkId:I.chunkId,datasetId:I.datasetId});const U=v.reasoning;if(U&&U.length>0&&($+=U,yield N()),v.type)switch(v.type){case"source-document":v.sourceId&&L.push({sourceId:v.sourceId,filename:v.title||"Unknown",score:1});continue;case"reasoning-start":continue;case"reasoning-delta":v.delta&&($+=v.delta),(_||$)&&(yield N());continue;case"reasoning-end":(_||$)&&(yield N());continue;case"text-delta":v.delta&&($&&!ae&&!_&&(ae=!0,await new Promise(I=>setTimeout(I,400))),_+=v.delta),_&&(yield N());continue;case"error":throw new Error(v.errorText||"Stream error");case"text-start":case"text-end":case"start":case"start-step":case"finish-step":case"finish":continue}const q=v.delta;if(q!=null&&($&&!ae&&!_&&(ae=!0,await new Promise(I=>setTimeout(I,400))),_+=q),v.content&&(_+=v.content),v.message&&(_+=v.message.content||""),v.finished){(_||$||L.length>0)&&(yield N());break}(_||$||L.length>0)&&(yield N())}(_||$||L.length>0)&&(yield N())}}}class le extends Error{constructor(t,r,a){super(t),this.code=r,this.file=a,this.name="AttachmentValidationError"}}const va=["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"],ja=[".pdf",".doc",".docx",".xls",".xlsx",".txt",".md",".csv",".json",".jpg",".jpeg",".png",".gif",".webp",".svg"],Ta=10*1024*1024;function mt(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 Sa(e){return e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")).toLowerCase():""}function Ma(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 Ia(){return typeof crypto<"u"&&crypto.randomUUID?"attachment-"+crypto.randomUUID():"attachment-"+Date.now()+"-"+Math.random().toString(36).slice(2,11)}function Xe(e={}){const{validation:t={},supportsVision:r=!0,onValidationError:a,onAttachmentAdded:n,onAttachmentRemoved:s}=e,{maxFileSizeBytes:i=Ta,allowedMimeTypes:c=va,allowedExtensions:o=ja,validateContentType:l=!0}=t,m=o.join(",");function d(h){if(h.size>i){const f=new le('File "'+h.name+'" is too large ('+mt(h.size)+"). Maximum size is "+mt(i)+".","FILE_TOO_LARGE",h);throw a?.(f),f}if(!r&&h.type.startsWith("image/")){const f=new le("The current model does not support image inputs. Please select a model with vision capabilities to attach images.","VISION_NOT_SUPPORTED",h);throw a?.(f),f}const y=Sa(h.name);if(y&&!o.some(f=>f.toLowerCase()===y)){const f=new le('File type "'+y+'" is not allowed. Allowed types: '+o.join(", "),"INVALID_TYPE",h);throw a?.(f),f}if(h.type&&!c.some(f=>{if(f.endsWith("/*")){const b=f.slice(0,-1);return h.type.startsWith(b)}return h.type===f})){const f=new le('File type "'+h.type+'" is not allowed.',"INVALID_TYPE",h);throw a?.(f),f}if(l&&h.type&&y&&!Ma(h.type,y)){const f=new le('File extension "'+y+'" does not match content type "'+h.type+'".',"VALIDATION_FAILED",h);throw a?.(f),f}}return{accept:m,async add({file:h}){d(h);let y="file";h.type.startsWith("image/")?y="image":(h.type.includes("pdf")||h.type.includes("document")||h.type.includes("text")||h.name.endsWith(".pdf")||h.name.endsWith(".docx")||h.name.endsWith(".txt")||h.name.endsWith(".md")||h.name.endsWith(".csv")||h.name.endsWith(".json"))&&(y="document");const f={id:Ia(),type:y,name:h.name,contentType:h.type,file:h,status:{type:"requires-action",reason:"composer-send"}};return n?.(f),f},async remove(h){s?.(h.id)},async send(h){if(h.type==="image"&&h.file){const y=await new Promise((f,b)=>{const w=new FileReader;w.onload=()=>f(w.result),w.onerror=()=>b(new Error("Failed to read file")),w.readAsDataURL(h.file)});return{...h,status:{type:"complete"},content:[{type:"image",image:y}]}}return{...h,status:{type:"complete"},content:[]}}}}class Aa{constructor(){D(this,"current",null);D(this,"listeners",new Set);D(this,"getSnapshot",()=>this.current);D(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 fe=new Aa;function Na({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:m,onError:d,onChatCreated:h,onUserMessage:y,onThreadIdUpdate:f,onChatsLoaded:b,enableAttachments:w=!1,supportsVision:g=!0,onBeforeRequest:k,mockResponseOnBlocked:C}){const S=x.useMemo(()=>new Rt(t,r||void 0,a),[t,r,a]),[P,A]=x.useState(s||null);x.useEffect(()=>{s&&A(s)},[s]);const z=x.useCallback(p=>{h?.(p)},[h]),F=x.useCallback((p,_)=>{f?.(p,_)},[f]),Q=x.useMemo(()=>$t(S,{modelId:P||void 0,systemPrompt:o,ephemeral:c,enableReasoning:l,onChatCreated:z,onUserMessage:y,onBeforeRequest:k,mockResponseOnBlocked:C}),[S,P,o,c,l,z,y,k,C]);return n==="singleChat"?u.jsx(Pa,{client:S,initialThreadId:m,modelAdapter:Q,enableAttachments:w,supportsVision:g,onChatCreated:z,children:e}):u.jsx(Ra,{client:S,modelAdapterOptions:{modelId:P||void 0,systemPrompt:o,ephemeral:c,enableReasoning:l,onChatCreated:z,onUserMessage:y,onBeforeRequest:k,mockResponseOnBlocked:C},initialThreadId:m,onChatsLoaded:b,onThreadIdUpdate:F,onError:d,enableAttachments:w,supportsVision:g,children:e})}function Pa({client:e,initialThreadId:t,modelAdapter:r,enableAttachments:a,supportsVision:n=!0,onChatCreated:s,children:i}){const[c,o]=x.useState(void 0),[l,m]=x.useState(!!t),[d,h]=x.useState(t??"new"),y=x.useRef(s);return y.current=s,x.useEffect(()=>{if(!t){o(void 0),h("new"),m(!1);return}m(!0);let f=!1;async function b(){try{const w=await e.getChat(t);if(f)return;if(w.messages&&w.messages.length>0){const g=w.messages.map(k=>Lt(k));for(const k of w.messages)ye.set(k.id,w.id);o(g)}else o(void 0);y.current?.(w.id)}catch{o(void 0)}finally{f||(h(t),m(!1))}}return b(),()=>{f=!0}},[e,t]),u.jsx(Ea,{modelAdapter:r,initialMessages:l?void 0:c,enableAttachments:a,supportsVision:n,children:l?u.jsx(_a,{}):i},d)}function _a(){return u.jsx("div",{className:"flex items-center justify-center h-full w-full",children:u.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-muted-foreground/30 border-t-muted-foreground"})})}function Ea({modelAdapter:e,initialMessages:t,enableAttachments:r,supportsVision:a=!0,children:n}){const s=x.useMemo(()=>r?Xe({supportsVision:a,onValidationError:c=>{fe.push(c.message,c.code)}}):void 0,[r,a]),i=j.useLocalRuntime(e,{initialMessages:t,adapters:{...s&&{attachments:s}}});return u.jsx(j.AssistantRuntimeProvider,{runtime:i,children:n})}function Ra({client:e,modelAdapterOptions:t,initialThreadId:r,onChatsLoaded:a,onThreadIdUpdate:n,onError:s,enableAttachments:i,supportsVision:c,children:o}){const l=x.useMemo(()=>ka(e,(C,S)=>{n?.(C,S)}),[e,n]),m=x.useCallback((C,S)=>{l.updateRemoteId&&l.updateRemoteId(C,S),n?.(C,S)},[l,n]),d=x.useRef(a);d.current=a;const h=x.useMemo(()=>({...l,async list(){const C=await l.list();return d.current?.(),C}}),[l]);x.useEffect(()=>{window.__cuadraThreadListAdapter=h,window.__cuadraThreadListRuntime=null},[h]);const y=x.useRef(t.modelId);y.current=t.modelId;const f=x.useMemo(()=>{const{modelId:C,...S}=t;return S},[t.systemPrompt,t.ephemeral,t.enableReasoning,t.onChatCreated,t.onUserMessage,t.onBeforeRequest,t.mockResponseOnBlocked]),b=x.useMemo(()=>$t(e,{...f,getModelId:()=>y.current,onThreadIdUpdate:m}),[e,f,m]),w=x.useMemo(()=>i?Xe({supportsVision:c,onValidationError:C=>{fe.push(C.message,C.code)}}):void 0,[i,c]),g=x.useCallback(()=>j.useLocalRuntime(b,{adapters:{...w&&{attachments:w}}}),[b,w]),k=j.unstable_useRemoteThreadListRuntime({adapter:h,runtimeHook:g});return x.useEffect(()=>{window.__cuadraThreadListRuntime=k},[k]),u.jsx(j.AssistantRuntimeProvider,{runtime:k,children:o})}function pt(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 be=Pe(/[A-Za-z]/),Ze=Pe(/[\dA-Za-z]/);function La(e){return e!==null&&(e<32||e===127)}function he(e){return e!==null&&e<-2}function W(e){return e!==null&&(e<0||e===32)}function ee(e){return e===-2||e===-1||e===32}const Ne=Pe(/\p{P}|\p{S}/u),ie=Pe(/\s/);function Pe(e){return t;function t(r){return r!==null&&r>-1&&e.test(String.fromCharCode(r))}}function Da(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 $a;if(typeof e=="function")return Ee(e);if(typeof e=="object")return Array.isArray(e)?Fa(e):Ua(e);if(typeof e=="string")return za(e);throw new Error("Expected function, string, or object as test")});function Fa(e){const t=[];let r=-1;for(;++r<e.length;)t[r]=_e(e[r]);return Ee(a);function a(...n){let s=-1;for(;++s<t.length;)if(t[s].apply(this,n))return!0;return!1}}function Ua(e){const t=e;return Ee(r);function r(a){const n=a;let s;for(s in e)if(n[s]!==t[s])return!1;return!0}}function za(e){return Ee(t);function t(r){return r&&r.type===e}}function Ee(e){return t;function t(r,a,n){return!!(Oa(r)&&e.call(this,r,typeof a=="number"?a:void 0,n||void 0))}}function $a(){return!0}function Oa(e){return e!==null&&typeof e=="object"&&"type"in e}const Ot=[],Ba=!0,Qe=!1,qa="skip";function Bt(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,m){const d=o&&typeof o=="object"?o:{};if(typeof d.type=="string"){const y=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(h,"name",{value:"node ("+(o.type+(y?"<"+y+">":""))+")"})}return h;function h(){let y=Ot,f,b,w;if((!t||s(o,l,m[m.length-1]||void 0))&&(y=Va(r(o,m)),y[0]===Qe))return y;if("children"in o&&o.children){const g=o;if(g.children&&y[0]!==qa)for(b=(a?g.children.length:-1)+i,w=m.concat(g);b>-1&&b<g.children.length;){const k=g.children[b];if(f=c(k,b,w)(),f[0]===Qe)return f;b=typeof f[1]=="number"?f[1]:b+i}}return y}}}function Va(e){return Array.isArray(e)?e:typeof e=="number"?[Ba,e]:e==null?Ot:[e]}function Wa(e,t,r){const n=_e((r||{}).ignore||[]),s=Ha(t);let i=-1;for(;++i<s.length;)Bt(e,"text",c);function c(l,m){let d=-1,h;for(;++d<m.length;){const y=m[d],f=h?h.children:void 0;if(n(y,f?f.indexOf(y):void 0,h))return;h=y}if(h)return o(l,m)}function o(l,m){const d=m[m.length-1],h=s[i][0],y=s[i][1];let f=0;const w=d.children.indexOf(l);let g=!1,k=[];h.lastIndex=0;let C=h.exec(l.value);for(;C;){const S=C.index,P={index:C.index,input:C.input,stack:[...m,l]};let A=y(...C,P);if(typeof A=="string"&&(A=A.length>0?{type:"text",value:A}:void 0),A===!1?h.lastIndex=S+1:(f!==S&&k.push({type:"text",value:l.value.slice(f,S)}),Array.isArray(A)?k.push(...A):A&&k.push(A),f=S+C[0].length,g=!0),!h.global)break;C=h.exec(l.value)}return g?(f<l.value.length&&k.push({type:"text",value:l.value.slice(f)}),d.children.splice(w,1,...k)):k=[l],w+k.length}}function Ha(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([Ka(n[0]),Qa(n[1])])}return t}function Ka(e){return typeof e=="string"?new RegExp(Da(e),"g"):e}function Qa(e){return typeof e=="function"?e:function(){return e}}const Ue="phrasing",ze=["autolink","link","image","label"];function Ga(){return{transforms:[rn],enter:{literalAutolink:Ja,literalAutolinkEmail:$e,literalAutolinkHttp:$e,literalAutolinkWww:$e},exit:{literalAutolink:tn,literalAutolinkEmail:en,literalAutolinkHttp:Xa,literalAutolinkWww:Za}}}function Ya(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Ue,notInConstruct:ze},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Ue,notInConstruct:ze},{character:":",before:"[ps]",after:"\\/",inConstruct:Ue,notInConstruct:ze}]}}function Ja(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function $e(e){this.config.enter.autolinkProtocol.call(this,e)}function Xa(e){this.config.exit.autolinkProtocol.call(this,e)}function Za(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 en(e){this.config.exit.autolinkEmail.call(this,e)}function tn(e){this.exit(e)}function rn(e){Wa(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,an],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,nn]],{ignore:["link","linkReference"]})}function an(e,t,r,a,n){let s="";if(!qt(n)||(/^w/i.test(t)&&(r=t+r,t="",s="http://"),!sn(r)))return!1;const i=on(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 nn(e,t,r,a){return!qt(a,!0)||/[-\d_]$/.test(r)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+r,children:[{type:"text",value:t+"@"+r}]}}function sn(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 on(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=pt(e,"(");let s=pt(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 qt(e,t){const r=e.input.charCodeAt(e.index-1);return(e.index===0||ie(r)||Ne(r))&&(!t||r!==47)}function ke(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}Vt.peek=gn;function cn(){this.buffer()}function un(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function ln(){this.buffer()}function dn(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function fn(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=ke(this.sliceSerialize(e)).toLowerCase(),r.label=t}function hn(e){this.exit(e)}function mn(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=ke(this.sliceSerialize(e)).toLowerCase(),r.label=t}function pn(e){this.exit(e)}function gn(){return"["}function Vt(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 xn(){return{enter:{gfmFootnoteCallString:cn,gfmFootnoteCall:un,gfmFootnoteDefinitionLabelString:ln,gfmFootnoteDefinition:dn},exit:{gfmFootnoteCallString:fn,gfmFootnoteCall:hn,gfmFootnoteDefinitionLabelString:mn,gfmFootnoteDefinition:pn}}}function yn(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:r,footnoteReference:Vt},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"),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((t?`
6
+ `:" ")+s.indentLines(s.containerFlow(a,c.current()),t?Wt:bn))),l(),o}}function bn(e,t,r){return t===0?e:Wt(e,t,r)}function Wt(e,t,r){return(r?"":" ")+e}const wn=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Ht.peek=Tn;function kn(){return{canContainEols:["delete"],enter:{strikethrough:vn},exit:{strikethrough:jn}}}function Cn(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:wn}],handlers:{delete:Ht}}}function vn(e){this.enter({type:"delete",children:[]},e)}function jn(e){this.exit(e)}function Ht(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 Tn(){return"~"}function Sn(e){return e.length}function Mn(e,t){const r=t||{},a=(r.align||[]).concat(),n=r.stringLength||Sn,s=[],i=[],c=[],o=[];let l=0,m=-1;for(;++m<e.length;){const b=[],w=[];let g=-1;for(e[m].length>l&&(l=e[m].length);++g<e[m].length;){const k=In(e[m][g]);if(r.alignDelimiters!==!1){const C=n(k);w[g]=C,(o[g]===void 0||C>o[g])&&(o[g]=C)}b.push(k)}i[m]=b,c[m]=w}let d=-1;if(typeof a=="object"&&"length"in a)for(;++d<l;)s[d]=gt(a[d]);else{const b=gt(a);for(;++d<l;)s[d]=b}d=-1;const h=[],y=[];for(;++d<l;){const b=s[d];let w="",g="";b===99?(w=":",g=":"):b===108?w=":":b===114&&(g=":");let k=r.alignDelimiters===!1?1:Math.max(1,o[d]-w.length-g.length);const C=w+"-".repeat(k)+g;r.alignDelimiters!==!1&&(k=w.length+k+g.length,k>o[d]&&(o[d]=k),y[d]=k),h[d]=C}i.splice(1,0,h),c.splice(1,0,y),m=-1;const f=[];for(;++m<i.length;){const b=i[m],w=c[m];d=-1;const g=[];for(;++d<l;){const k=b[d]||"";let C="",S="";if(r.alignDelimiters!==!1){const P=o[d]-(w[d]||0),A=s[d];A===114?C=" ".repeat(P):A===99?P%2?(C=" ".repeat(P/2+.5),S=" ".repeat(P/2-.5)):(C=" ".repeat(P/2),S=C):S=" ".repeat(P)}r.delimiterStart!==!1&&!d&&g.push("|"),r.padding!==!1&&!(r.alignDelimiters===!1&&k==="")&&(r.delimiterStart!==!1||d)&&g.push(" "),r.alignDelimiters!==!1&&g.push(C),g.push(k),r.alignDelimiters!==!1&&g.push(S),r.padding!==!1&&g.push(" "),(r.delimiterEnd!==!1||d!==l-1)&&g.push("|")}f.push(r.delimiterEnd===!1?g.join("").replace(/ +$/,""):g.join(""))}return f.join(`
7
+ `)}function In(e){return e==null?"":String(e)}function gt(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 An(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()),Nn);return n(),i}function Nn(e,t,r){return">"+(r?"":" ")+e}function Pn(e,t){return xt(e,t.inConstruct,!0)&&!xt(e,t.notInConstruct,!1)}function xt(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 yt(e,t,r,a){let n=-1;for(;++n<r.unsafe.length;)if(r.unsafe[n].character===`
8
+ `&&Pn(r.stack,r.unsafe[n]))return/[ \t]/.test(a.before)?"":" ";return`\\
9
+ `}function _n(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 En(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 Rn(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 Ln(e,t,r,a){const n=Rn(r),s=e.value||"",i=n==="`"?"GraveAccent":"Tilde";if(En(e,r)){const d=r.enter("codeIndented"),h=r.indentLines(s,Dn);return d(),h}const c=r.createTracker(a),o=n.repeat(Math.max(_n(s,n)+1,3)),l=r.enter("codeFenced");let m=c.move(o);if(e.lang){const d=r.enter(`codeFencedLang${i}`);m+=c.move(r.safe(e.lang,{before:m,after:" ",encode:["`"],...c.current()})),d()}if(e.lang&&e.meta){const d=r.enter(`codeFencedMeta${i}`);m+=c.move(" "),m+=c.move(r.safe(e.meta,{before:m,after:`
10
10
  `,encode:["`"],...c.current()})),d()}return m+=c.move(`
11
11
  `),s&&(m+=c.move(s+`
12
- `)),m+=c.move(o),l(),m}function Ln(e,t,r){return(r?"":" ")+e}function et(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 Dn(e,t,r,a){const n=et(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 Fn(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 we(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Me(e){if(e===null||W(e)||ie(e))return 1;if(Ne(e))return 2}function Ae(e,t,r){const a=Me(e),n=Me(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}}Kt.peek=Un;function Kt(e,t,r,a){const n=Fn(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),m=Ae(a.before.charCodeAt(a.before.length-1),l,n);m.inside&&(o=we(l)+o.slice(1));const d=o.charCodeAt(o.length-1),h=Ae(a.after.charCodeAt(0),d,n);h.inside&&(o=o.slice(0,-1)+we(d));const x=i.move(n);return s(),r.attentionEncodeSurroundingInfo={after:h.outside,before:m.outside},c+o+x}function Un(e,t,r){return r.options.emphasis||"*"}function zn(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),Bt(e,s,c,n);function c(o,l){const m=l[l.length-1],d=m?m.children.indexOf(o):void 0;return i(o,d,m)}}const $n={};function Qt(e,t){const r=$n,a=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,n=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return Gt(e,a,n)}function Gt(e,t,r){if(On(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 bt(e.children,t,r)}return Array.isArray(e)?bt(e,t,r):""}function bt(e,t,r){const a=[];let n=-1;for(;++n<e.length;)a[n]=Gt(e[n],t,r);return a.join("")}function On(e){return!!(e&&typeof e=="object")}function Bn(e,t){let r=!1;return zn(e,function(a){if("value"in a&&/\r?\n|\r/.test(a.value)||a.type==="break")return r=!0,Qe}),!!((!e.depth||e.depth<3)&&Qt(e)&&(t.options.setext||r))}function qn(e,t,r,a){const n=Math.max(Math.min(6,e.depth||1),1),s=r.createTracker(a);if(Bn(e,r)){const m=r.enter("headingSetext"),d=r.enter("phrasing"),h=r.containerPhrasing(e,{...s.current(),before:`
12
+ `)),m+=c.move(o),l(),m}function Dn(e,t,r){return(r?"":" ")+e}function et(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 Fn(e,t,r,a){const n=et(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 Un(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 we(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Ie(e){if(e===null||W(e)||ie(e))return 1;if(Ne(e))return 2}function Ae(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}}Kt.peek=zn;function Kt(e,t,r,a){const n=Un(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),m=Ae(a.before.charCodeAt(a.before.length-1),l,n);m.inside&&(o=we(l)+o.slice(1));const d=o.charCodeAt(o.length-1),h=Ae(a.after.charCodeAt(0),d,n);h.inside&&(o=o.slice(0,-1)+we(d));const y=i.move(n);return s(),r.attentionEncodeSurroundingInfo={after:h.outside,before:m.outside},c+o+y}function zn(e,t,r){return r.options.emphasis||"*"}function $n(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),Bt(e,s,c,n);function c(o,l){const m=l[l.length-1],d=m?m.children.indexOf(o):void 0;return i(o,d,m)}}const On={};function Qt(e,t){const r=On,a=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,n=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return Gt(e,a,n)}function Gt(e,t,r){if(Bn(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 bt(e.children,t,r)}return Array.isArray(e)?bt(e,t,r):""}function bt(e,t,r){const a=[];let n=-1;for(;++n<e.length;)a[n]=Gt(e[n],t,r);return a.join("")}function Bn(e){return!!(e&&typeof e=="object")}function qn(e,t){let r=!1;return $n(e,function(a){if("value"in a&&/\r?\n|\r/.test(a.value)||a.type==="break")return r=!0,Qe}),!!((!e.depth||e.depth<3)&&Qt(e)&&(t.options.setext||r))}function Vn(e,t,r,a){const n=Math.max(Math.min(6,e.depth||1),1),s=r.createTracker(a);if(qn(e,r)){const m=r.enter("headingSetext"),d=r.enter("phrasing"),h=r.containerPhrasing(e,{...s.current(),before:`
14
14
  `,after:`
15
15
  `});return d(),m(),h+`
16
16
  `+(n===1?"=":"-").repeat(h.length-(Math.max(h.lastIndexOf("\r"),h.lastIndexOf(`
17
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=we(l.charCodeAt(0))+l.slice(1)),l=l?i+" "+l:i,r.options.closeAtx&&(l+=" "+i),o(),c(),l}Yt.peek=Vn;function Yt(e){return e.value||""}function Vn(){return"<"}Jt.peek=Wn;function Jt(e,t,r,a){const n=et(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 Wn(){return"!"}Xt.peek=Hn;function Xt(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 m=r.stack;r.stack=[],i=r.enter("reference");const d=r.safe(r.associationId(e),{before:o,after:"]",...c.current()});return i(),r.stack=m,s(),n==="full"||!l||l!==d?o+=c.move(d+"]"):n==="shortcut"?o=o.slice(0,-1):o+=c.move("]"),o}function Hn(){return"!"}Zt.peek=Kn;function Zt(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 Kn(){return"`"}function er(e,t){const r=Qt(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))}tr.peek=Qn;function tr(e,t,r,a){const n=et(r),s=n==='"'?"Quote":"Apostrophe",i=r.createTracker(a);let c,o;if(er(e,r)){const m=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=m,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 er(e,r)?"<":"["}rr.peek=Gn;function rr(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 m=r.stack;r.stack=[],i=r.enter("reference");const d=r.safe(r.associationId(e),{before:o,after:"]",...c.current()});return i(),r.stack=m,s(),n==="full"||!l||l!==d?o+=c.move(d+"]"):n==="shortcut"?o=o.slice(0,-1):o+=c.move("]"),o}function Gn(){return"["}function tt(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 Yn(e){const t=tt(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 Jn(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 ar(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 Xn(e,t,r,a){const n=r.enter("list"),s=r.bulletCurrent;let i=e.ordered?Jn(r):tt(r);const c=e.ordered?i==="."?")":".":Yn(r);let o=t&&r.bulletLastUsed?i===r.bulletLastUsed:!1;if(!e.ordered){const m=e.children?e.children[0]:void 0;if((i==="*"||i==="-")&&m&&(!m.children||!m.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),ar(r)===i&&m){let d=-1;for(;++d<e.children.length;){const h=e.children[d];if(h&&h.type==="listItem"&&h.children&&h.children[0]&&h.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 Zn(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 ei(e,t,r,a){const n=Zn(r);let s=r.bulletCurrent||tt(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()),m);return o(),l;function m(d,h,x){return h?(x?"":" ".repeat(i))+d:(x?s:s+" ".repeat(i-s.length))+d}}function ti(e,t,r,a){const n=r.enter("paragraph"),s=r.enter("phrasing"),i=r.containerPhrasing(e,a);return s(),n(),i}const ri=_e(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function ai(e,t,r,a){return(e.children.some(function(i){return ri(i)})?r.containerPhrasing:r.containerFlow).call(r,e,a)}function ni(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}nr.peek=ii;function nr(e,t,r,a){const n=ni(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),m=Ae(a.before.charCodeAt(a.before.length-1),l,n);m.inside&&(o=we(l)+o.slice(1));const d=o.charCodeAt(o.length-1),h=Ae(a.after.charCodeAt(0),d,n);h.inside&&(o=o.slice(0,-1)+we(d));const x=i.move(n+n);return s(),r.attentionEncodeSurroundingInfo={after:h.outside,before:m.outside},c+o+x}function ii(e,t,r){return r.options.strong||"*"}function si(e,t,r,a){return r.safe(e.value,a)}function oi(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 ci(e,t,r){const a=(ar(r)+(r.options.ruleSpaces?" ":"")).repeat(oi(r));return r.options.ruleSpaces?a.slice(0,-1):a}const ir={blockquote:Mn,break:yt,code:Rn,definition:Dn,emphasis:Kt,hardBreak:yt,heading:qn,html:Yt,image:Jt,imageReference:Xt,inlineCode:Zt,link:tr,linkReference:rr,list:Xn,listItem:ei,paragraph:ti,root:ai,strong:nr,text:si,thematicBreak:ci};function ui(){return{enter:{table:li,tableData:wt,tableHeader:wt,tableRow:fi},exit:{codeText:hi,table:di,tableData:Oe,tableHeader:Oe,tableRow:Oe}}}function li(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 di(e){this.exit(e),this.data.inTable=void 0}function fi(e){this.enter({type:"tableRow",children:[]},e)}function Oe(e){this.exit(e)}function wt(e){this.enter({type:"tableCell",children:[]},e)}function hi(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,mi));const r=this.stack[this.stack.length-1];r.type,r.value=t,this.exit(e)}function mi(e,t){return t==="|"?t:e}function pi(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:h,table:i,tableCell:o,tableRow:c}};function i(x,f,b,w){return l(m(x,b,w),x.align)}function c(x,f,b,w){const g=d(x,b,w),v=l([g]);return v.slice(0,v.indexOf(`
20
- `))}function o(x,f,b,w){const g=b.enter("tableCell"),v=b.enter("phrasing"),k=b.containerPhrasing(x,{...w,before:s,after:s});return v(),g(),k}function l(x,f){return Sn(x,{align:f,alignDelimiters:a,padding:r,stringLength:n})}function m(x,f,b){const w=x.children;let g=-1;const v=[],k=f.enter("table");for(;++g<w.length;)v[g]=d(w[g],f,b);return k(),v}function d(x,f,b){const w=x.children;let g=-1;const v=[],k=f.enter("tableRow");for(;++g<w.length;)v[g]=o(w[g],x,f,b);return k(),v}function h(x,f,b){let w=ir.inlineCode(x,f,b);return b.stack.includes("tableCell")&&(w=w.replace(/\|/g,"\\$&")),w}}function gi(){return{exit:{taskListCheckValueChecked:kt,taskListCheckValueUnchecked:kt,paragraph:yi}}}function xi(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:bi}}}function kt(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function yi(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 bi(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=ir.listItem(e,t,r,{...a,...c.current()});return s&&(o=o.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,l)),o;function l(m){return m+i}}function wi(){return[Qa(),gn(),wn(),ui(),gi()]}function ki(e){return{extensions:[Ga(),xn(e),kn(),pi(e),xi()]}}function Se(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 Ct={}.hasOwnProperty;function Ci(e){const t={};let r=-1;for(;++r<e.length;)vi(t,e[r]);return t}function vi(e,t){let r;for(r in t){const n=(Ct.call(e,r)?e[r]:void 0)||(e[r]={}),s=t[r];let i;if(s)for(i in s){Ct.call(n,i)||(n[i]=[]);const c=s[i];ji(n[i],Array.isArray(c)?c:c?[c]:[])}}}function ji(e,t){let r=-1;const a=[];for(;++r<t.length;)(t[r].add==="after"?e:a).push(t[r]);Se(e,0,0,a)}const Ti={tokenize:Pi,partial:!0},sr={tokenize:_i,partial:!0},or={tokenize:Ei,partial:!0},cr={tokenize:Ri,partial:!0},Si={tokenize:Li,partial:!0},ur={name:"wwwAutolink",tokenize:Ai,previous:dr},lr={name:"protocolAutolink",tokenize:Ni,previous:fr},re={name:"emailAutolink",tokenize:Mi,previous:hr},Y={};function Ii(){return{text:Y}}let ne=48;for(;ne<123;)Y[ne]=re,ne++,ne===58?ne=65:ne===91&&(ne=97);Y[43]=re;Y[45]=re;Y[46]=re;Y[95]=re;Y[72]=[re,lr];Y[104]=[re,lr];Y[87]=[re,ur];Y[119]=[re,ur];function Mi(e,t,r){const a=this;let n,s;return i;function i(d){return!Ge(d)||!hr.call(a,a.previous)||rt(a.events)?r(d):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(d))}function c(d){return Ge(d)?(e.consume(d),c):d===64?(e.consume(d),o):r(d)}function o(d){return d===46?e.check(Si,m,l)(d):d===45||d===95||Ze(d)?(s=!0,e.consume(d),o):m(d)}function l(d){return e.consume(d),n=!0,o}function m(d){return s&&n&&be(a.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(d)):r(d)}}function Ai(e,t,r){const a=this;return n;function n(i){return i!==87&&i!==119||!dr.call(a,a.previous)||rt(a.events)?r(i):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(Ti,e.attempt(sr,e.attempt(or,s),r),r)(i))}function s(i){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(i)}}function Ni(e,t,r){const a=this;let n="",s=!1;return i;function i(d){return(d===72||d===104)&&fr.call(a,a.previous)&&!rt(a.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),n+=String.fromCodePoint(d),e.consume(d),c):r(d)}function c(d){if(be(d)&&n.length<5)return n+=String.fromCodePoint(d),e.consume(d),c;if(d===58){const h=n.toLowerCase();if(h==="http"||h==="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||Ra(d)||W(d)||ie(d)||Ne(d)?r(d):e.attempt(sr,e.attempt(or,m),r)(d)}function m(d){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(d)}}function Pi(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 _i(e,t,r){let a,n,s;return i;function i(l){return l===46||l===95?e.check(cr,o,c)(l):l===null||W(l)||ie(l)||l!==45&&Ne(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 Ei(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(cr,t,s)(i):i===null||W(i)||ie(i)?t(i):(e.consume(i),n)}function s(i){return i===41&&a++,e.consume(i),n}}function Ri(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||W(c)||ie(c)?t(c):r(c)}function n(c){return c===null||c===40||c===91||W(c)||ie(c)?t(c):a(c)}function s(c){return be(c)?i(c):r(c)}function i(c){return c===59?(e.consume(c),a):be(c)?(e.consume(c),i):r(c)}}function Li(e,t,r){return a;function a(s){return e.consume(s),n}function n(s){return Ze(s)?r(s):t(s)}}function dr(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||W(e)}function fr(e){return!be(e)}function hr(e){return!(e===47||Ge(e))}function Ge(e){return e===43||e===45||e===46||e===95||Ze(e)}function rt(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 Di(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 te(e,t,r,a){const n=a?a-1:Number.POSITIVE_INFINITY;let s=0;return i;function i(o){return ee(o)?(e.enter(r),c(o)):t(o)}function c(o){return ee(o)&&s++<n?(e.consume(o),c):(e.exit(r),t(o))}}const Fi={partial:!0,tokenize:Ui};function Ui(e,t,r){return a;function a(s){return ee(s)?te(e,n,"linePrefix")(s):n(s)}function n(s){return s===null||he(s)?t(s):r(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,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=ke(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 Bi(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 qi(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||W(d))return r(d);if(d===93){e.exit("chunkString");const h=e.exit("gfmFootnoteCallString");return n.includes(ke(a.sliceSerialize(h)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(d)}return W(d)||(i=!0),s++,e.consume(d),d===92?m:l}function m(d){return d===91||d===92||d===93?(e.consume(d),s++,l):l(d)}}function Vi(e,t,r){const a=this,n=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let s,i=0,c;return o;function o(f){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),l}function l(f){return f===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",m):r(f)}function m(f){if(i>999||f===93&&!c||f===null||f===91||W(f))return r(f);if(f===93){e.exit("chunkString");const b=e.exit("gfmFootnoteDefinitionLabelString");return s=ke(a.sliceSerialize(b)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),h}return W(f)||(c=!0),i++,e.consume(f),f===92?d:m}function d(f){return f===91||f===92||f===93?(e.consume(f),i++,m):m(f)}function h(f){return f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),n.includes(s)||n.push(s),te(e,x,"gfmFootnoteDefinitionWhitespace")):r(f)}function x(f){return t(f)}}function Wi(e,t,r){return e.check(Fi,t,e.attempt(zi,t,r))}function Hi(e){e.exit("gfmFootnoteDefinition")}function Ki(e,t,r){const a=this;return te(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 m={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)},h=[["enter",m,c],["enter",i[l][1],c],["exit",i[l][1],c],["enter",d,c]],x=c.parser.constructs.insideSpan.null;x&&Se(h,h.length,0,Di(x,i.slice(l+1,o),c)),Se(h,h.length,0,[["exit",d,c],["enter",i[o][1],c],["exit",i[o][1],c],["exit",m,c]]),Se(i,l-1,o-l+3,h),o=l+h.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,m=this.events;let d=0;return h;function h(f){return l===126&&m[m.length-1][1].type!=="characterEscape"?o(f):(i.enter("strikethroughSequenceTemporary"),x(f))}function x(f){const b=Me(l);if(f===126)return d>1?o(f):(i.consume(f),d++,x);if(d<2&&!r)return o(f);const w=i.exit("strikethroughSequenceTemporary"),g=Me(f);return w._open=!g||g===2&&!!b,w._close=!b||b===2&&!!g,c(f)}}}class Gi{constructor(){this.map=[]}add(t,r,a){Yi(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 Yi(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 Ji(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 Xi(){return{flow:{null:{name:"table",tokenize:Zi,resolveAll:es}}}}function Zi(e,t,r){const a=this;let n=0,s=0,i;return c;function c(p){let _=a.events.length-1;for(;_>-1;){const L=a.events[_][1].type;if(L==="lineEnding"||L==="linePrefix")_--;else break}const $=_>-1?a.events[_][1].type:null,G=$==="tableHead"||$==="tableRow"?A:o;return G===A&&a.parser.lazy[a.now().line]?r(p):G(p)}function o(p){return e.enter("tableHead"),e.enter("tableRow"),l(p)}function l(p){return p===124||(i=!0,s+=1),m(p)}function m(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"),x):r(p):ee(p)?te(e,m,"whitespace")(p):(s+=1,i&&(i=!1,n+=1),p===124?(e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),i=!0,m):(e.enter("data"),d(p)))}function d(p){return p===null||p===124||W(p)?(e.exit("data"),m(p)):(e.consume(p),p===92?h:d)}function h(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]?r(p):(e.enter("tableDelimiterRow"),i=!1,ee(p)?te(e,f,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(p):f(p))}function f(p){return p===45||p===58?w(p):p===124?(i=!0,e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),b):P(p)}function b(p){return ee(p)?te(e,w,"whitespace")(p):w(p)}function w(p){return p===58?(s+=1,i=!0,e.enter("tableDelimiterMarker"),e.consume(p),e.exit("tableDelimiterMarker"),g):p===45?(s+=1,g(p)):p===null||he(p)?S(p):P(p)}function g(p){return p===45?(e.enter("tableDelimiterFiller"),v(p)):P(p)}function v(p){return p===45?(e.consume(p),v):p===58?(i=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(p),e.exit("tableDelimiterMarker"),k):(e.exit("tableDelimiterFiller"),k(p))}function k(p){return ee(p)?te(e,S,"whitespace")(p):S(p)}function S(p){return p===124?f(p):p===null||he(p)?!i||n!==s?P(p):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(p)):P(p)}function P(p){return r(p)}function A(p){return e.enter("tableRow"),z(p)}function z(p){return p===124?(e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),z):p===null||he(p)?(e.exit("tableRow"),t(p)):ee(p)?te(e,z,"whitespace")(p):(e.enter("data"),F(p))}function F(p){return p===null||p===124||W(p)?(e.exit("data"),z(p)):(e.consume(p),p===92?Q:F)}function Q(p){return p===92||p===124?(e.consume(p),F):F(p)}}function es(e,t){let r=-1,a=!0,n=0,s=[0,0,0,0],i=[0,0,0,0],c=!1,o=0,l,m,d;const h=new Gi;for(;++r<e.length;){const x=e[r],f=x[1];x[0]==="enter"?f.type==="tableHead"?(c=!1,o!==0&&(vt(h,t,o,l,m),m=void 0,o=0),l={type:"table",start:Object.assign({},f.start),end:Object.assign({},f.end)},h.add(r,0,[["enter",l,t]])):f.type==="tableRow"||f.type==="tableDelimiterRow"?(a=!0,d=void 0,s=[0,0,0,0],i=[0,r+1,0,0],c&&(c=!1,m={type:"tableBody",start:Object.assign({},f.start),end:Object.assign({},f.end)},h.add(r,0,[["enter",m,t]])),n=f.type==="tableDelimiterRow"?2:m?3:1):n&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")?(a=!1,i[2]===0&&(s[1]!==0&&(i[0]=i[1],d=je(h,t,s,n,void 0,d),s=[0,0,0,0]),i[2]=r)):f.type==="tableCellDivider"&&(a?a=!1:(s[1]!==0&&(i[0]=i[1],d=je(h,t,s,n,void 0,d)),s=i,i=[s[1],r,0,0])):f.type==="tableHead"?(c=!0,o=r):f.type==="tableRow"||f.type==="tableDelimiterRow"?(o=r,s[1]!==0?(i[0]=i[1],d=je(h,t,s,n,r,d)):i[1]!==0&&(d=je(h,t,i,n,r,d)),n=0):n&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")&&(i[3]=r)}for(o!==0&&vt(h,t,o,l,m),h.consume(t.events),r=-1;++r<t.events.length;){const x=t.events[r];x[0]==="enter"&&x[1].type==="table"&&(x[1]._align=Ji(t.events,r))}return e}function je(e,t,r,a,n,s){const i=a===1?"tableHeader":a===2?"tableDelimiter":"tableData",c="tableContent";r[0]!==0&&(s.end=Object.assign({},de(t.events,r[0])),e.add(r[0],0,[["exit",s,t]]));const o=de(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=de(t.events,r[2]),m=de(t.events,r[3]),d={type:c,start:Object.assign({},l),end:Object.assign({},m)};if(e.add(r[2],0,[["enter",d,t]]),a!==2){const h=t.events[r[2]],x=t.events[r[3]];if(h[1].end=Object.assign({},x[1].end),h[1].type="chunkText",h[1].contentType="text",r[3]>r[2]+1){const f=r[2]+1,b=r[3]-r[2]-1;e.add(f,b,[])}}e.add(r[3]+1,0,[["exit",d,t]])}return n!==void 0&&(s.end=Object.assign({},de(t.events,n)),e.add(n,0,[["exit",s,t]]),s=void 0),s}function vt(e,t,r,a,n){const s=[],i=de(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 de(e,t){const r=e[t],a=r[0]==="enter"?"start":"end";return r[1][a]}const ts={name:"tasklistCheck",tokenize:as};function rs(){return{text:{91:ts}}}function as(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 W(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):ee(o)?e.check({tokenize:ns},t,r)(o):r(o)}}function ns(e,t,r){return te(e,a,"whitespace");function a(n){return n===null?r(n):t(n)}}function is(e){return Ci([Ii(),$i(),Qi(e),Xi(),rs()])}const ss={};function os(e){const t=this,r=e||ss,a=t.data(),n=a.micromarkExtensions||(a.micromarkExtensions=[]),s=a.fromMarkdownExtensions||(a.fromMarkdownExtensions=[]),i=a.toMarkdownExtensions||(a.toMarkdownExtensions=[]);n.push(is(r)),s.push(wi()),i.push(ki(r))}function O(...e){return e.filter(Boolean).join(" ")}const cs=({content:e})=>u.jsx(Ve.MarkdownTextPrimitive,{remarkPlugins:[os],className:"cuadra-aui-md",components:ds,children:e}),at=y.memo(cs),us=({language:e,code:t})=>{const{isCopied:r,copyToClipboard:a}=ls(),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(zr,{className:"cuadra-h-4 cuadra-w-4"}),r&&u.jsx(We,{className:"cuadra-h-4 cuadra-w-4"})]})]})},ls=({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)})}}},ds=Ve.unstable_memoizeMarkdownComponents({h1:({className:e,...t})=>u.jsx("h1",{className:O("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:O("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:O("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:O("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:O("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:O("cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand",e),...t}),p:({className:e,...t})=>u.jsx("p",{className:O("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:O("cuadra-text-primary cuadra-font-medium cuadra-underline cuadra-underline-offset-4 font-brand",e),...t}),blockquote:({className:e,...t})=>u.jsx("blockquote",{className:O("cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand",e),...t}),ul:({className:e,...t})=>u.jsx("ul",{className:O("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:O("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:O("cuadra-my-5 cuadra-border-b",e),...t}),table:({className:e,...t})=>u.jsx("table",{className:O("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:O("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:O("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:O("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:O("[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand",e),...t}),pre:({className:e,...t})=>u.jsx("pre",{className:O("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=Ve.useIsMarkdownCodeBlock();return u.jsx("code",{className:O(!a&&"cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand",t),...r})},CodeHeader:us});function nt({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 fs(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 mr({sources:e,maxVisible:t=3}){if(!e||e.length===0)return null;const r=fs(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(ms,{source:s},s.sourceId||i)),n>0&&u.jsxs(nt,{variant:"subtle",children:["+",n," more"]})]})]})}function hs(e){switch(e.split(".").pop()?.toLowerCase()){case"csv":case"xlsx":case"xls":return Vr;case"md":case"txt":return Kr;default:return Mt}}function ms({source:e}){const{filename:t,score:r}=e,a=hs(t);return u.jsxs(nt,{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 ps=y.forwardRef(function({welcomeTitle:t="What should we work on?",welcomeSubtitle:r,extraTopPadding:a,suggestions:n,inputPlaceholder:s="Reply...",enableAttachments:i=!1,preMadeResponseDelay:c=1e3,streamingSpeed:o=50,safeArea:l=!1,composerBorder:m=!1,models:d,selectedModelId:h,onModelChange:x,showChatHeader:f=!1},b){const w=j.useThreadRuntime(),g=j.useAui(),[v,k]=y.useState(!1),[S,P]=y.useState(null),[A,z]=y.useState(!1),F=y.useSyncExternalStore(fe.subscribe,fe.getSnapshot);y.useEffect(()=>{if(F){const I=setTimeout(()=>fe.clear(),4e3);return()=>clearTimeout(I)}},[F]);const p=j.useThread(I=>{const N=I.messages;return!N||N.length===0})&&!v,_=j.useAssistantRuntime(),$=y.useRef(_);$.current=_;const G=y.useRef(h);y.useEffect(()=>{const I=G.current;if(G.current=h,I&&h&&I!==h){const N=setTimeout(()=>{try{$.current.switchToNewThread()}catch{}},50);return()=>clearTimeout(N)}},[h]);const L=y.useCallback((I,N,C)=>{if(!A)try{const T=C?.streamingSpeed??o,R=C?.delay??c;zt(I,N,T,R),g.composer().setText(I),setTimeout(()=>{g.composer().send()},10)}catch{}},[A,o,c,g]),K=y.useCallback(I=>{try{g.composer().setText(I),setTimeout(()=>{g.composer().send()},10)}catch{}},[g]),ae=y.useCallback(async I=>{if(!(A||!w))try{if(I.response){const N=I.responseDelay??c;await L(I.prompt,I.response,{delay:N,streamingSpeed:o})}else K(I.prompt)}catch{}},[w,A,c,o,L,K]),se=y.useCallback(async()=>{try{const N=window.__cuadraThreadListRuntime?.threadList;N?.switchToNewThread&&await N.switchToNewThread()}catch{}},[]);return y.useImperativeHandle(b,()=>({sendMessage:K,sendPreMadeQA:L,clearChat:se}),[K,L,se]),y.useEffect(()=>{if(!w){k(!1);return}try{const I=w?.store;if(!I){k(!1);return}const N=I.subscribe?.(T=>{const R=T?.threadId,U=T?.messages||[],q=T?.isLoadingHistory||!1,M=U.length;R&&R!==S&&P(R),k(q&&M===0)}),C=I.getState?.();if(C){const T=C?.threadId,R=C?.messages||[],U=C?.isLoadingHistory||!1,q=R.length;T&&T!==S&&P(T),k(U&&q===0)}return()=>{N&&N()}}catch{k(!1)}},[w,S]),u.jsxs(j.ThreadPrimitive.Root,{className:"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full cuadra-relative",children:[(f||d&&d.length>0)&&u.jsxs("div",{className:"cuadra-relative cuadra-flex cuadra-items-center cuadra-justify-center cuadra-px-3 cuadra-py-2 cuadra-min-h-[48px]",children:[f&&u.jsx("div",{className:"cuadra-absolute cuadra-right-3 md:cuadra-right-auto md:cuadra-left-3 cuadra-top-0 cuadra-bottom-0 cuadra-flex cuadra-items-center",children:u.jsx(Cs,{})}),d&&d.length>0&&u.jsx(ks,{models:d,selectedModelId:h,onModelChange:x})]}),u.jsxs(j.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(ra,{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(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||(f||d&&d.length>0?"0.5rem":"2rem")},children:v?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(j.ThreadPrimitive.Empty,{children:u.jsx(gs,{title:t,subtitle:r})}),u.jsx(j.ThreadPrimitive.Messages,{components:{UserMessage:xs,AssistantMessage:ws}})]})}),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:[F&&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(Fr,{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:F.message}),u.jsx("button",{type:"button",onClick:()=>fe.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(Ie,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})]}),i&&u.jsx(j.ComposerPrimitive.Attachments,{components:{Attachment:()=>{const I=j.useAuiState(({attachment:N})=>N);return I?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:I.name||"Attachment"}),u.jsx(j.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(Ie,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})})]}):null}}}),u.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:[u.jsx(j.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(j.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(He,{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.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:u.jsx(j.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(_r,{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((I,N)=>u.jsx("button",{type:"button",onClick:()=>ae(I),disabled:A,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:I.prompt},`suggestion-${N}`))})]})]})});function gs({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-2xl md: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}),t&&u.jsx("p",{className:"cuadra-text-sm md:cuadra-text-base cuadra-text-muted-foreground cuadra-mt-2 md:cuadra-mt-3 cuadra-max-w-lg cuadra-whitespace-pre-line",children:t})]})}function xs(){return u.jsx(j.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(j.MessagePrimitive.Attachments,{components:{Attachment:()=>{const e=j.useAuiState(({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(j.MessagePrimitive.Parts,{components:{Text:({text:e})=>u.jsx(at,{content:e||""})}})})]})})}function ys({text:e}){const[t,r]=y.useState(!1),a=j.useAuiState(({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(Ye,{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(at,{content:e})})})]}):null}function bs(){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 ws(){const e=j.useAuiState(({message:i})=>i?.status?.type==="running"),t=j.useAuiState(({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=Z.getCurrentMessageId();i&&(r.current=!0,n(i))}},[e,t]);const s=y.useSyncExternalStore(i=>Z.subscribe(i),()=>{if(a){const i=Z.getForMessage(a);return i.sources?.length?i.sources:null}if(e&&t){const i=Z.getCurrentMessageId();if(i){const c=Z.getForMessage(i);return c.sources?.length?c.sources:null}}return null},()=>null);return u.jsx(j.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(j.MessagePrimitive.Parts,{components:{Text:({text:i})=>u.jsx(at,{content:i||""}),Reasoning:({text:i})=>u.jsx(ys,{text:i||""})}}),e&&!t&&u.jsx(bs,{}),s&&s.length>0&&u.jsx(mr,{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 ks({models:e,selectedModelId:t,onModelChange:r}){const[a,n]=y.useState(!1),s=e.find(c=>c.id===t)||e[0];if(!s)return null;const i=c=>{n(!1),c!==t&&r?.(c)};return u.jsxs("div",{className:"cuadra-relative",children:[u.jsxs("button",{type:"button",onClick:()=>n(!a),className:"cuadra-flex cuadra-items-center cuadra-gap-1.5 cuadra-px-2.5 cuadra-py-1.5 cuadra-rounded-lg cuadra-text-sm md:cuadra-text-base cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-colors font-brand",children:[u.jsx("span",{children:s.name}),u.jsx(Ye,{className:"cuadra-h-3.5 cuadra-w-3.5"})]}),a&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"cuadra-hidden md:cuadra-block cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:()=>n(!1)}),u.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:[u.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-end cuadra-px-4 cuadra-py-3 cuadra-min-h-[48px]",children:u.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:u.jsx(Ie,{className:"cuadra-h-5 cuadra-w-5"})})}),u.jsx("div",{className:"cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto cuadra-py-1",children:e.map(c=>u.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:()=>i(c.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:c.name}),c.supportsReasoning&&u.jsx(Te,{label:"Reasoning",children:u.jsx(ut,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})}),c.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"})})]}),c.description&&u.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground",children:c.description})]}),c.id===t&&u.jsx(We,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-primary cuadra-flex-shrink-0"})]},c.id))})]}),u.jsx("div",{className:"cuadra-hidden md:cuadra-block cuadra-absolute cuadra-top-full cuadra-left-1/2 cuadra--translate-x-1/2 cuadra-mt-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(c=>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:()=>i(c.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:c.name}),c.supportsReasoning&&u.jsx(Te,{label:"Reasoning",children:u.jsx(ut,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})}),c.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"})})]}),c.description&&u.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground",children:c.description})]}),c.id===t&&u.jsx(We,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-primary cuadra-flex-shrink-0"})]},c.id))})]})]})}function Cs(){const e=j.useAuiState(({threadListItem:n})=>n?.title??null),[t,r]=y.useState(!1),a=e||"Untitled chat";return u.jsxs("div",{className:"cuadra-relative",children:[u.jsxs("button",{type:"button",onClick:()=>r(!t),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:[u.jsx("span",{className:"cuadra-font-medium cuadra-truncate cuadra-max-w-[200px]",children:a}),u.jsx(Ye,{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":""}`})]}),u.jsx("button",{type:"button",onClick:()=>r(!t),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:u.jsx(Yr,{className:"cuadra-h-5 cuadra-w-5"})}),t&&u.jsx(vs,{onClose:()=>r(!1)})]})}function vs({onClose:e}){return u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"cuadra-hidden md:cuadra-block cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:e}),u.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:[u.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-end cuadra-px-4 cuadra-py-3 cuadra-min-h-[48px]",children:u.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:u.jsx(Ie,{className:"cuadra-h-5 cuadra-w-5"})})}),u.jsxs(j.ThreadListPrimitive.Root,{className:"cuadra-flex cuadra-flex-col cuadra-flex-1 cuadra-min-h-0",children:[u.jsx("div",{className:"cuadra-px-3 cuadra-py-2",children:u.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:[u.jsx(He,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"New Chat"]})}),u.jsx(jt,{onSelect:e,fullHeight:!0})]})]}),u.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:u.jsxs(j.ThreadListPrimitive.Root,{className:"cuadra-flex cuadra-flex-col",children:[u.jsx("div",{className:"cuadra-px-2 cuadra-py-1.5",children:u.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:[u.jsx(He,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"New Chat"]})}),u.jsx(jt,{onSelect:e})]})})]})}function jt({onSelect:e,fullHeight:t}){const r=j.useAuiState(({threads:s})=>s?.threadIds??[]),a=j.useAuiState(({threads:s})=>s?.newThreadId);return r.some(s=>s!==a)?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 scrollbar-thin ${t?"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:t?void 0:{maxHeight:"340px"},children:u.jsx(j.ThreadListPrimitive.Items,{components:{ThreadListItem:s=>u.jsx(js,{...s,onSelect:e,fullHeight:t})}})})]}):null}function js({onSelect:e,fullHeight:t}){const r=j.useThreadListItem(),a=j.useThreadListItemRuntime(),n=j.useAssistantRuntime(),s=j.useThread(g=>g.threadId),i=r?.id===s,[c,o]=y.useState(!1),[l,m]=y.useState(!1),[d,h]=y.useState(r?.title||""),[x,f]=y.useState(!1),b=async()=>{if(!r?.remoteId||!d||d===r.title){m(!1);return}try{f(!0),await a.rename(d)}catch{}finally{f(!1),m(!1)}},w=async g=>{g.stopPropagation();try{await a.delete(),i&&await n.switchToNewThread()}catch(v){console.error("[CuadraChat] Failed to delete thread:",v)}};return y.useEffect(()=>{r?.title&&!l&&h(r.title)},[r?.title,l]),r?t?u.jsxs(j.ThreadListItemPrimitive.Root,{className:`cuadra-relative cuadra-flex cuadra-items-center cuadra-rounded-xl cuadra-transition-colors cuadra-cursor-pointer ${i?"cuadra-bg-primary/10 cuadra-ring-1 cuadra-ring-primary/20":"cuadra-bg-muted/40"}`,children:[l?u.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: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:d,onChange:g=>h(g.target.value),onKeyDown:g=>{g.stopPropagation(),g.key==="Enter"&&b(),g.key==="Escape"&&(m(!1),h(r.title||""))},onBlur:()=>void b(),disabled:x,autoFocus:!0})}):u.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:u.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground cuadra-truncate cuadra-block cuadra-text-left font-brand",children:r.title||"Chat"})}),!l&&u.jsx(Ts,{onRename:()=>{m(!0),h(r.title||"Chat")},onDelete:w})]}):u.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 ${i?"cuadra-bg-muted":"hover:cuadra-bg-muted/60"}`,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),children:[l?u.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: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:d,onChange:g=>h(g.target.value),onKeyDown:g=>{g.stopPropagation(),g.key==="Enter"&&b(),g.key==="Escape"&&(m(!1),h(r.title||""))},onBlur:()=>void b(),disabled:x,autoFocus:!0})}):u.jsx(j.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:r.title||"Chat"})}),(c||i)&&!l&&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:g=>{g.stopPropagation(),m(!0),h(r.title||"Chat")},title:"Rename",children:u.jsx(Pt,{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(_t,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-destructive"})})]})]}):null}function Ts({onRename:e,onDelete:t}){const[r,a]=y.useState(!1);return u.jsxs("div",{className:"cuadra-relative cuadra-flex-shrink-0 cuadra-mr-2",children:[u.jsx("button",{type:"button",className:"cuadra-p-2 cuadra-rounded-lg cuadra-text-muted-foreground hover:cuadra-bg-background/60 cuadra-transition-colors",onClick:n=>{n.stopPropagation(),a(!r)},children:u.jsx(Or,{className:"cuadra-h-4 cuadra-w-4"})}),r&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-50",onClick:n=>{n.stopPropagation(),a(!1)}}),u.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:[u.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:n=>{n.stopPropagation(),a(!1),e()},children:[u.jsx(Pt,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"Rename"]}),u.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:n=>{n.stopPropagation(),a(!1),t(n)},children:[u.jsx(_t,{className:"cuadra-h-4 cuadra-w-4"}),"Delete"]})]})]})]})}const Be=({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}),Ss=y.createContext(void 0),qe=({children:e,value:t})=>u.jsx(Ss.Provider,{value:t,children:e});function Is(){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:me&&me.tagName.toUpperCase()==="SCRIPT"&&me.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 Ms=y.forwardRef(function({config:t},r){Is();const a=y.useRef(null),n=y.useRef(!1),{baseUrl:s,proxyUrl:i,sessionToken:c,mode:o="multiChat",modelMode:l="fixed",modelId:m,onModelChange:d,ephemeral:h=!1,systemPrompt:x,enableReasoning:f=!1,initialThreadId:b,welcomeTitle:w,welcomeSubtitle:g,extraTopPadding:v,suggestions:k,inputPlaceholder:S,preMadeResponseDelay:P=1e3,streamingSpeed:A=50,initialMessage:z,initialPreMadeQA:F,theme:Q="system",onError:p,onChatCreated:_,onUserMessage:$,onThreadIdUpdate:G,enableAttachments:L=!1,supportsVision:K,onBeforeRequest:ae,mockResponseOnBlocked:se}=t;y.useImperativeHandle(r,()=>({sendMessage:E=>{a.current?.sendMessage(E)},sendPreMadeQA:(E,ue,Cr)=>{a.current?.sendPreMadeQA(E,ue,Cr)},clearChat:()=>{a.current?.clearChat()}}),[]),y.useEffect(()=>{if(n.current)return;const E=setTimeout(()=>{F?(n.current=!0,a.current?.sendPreMadeQA(F.question,F.answer,{delay:P,streamingSpeed:A})):z&&(n.current=!0,a.current?.sendMessage(z))},500);return()=>clearTimeout(E)},[z,F,P,A]);const I=i||s||"",N=!!i,C=y.useMemo(()=>new Rt(I,c||void 0,N),[I,c,N]),[T,R]=y.useState(null),[U,q]=y.useState(!1),[M,V]=y.useState(null),[oe,ce]=y.useState(!1);y.useEffect(()=>{o==="multiChat"&&ce(!0)},[o]);const J=y.useCallback(async()=>{if(l==="selector"){q(!0),V(null);try{const E=await C.listModels();R(E)}catch(E){V(E instanceof Error?E:new Error("Failed to load models"))}finally{q(!1)}}},[C,l]);y.useEffect(()=>{l==="selector"&&J()},[l,J]),y.useEffect(()=>(typeof window<"u"&&(window.__cuadraUIKitRefetchModels=J),()=>{typeof window<"u"&&delete window.__cuadraUIKitRefetchModels}),[J]);const[H,X]=y.useState(l==="fixed"&&m||null),Re=y.useRef(H),Ce=y.useCallback(E=>{X(E),Re.current=E,d?.(E)},[d,o]);y.useEffect(()=>{if(l==="selector"&&T?.items&&T.items.length>0&&!H){const E=T.items[0];if(E?.id){const ue=E.id;X(ue),d?.(ue)}}},[l,T?.items,H,d]);const br=l==="fixed"?!!m:!!H,wr=y.useMemo(()=>K!==void 0?K:l==="selector"&&H&&T?.items?T.items.find(ue=>ue.id===H)?.supportsVision??!0:!0,[K,l,H,T?.items]),Le=y.useMemo(()=>(T?.items||[]).filter(E=>E?.id&&E?.displayName).map(E=>({id:E.id,name:E.displayName,supportsVision:E.supportsVision??!1,supportsReasoning:E.supportsReasoning??!1})),[T]),De=y.useMemo(()=>({currentModelId:H||"",models:Le,modelsLoading:U,modelsError:M,onModelChange:Ce,refetchModels:J}),[H,Le,U,M,Ce,J]),kr=y.useCallback(()=>{o==="multiChat"&&ce(!1)},[o]);return l==="selector"&&U||o==="multiChat"&&oe?u.jsx(qe,{value:De,children:u.jsx(Be,{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"&&!br&&M?u.jsx(qe,{value:De,children:u.jsx(Be,{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(qe,{value:De,children:u.jsx(Na,{baseUrl:N?I:s||I,sessionToken:c,isProxyMode:N,mode:o,modelMode:l,modelId:H||m||void 0,onModelChange:Ce,ephemeral:h,systemPrompt:x,enableReasoning:f,initialThreadId:b,enableAttachments:L,supportsVision:wr,onError:p,onChatCreated:_,onUserMessage:$,onThreadIdUpdate:G,onBeforeRequest:ae,mockResponseOnBlocked:se,onChatsLoaded:kr,children:u.jsx(Be,{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(ps,{ref:a,welcomeTitle:w,welcomeSubtitle:g,extraTopPadding:v,suggestions:k,inputPlaceholder:S,enableAttachments:L,preMadeResponseDelay:P,streamingSpeed:A,safeArea:t.safeArea,showChatHeader:o==="multiChat",models:l==="selector"?Le:void 0,selectedModelId:H||void 0,onModelChange:l==="selector"?Ce:void 0,theme:Q})})})})})})})})});function pr(e,t=":root"){if(typeof document>"u")return;const r=document.documentElement,a=[];if(e.light){Ns(e.light,r);const n=Tt(e.light);n&&a.push(`.cuadra-uikit { ${n} }`)}if(e.dark){const n=Tt(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 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 gr(e){const t=As[e];return t?`--cuadra-${t}`:`--cuadra-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function Ns(e,t){Object.entries(e).forEach(([r,a])=>{if(a){const n=gr(r);t.style.setProperty(n,a)}})}function Tt(e){return Object.entries(e).map(([t,r])=>r?`${gr(t)}: ${r};`:"").filter(Boolean).join(" ")}function Ps(){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 _s({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 it extends y.Component{constructor(r){super(r);D(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(_s,{error:a,onReset:this.reset})}return this.props.children}}function Es(e,t){const r=a=>u.jsx(it,{...t,children:u.jsx(e,{...a})});return r.displayName=`withErrorBoundary(${e.displayName||e.name||"Component"})`,r}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[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(ge.Provider,{value:s,children:e})}function xr(e){return"connection"in e&&typeof e.connection=="object"}function yr(e){return xr(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}}let St=!1;const zs=y.forwardRef(function({config:t},r){const a=y.useRef(null),n=y.useContext(ge);y.useEffect(()=>{t.ui.customTheme&&pr(t.ui.customTheme)},[t.ui.customTheme]),y.useEffect(()=>{if(t.ui.primaryColor&&typeof document<"u"){const c=document.documentElement,o=l=>{const m=l.replace("#",""),d=parseInt(m.slice(0,2),16)/255,h=parseInt(m.slice(2,4),16)/255,x=parseInt(m.slice(4,6),16)/255,f=Math.max(d,h,x),b=Math.min(d,h,x);let w=0,g=0;const v=(f+b)/2;if(f!==b){const k=f-b;switch(g=v>.5?k/(2-f-b):k/(f+b),f){case d:w=((h-x)/k+(h<x?6:0))/6;break;case h:w=((x-d)/k+2)/6;break;case x:w=((d-h)/k+4)/6;break}}return`${Math.round(w*360)} ${Math.round(g*100)}% ${Math.round(v*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"&&!St&&(St=!0,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(Ms,{ref:a,config:i})}),$s=y.forwardRef(function(t,r){const a=yr(t),n=a.errorFallback;return u.jsx(it,{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(zs,{ref:r,config:a})})});exports.AttachmentValidationError=le;exports.Badge=nt;exports.CuadraChat=$s;exports.CuadraChatContext=ge;exports.CuadraChatProvider=Ds;exports.CuadraErrorBoundary=it;exports.SourceCitations=mr;exports.applyTheme=pr;exports.createAttachmentAdapter=Xe;exports.escapeHtml=ua;exports.generateSecureUUID=Et;exports.isV2Props=xr;exports.isValidUrl=sa;exports.normalizeCuadraChatProps=yr;exports.removeTheme=Ps;exports.sanitizeSystemPrompt=ia;exports.streamingMetadataStore=Z;exports.useCuadraChat=Rs;exports.useCuadraChatOptional=Ls;exports.validateBaseUrl=oa;exports.withErrorBoundary=Es;
18
+ `,...s.current()});return/^[\t ]/.test(l)&&(l=we(l.charCodeAt(0))+l.slice(1)),l=l?i+" "+l:i,r.options.closeAtx&&(l+=" "+i),o(),c(),l}Yt.peek=Wn;function Yt(e){return e.value||""}function Wn(){return"<"}Jt.peek=Hn;function Jt(e,t,r,a){const n=et(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 Hn(){return"!"}Xt.peek=Kn;function Xt(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 m=r.stack;r.stack=[],i=r.enter("reference");const d=r.safe(r.associationId(e),{before:o,after:"]",...c.current()});return i(),r.stack=m,s(),n==="full"||!l||l!==d?o+=c.move(d+"]"):n==="shortcut"?o=o.slice(0,-1):o+=c.move("]"),o}function Kn(){return"!"}Zt.peek=Qn;function Zt(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 Qn(){return"`"}function er(e,t){const r=Qt(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))}tr.peek=Gn;function tr(e,t,r,a){const n=et(r),s=n==='"'?"Quote":"Apostrophe",i=r.createTracker(a);let c,o;if(er(e,r)){const m=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=m,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 Gn(e,t,r){return er(e,r)?"<":"["}rr.peek=Yn;function rr(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 m=r.stack;r.stack=[],i=r.enter("reference");const d=r.safe(r.associationId(e),{before:o,after:"]",...c.current()});return i(),r.stack=m,s(),n==="full"||!l||l!==d?o+=c.move(d+"]"):n==="shortcut"?o=o.slice(0,-1):o+=c.move("]"),o}function Yn(){return"["}function tt(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 Jn(e){const t=tt(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 Xn(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 ar(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 Zn(e,t,r,a){const n=r.enter("list"),s=r.bulletCurrent;let i=e.ordered?Xn(r):tt(r);const c=e.ordered?i==="."?")":".":Jn(r);let o=t&&r.bulletLastUsed?i===r.bulletLastUsed:!1;if(!e.ordered){const m=e.children?e.children[0]:void 0;if((i==="*"||i==="-")&&m&&(!m.children||!m.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),ar(r)===i&&m){let d=-1;for(;++d<e.children.length;){const h=e.children[d];if(h&&h.type==="listItem"&&h.children&&h.children[0]&&h.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 ei(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 ti(e,t,r,a){const n=ei(r);let s=r.bulletCurrent||tt(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()),m);return o(),l;function m(d,h,y){return h?(y?"":" ".repeat(i))+d:(y?s:s+" ".repeat(i-s.length))+d}}function ri(e,t,r,a){const n=r.enter("paragraph"),s=r.enter("phrasing"),i=r.containerPhrasing(e,a);return s(),n(),i}const ai=_e(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function ni(e,t,r,a){return(e.children.some(function(i){return ai(i)})?r.containerPhrasing:r.containerFlow).call(r,e,a)}function ii(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}nr.peek=si;function nr(e,t,r,a){const n=ii(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),m=Ae(a.before.charCodeAt(a.before.length-1),l,n);m.inside&&(o=we(l)+o.slice(1));const d=o.charCodeAt(o.length-1),h=Ae(a.after.charCodeAt(0),d,n);h.inside&&(o=o.slice(0,-1)+we(d));const y=i.move(n+n);return s(),r.attentionEncodeSurroundingInfo={after:h.outside,before:m.outside},c+o+y}function si(e,t,r){return r.options.strong||"*"}function oi(e,t,r,a){return r.safe(e.value,a)}function ci(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 ui(e,t,r){const a=(ar(r)+(r.options.ruleSpaces?" ":"")).repeat(ci(r));return r.options.ruleSpaces?a.slice(0,-1):a}const ir={blockquote:An,break:yt,code:Ln,definition:Fn,emphasis:Kt,hardBreak:yt,heading:Vn,html:Yt,image:Jt,imageReference:Xt,inlineCode:Zt,link:tr,linkReference:rr,list:Zn,listItem:ti,paragraph:ri,root:ni,strong:nr,text:oi,thematicBreak:ui};function li(){return{enter:{table:di,tableData:wt,tableHeader:wt,tableRow:hi},exit:{codeText:mi,table:fi,tableData:Oe,tableHeader:Oe,tableRow:Oe}}}function di(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 fi(e){this.exit(e),this.data.inTable=void 0}function hi(e){this.enter({type:"tableRow",children:[]},e)}function Oe(e){this.exit(e)}function wt(e){this.enter({type:"tableCell",children:[]},e)}function mi(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,pi));const r=this.stack[this.stack.length-1];r.type,r.value=t,this.exit(e)}function pi(e,t){return t==="|"?t:e}function gi(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:h,table:i,tableCell:o,tableRow:c}};function i(y,f,b,w){return l(m(y,b,w),y.align)}function c(y,f,b,w){const g=d(y,b,w),k=l([g]);return k.slice(0,k.indexOf(`
20
+ `))}function o(y,f,b,w){const g=b.enter("tableCell"),k=b.enter("phrasing"),C=b.containerPhrasing(y,{...w,before:s,after:s});return k(),g(),C}function l(y,f){return Mn(y,{align:f,alignDelimiters:a,padding:r,stringLength:n})}function m(y,f,b){const w=y.children;let g=-1;const k=[],C=f.enter("table");for(;++g<w.length;)k[g]=d(w[g],f,b);return C(),k}function d(y,f,b){const w=y.children;let g=-1;const k=[],C=f.enter("tableRow");for(;++g<w.length;)k[g]=o(w[g],y,f,b);return C(),k}function h(y,f,b){let w=ir.inlineCode(y,f,b);return b.stack.includes("tableCell")&&(w=w.replace(/\|/g,"\\$&")),w}}function xi(){return{exit:{taskListCheckValueChecked:kt,taskListCheckValueUnchecked:kt,paragraph:bi}}}function yi(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:wi}}}function kt(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function bi(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 wi(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=ir.listItem(e,t,r,{...a,...c.current()});return s&&(o=o.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,l)),o;function l(m){return m+i}}function ki(){return[Ga(),xn(),kn(),li(),xi()]}function Ci(e){return{extensions:[Ya(),yn(e),Cn(),gi(e),yi()]}}function Se(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 Ct={}.hasOwnProperty;function vi(e){const t={};let r=-1;for(;++r<e.length;)ji(t,e[r]);return t}function ji(e,t){let r;for(r in t){const n=(Ct.call(e,r)?e[r]:void 0)||(e[r]={}),s=t[r];let i;if(s)for(i in s){Ct.call(n,i)||(n[i]=[]);const c=s[i];Ti(n[i],Array.isArray(c)?c:c?[c]:[])}}}function Ti(e,t){let r=-1;const a=[];for(;++r<t.length;)(t[r].add==="after"?e:a).push(t[r]);Se(e,0,0,a)}const Si={tokenize:_i,partial:!0},sr={tokenize:Ei,partial:!0},or={tokenize:Ri,partial:!0},cr={tokenize:Li,partial:!0},Mi={tokenize:Di,partial:!0},ur={name:"wwwAutolink",tokenize:Ni,previous:dr},lr={name:"protocolAutolink",tokenize:Pi,previous:fr},re={name:"emailAutolink",tokenize:Ai,previous:hr},Y={};function Ii(){return{text:Y}}let ne=48;for(;ne<123;)Y[ne]=re,ne++,ne===58?ne=65:ne===91&&(ne=97);Y[43]=re;Y[45]=re;Y[46]=re;Y[95]=re;Y[72]=[re,lr];Y[104]=[re,lr];Y[87]=[re,ur];Y[119]=[re,ur];function Ai(e,t,r){const a=this;let n,s;return i;function i(d){return!Ge(d)||!hr.call(a,a.previous)||rt(a.events)?r(d):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(d))}function c(d){return Ge(d)?(e.consume(d),c):d===64?(e.consume(d),o):r(d)}function o(d){return d===46?e.check(Mi,m,l)(d):d===45||d===95||Ze(d)?(s=!0,e.consume(d),o):m(d)}function l(d){return e.consume(d),n=!0,o}function m(d){return s&&n&&be(a.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(d)):r(d)}}function Ni(e,t,r){const a=this;return n;function n(i){return i!==87&&i!==119||!dr.call(a,a.previous)||rt(a.events)?r(i):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(Si,e.attempt(sr,e.attempt(or,s),r),r)(i))}function s(i){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(i)}}function Pi(e,t,r){const a=this;let n="",s=!1;return i;function i(d){return(d===72||d===104)&&fr.call(a,a.previous)&&!rt(a.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),n+=String.fromCodePoint(d),e.consume(d),c):r(d)}function c(d){if(be(d)&&n.length<5)return n+=String.fromCodePoint(d),e.consume(d),c;if(d===58){const h=n.toLowerCase();if(h==="http"||h==="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||La(d)||W(d)||ie(d)||Ne(d)?r(d):e.attempt(sr,e.attempt(or,m),r)(d)}function m(d){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(d)}}function _i(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 Ei(e,t,r){let a,n,s;return i;function i(l){return l===46||l===95?e.check(cr,o,c)(l):l===null||W(l)||ie(l)||l!==45&&Ne(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 Ri(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(cr,t,s)(i):i===null||W(i)||ie(i)?t(i):(e.consume(i),n)}function s(i){return i===41&&a++,e.consume(i),n}}function Li(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||W(c)||ie(c)?t(c):r(c)}function n(c){return c===null||c===40||c===91||W(c)||ie(c)?t(c):a(c)}function s(c){return be(c)?i(c):r(c)}function i(c){return c===59?(e.consume(c),a):be(c)?(e.consume(c),i):r(c)}}function Di(e,t,r){return a;function a(s){return e.consume(s),n}function n(s){return Ze(s)?r(s):t(s)}}function dr(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||W(e)}function fr(e){return!be(e)}function hr(e){return!(e===47||Ge(e))}function Ge(e){return e===43||e===45||e===46||e===95||Ze(e)}function rt(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 Fi(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 te(e,t,r,a){const n=a?a-1:Number.POSITIVE_INFINITY;let s=0;return i;function i(o){return ee(o)?(e.enter(r),c(o)):t(o)}function c(o){return ee(o)&&s++<n?(e.consume(o),c):(e.exit(r),t(o))}}const Ui={partial:!0,tokenize:zi};function zi(e,t,r){return a;function a(s){return ee(s)?te(e,n,"linePrefix")(s):n(s)}function n(s){return s===null||he(s)?t(s):r(s)}}const $i={tokenize:Qi,partial:!0};function Oi(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Wi,continuation:{tokenize:Hi},exit:Ki}},text:{91:{name:"gfmFootnoteCall",tokenize:Vi},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Bi,resolveTo:qi}}}}function Bi(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=ke(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 qi(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 Vi(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||W(d))return r(d);if(d===93){e.exit("chunkString");const h=e.exit("gfmFootnoteCallString");return n.includes(ke(a.sliceSerialize(h)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(d)}return W(d)||(i=!0),s++,e.consume(d),d===92?m:l}function m(d){return d===91||d===92||d===93?(e.consume(d),s++,l):l(d)}}function Wi(e,t,r){const a=this,n=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let s,i=0,c;return o;function o(f){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),l}function l(f){return f===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",m):r(f)}function m(f){if(i>999||f===93&&!c||f===null||f===91||W(f))return r(f);if(f===93){e.exit("chunkString");const b=e.exit("gfmFootnoteDefinitionLabelString");return s=ke(a.sliceSerialize(b)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),h}return W(f)||(c=!0),i++,e.consume(f),f===92?d:m}function d(f){return f===91||f===92||f===93?(e.consume(f),i++,m):m(f)}function h(f){return f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),n.includes(s)||n.push(s),te(e,y,"gfmFootnoteDefinitionWhitespace")):r(f)}function y(f){return t(f)}}function Hi(e,t,r){return e.check(Ui,t,e.attempt($i,t,r))}function Ki(e){e.exit("gfmFootnoteDefinition")}function Qi(e,t,r){const a=this;return te(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 Gi(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 m={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)},h=[["enter",m,c],["enter",i[l][1],c],["exit",i[l][1],c],["enter",d,c]],y=c.parser.constructs.insideSpan.null;y&&Se(h,h.length,0,Fi(y,i.slice(l+1,o),c)),Se(h,h.length,0,[["exit",d,c],["enter",i[o][1],c],["exit",i[o][1],c],["exit",m,c]]),Se(i,l-1,o-l+3,h),o=l+h.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,m=this.events;let d=0;return h;function h(f){return l===126&&m[m.length-1][1].type!=="characterEscape"?o(f):(i.enter("strikethroughSequenceTemporary"),y(f))}function y(f){const b=Ie(l);if(f===126)return d>1?o(f):(i.consume(f),d++,y);if(d<2&&!r)return o(f);const w=i.exit("strikethroughSequenceTemporary"),g=Ie(f);return w._open=!g||g===2&&!!b,w._close=!b||b===2&&!!g,c(f)}}}class Yi{constructor(){this.map=[]}add(t,r,a){Ji(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 Ji(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 Xi(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 Zi(){return{flow:{null:{name:"table",tokenize:es,resolveAll:ts}}}}function es(e,t,r){const a=this;let n=0,s=0,i;return c;function c(p){let _=a.events.length-1;for(;_>-1;){const L=a.events[_][1].type;if(L==="lineEnding"||L==="linePrefix")_--;else break}const $=_>-1?a.events[_][1].type:null,G=$==="tableHead"||$==="tableRow"?A:o;return G===A&&a.parser.lazy[a.now().line]?r(p):G(p)}function o(p){return e.enter("tableHead"),e.enter("tableRow"),l(p)}function l(p){return p===124||(i=!0,s+=1),m(p)}function m(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"),y):r(p):ee(p)?te(e,m,"whitespace")(p):(s+=1,i&&(i=!1,n+=1),p===124?(e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),i=!0,m):(e.enter("data"),d(p)))}function d(p){return p===null||p===124||W(p)?(e.exit("data"),m(p)):(e.consume(p),p===92?h:d)}function h(p){return p===92||p===124?(e.consume(p),d):d(p)}function y(p){return a.interrupt=!1,a.parser.lazy[a.now().line]?r(p):(e.enter("tableDelimiterRow"),i=!1,ee(p)?te(e,f,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(p):f(p))}function f(p){return p===45||p===58?w(p):p===124?(i=!0,e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),b):P(p)}function b(p){return ee(p)?te(e,w,"whitespace")(p):w(p)}function w(p){return p===58?(s+=1,i=!0,e.enter("tableDelimiterMarker"),e.consume(p),e.exit("tableDelimiterMarker"),g):p===45?(s+=1,g(p)):p===null||he(p)?S(p):P(p)}function g(p){return p===45?(e.enter("tableDelimiterFiller"),k(p)):P(p)}function k(p){return p===45?(e.consume(p),k):p===58?(i=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(p),e.exit("tableDelimiterMarker"),C):(e.exit("tableDelimiterFiller"),C(p))}function C(p){return ee(p)?te(e,S,"whitespace")(p):S(p)}function S(p){return p===124?f(p):p===null||he(p)?!i||n!==s?P(p):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(p)):P(p)}function P(p){return r(p)}function A(p){return e.enter("tableRow"),z(p)}function z(p){return p===124?(e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),z):p===null||he(p)?(e.exit("tableRow"),t(p)):ee(p)?te(e,z,"whitespace")(p):(e.enter("data"),F(p))}function F(p){return p===null||p===124||W(p)?(e.exit("data"),z(p)):(e.consume(p),p===92?Q:F)}function Q(p){return p===92||p===124?(e.consume(p),F):F(p)}}function ts(e,t){let r=-1,a=!0,n=0,s=[0,0,0,0],i=[0,0,0,0],c=!1,o=0,l,m,d;const h=new Yi;for(;++r<e.length;){const y=e[r],f=y[1];y[0]==="enter"?f.type==="tableHead"?(c=!1,o!==0&&(vt(h,t,o,l,m),m=void 0,o=0),l={type:"table",start:Object.assign({},f.start),end:Object.assign({},f.end)},h.add(r,0,[["enter",l,t]])):f.type==="tableRow"||f.type==="tableDelimiterRow"?(a=!0,d=void 0,s=[0,0,0,0],i=[0,r+1,0,0],c&&(c=!1,m={type:"tableBody",start:Object.assign({},f.start),end:Object.assign({},f.end)},h.add(r,0,[["enter",m,t]])),n=f.type==="tableDelimiterRow"?2:m?3:1):n&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")?(a=!1,i[2]===0&&(s[1]!==0&&(i[0]=i[1],d=je(h,t,s,n,void 0,d),s=[0,0,0,0]),i[2]=r)):f.type==="tableCellDivider"&&(a?a=!1:(s[1]!==0&&(i[0]=i[1],d=je(h,t,s,n,void 0,d)),s=i,i=[s[1],r,0,0])):f.type==="tableHead"?(c=!0,o=r):f.type==="tableRow"||f.type==="tableDelimiterRow"?(o=r,s[1]!==0?(i[0]=i[1],d=je(h,t,s,n,r,d)):i[1]!==0&&(d=je(h,t,i,n,r,d)),n=0):n&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")&&(i[3]=r)}for(o!==0&&vt(h,t,o,l,m),h.consume(t.events),r=-1;++r<t.events.length;){const y=t.events[r];y[0]==="enter"&&y[1].type==="table"&&(y[1]._align=Xi(t.events,r))}return e}function je(e,t,r,a,n,s){const i=a===1?"tableHeader":a===2?"tableDelimiter":"tableData",c="tableContent";r[0]!==0&&(s.end=Object.assign({},de(t.events,r[0])),e.add(r[0],0,[["exit",s,t]]));const o=de(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=de(t.events,r[2]),m=de(t.events,r[3]),d={type:c,start:Object.assign({},l),end:Object.assign({},m)};if(e.add(r[2],0,[["enter",d,t]]),a!==2){const h=t.events[r[2]],y=t.events[r[3]];if(h[1].end=Object.assign({},y[1].end),h[1].type="chunkText",h[1].contentType="text",r[3]>r[2]+1){const f=r[2]+1,b=r[3]-r[2]-1;e.add(f,b,[])}}e.add(r[3]+1,0,[["exit",d,t]])}return n!==void 0&&(s.end=Object.assign({},de(t.events,n)),e.add(n,0,[["exit",s,t]]),s=void 0),s}function vt(e,t,r,a,n){const s=[],i=de(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 de(e,t){const r=e[t],a=r[0]==="enter"?"start":"end";return r[1][a]}const rs={name:"tasklistCheck",tokenize:ns};function as(){return{text:{91:rs}}}function ns(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 W(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):ee(o)?e.check({tokenize:is},t,r)(o):r(o)}}function is(e,t,r){return te(e,a,"whitespace");function a(n){return n===null?r(n):t(n)}}function ss(e){return vi([Ii(),Oi(),Gi(e),Zi(),as()])}const os={};function cs(e){const t=this,r=e||os,a=t.data(),n=a.micromarkExtensions||(a.micromarkExtensions=[]),s=a.fromMarkdownExtensions||(a.fromMarkdownExtensions=[]),i=a.toMarkdownExtensions||(a.toMarkdownExtensions=[]);n.push(ss(r)),s.push(ki()),i.push(Ci(r))}function O(...e){return e.filter(Boolean).join(" ")}const us=({content:e})=>u.jsx(Ve.MarkdownTextPrimitive,{remarkPlugins:[cs],className:"cuadra-aui-md",components:fs,children:e}),at=x.memo(us),ls=({language:e,code:t})=>{const{isCopied:r,copyToClipboard:a}=ds(),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(zr,{className:"cuadra-h-4 cuadra-w-4"}),r&&u.jsx(We,{className:"cuadra-h-4 cuadra-w-4"})]})]})},ds=({copiedDuration:e=3e3}={})=>{const[t,r]=x.useState(!1);return{isCopied:t,copyToClipboard:n=>{n&&navigator.clipboard.writeText(n).then(()=>{r(!0),setTimeout(()=>r(!1),e)})}}},fs=Ve.unstable_memoizeMarkdownComponents({h1:({className:e,...t})=>u.jsx("h1",{className:O("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:O("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:O("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:O("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:O("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:O("cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand",e),...t}),p:({className:e,...t})=>u.jsx("p",{className:O("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:O("cuadra-text-primary cuadra-font-medium cuadra-underline cuadra-underline-offset-4 font-brand",e),...t}),blockquote:({className:e,...t})=>u.jsx("blockquote",{className:O("cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand",e),...t}),ul:({className:e,...t})=>u.jsx("ul",{className:O("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:O("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:O("cuadra-my-5 cuadra-border-b",e),...t}),table:({className:e,...t})=>u.jsx("table",{className:O("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:O("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:O("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:O("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:O("[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand",e),...t}),pre:({className:e,...t})=>u.jsx("pre",{className:O("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=Ve.useIsMarkdownCodeBlock();return u.jsx("code",{className:O(!a&&"cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand",t),...r})},CodeHeader:ls});function nt({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 hs(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 mr({sources:e,maxVisible:t=3}){if(!e||e.length===0)return null;const r=hs(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(It,{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(ps,{source:s},s.sourceId||i)),n>0&&u.jsxs(nt,{variant:"subtle",children:["+",n," more"]})]})]})}function ms(e){switch(e.split(".").pop()?.toLowerCase()){case"csv":case"xlsx":case"xls":return Vr;case"md":case"txt":return Kr;default:return It}}function ps({source:e}){const{filename:t,score:r}=e,a=ms(t);return u.jsxs(nt,{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 gs=x.forwardRef(function({welcomeTitle:t="What should we work on?",welcomeSubtitle:r,extraTopPadding:a,suggestions:n,inputPlaceholder:s="Reply...",enableAttachments:i=!1,preMadeResponseDelay:c=1e3,streamingSpeed:o=50,safeArea:l=!1,composerBorder:m=!1,models:d,selectedModelId:h,onModelChange:y,showChatHeader:f=!1},b){const w=j.useThreadRuntime(),g=j.useAui(),[k,C]=x.useState(!1),[S,P]=x.useState(null),[A,z]=x.useState(!1),F=x.useSyncExternalStore(fe.subscribe,fe.getSnapshot);x.useEffect(()=>{if(F){const M=setTimeout(()=>fe.clear(),4e3);return()=>clearTimeout(M)}},[F]);const p=j.useThread(M=>{const N=M.messages;return!N||N.length===0})&&!k,_=j.useAssistantRuntime(),$=x.useRef(_);$.current=_;const G=x.useRef(h);x.useEffect(()=>{const M=G.current;if(G.current=h,M&&h&&M!==h){const N=setTimeout(()=>{try{$.current.switchToNewThread()}catch{}},50);return()=>clearTimeout(N)}},[h]);const L=x.useCallback((M,N,v)=>{if(!A)try{const T=v?.streamingSpeed??o,R=v?.delay??c;zt(M,N,T,R),g.composer().setText(M),setTimeout(()=>{g.composer().send()},10)}catch{}},[A,o,c,g]),K=x.useCallback(M=>{try{g.composer().setText(M),setTimeout(()=>{g.composer().send()},10)}catch{}},[g]),ae=x.useCallback(async M=>{if(!(A||!w))try{if(M.response){const N=M.responseDelay??c;await L(M.prompt,M.response,{delay:N,streamingSpeed:o})}else K(M.prompt)}catch{}},[w,A,c,o,L,K]),se=x.useCallback(async()=>{try{const N=window.__cuadraThreadListRuntime?.threadList;N?.switchToNewThread&&await N.switchToNewThread()}catch{}},[]);return x.useImperativeHandle(b,()=>({sendMessage:K,sendPreMadeQA:L,clearChat:se}),[K,L,se]),x.useEffect(()=>{if(!w){C(!1);return}try{const M=w?.store;if(!M){C(!1);return}const N=M.subscribe?.(T=>{const R=T?.threadId,U=T?.messages||[],q=T?.isLoadingHistory||!1,I=U.length;R&&R!==S&&P(R),C(q&&I===0)}),v=M.getState?.();if(v){const T=v?.threadId,R=v?.messages||[],U=v?.isLoadingHistory||!1,q=R.length;T&&T!==S&&P(T),C(U&&q===0)}return()=>{N&&N()}}catch{C(!1)}},[w,S]),u.jsxs(j.ThreadPrimitive.Root,{className:"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full cuadra-relative",children:[(f||d&&d.length>0)&&u.jsxs("div",{className:"cuadra-relative cuadra-flex cuadra-items-center cuadra-justify-center cuadra-px-3 cuadra-py-2 cuadra-min-h-[48px]",children:[f&&u.jsx("div",{className:"cuadra-absolute cuadra-right-3 md:cuadra-right-auto md:cuadra-left-3 cuadra-top-0 cuadra-bottom-0 cuadra-flex cuadra-items-center",children:u.jsx(vs,{})}),d&&d.length>0&&u.jsx(Cs,{models:d,selectedModelId:h,onModelChange:y})]}),u.jsxs(j.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(ra,{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(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||(f||d&&d.length>0?"0.5rem":"2rem")},children:k?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(j.ThreadPrimitive.Empty,{children:u.jsx(xs,{title:t,subtitle:r})}),u.jsx(j.ThreadPrimitive.Messages,{components:{UserMessage:ys,AssistantMessage:ks}})]})}),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:[F&&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(Fr,{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:F.message}),u.jsx("button",{type:"button",onClick:()=>fe.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(Me,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})]}),i&&u.jsx(j.ComposerPrimitive.Attachments,{components:{Attachment:()=>{const M=j.useAuiState(({attachment:N})=>N);return M?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:M.name||"Attachment"}),u.jsx(j.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(Me,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})})]}):null}}}),u.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:[u.jsx(j.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(j.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(He,{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.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:u.jsx(j.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(_r,{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((M,N)=>u.jsx("button",{type:"button",onClick:()=>ae(M),disabled:A,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:M.prompt},`suggestion-${N}`))})]})]})});function xs({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-2xl md: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}),t&&u.jsx("p",{className:"cuadra-text-sm md:cuadra-text-base cuadra-text-muted-foreground cuadra-mt-2 md:cuadra-mt-3 cuadra-max-w-lg cuadra-whitespace-pre-line",children:t})]})}function ys(){return u.jsx(j.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(j.MessagePrimitive.Attachments,{components:{Attachment:()=>{const e=j.useAuiState(({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(j.MessagePrimitive.Parts,{components:{Text:({text:e})=>u.jsx(at,{content:e||""})}})})]})})}function bs({text:e}){const[t,r]=x.useState(!1),a=j.useAuiState(({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(Ye,{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(at,{content:e})})})]}):null}function ws(){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 ks(){const e=j.useAuiState(({message:i})=>i?.status?.type==="running"),t=j.useAuiState(({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=x.useRef(!1),[a,n]=x.useState(null);x.useEffect(()=>{if(e&&t&&!r.current){const i=Z.getCurrentMessageId();i&&(r.current=!0,n(i))}},[e,t]);const s=x.useSyncExternalStore(i=>Z.subscribe(i),()=>{if(a){const i=Z.getForMessage(a);return i.sources?.length?i.sources:null}if(e&&t){const i=Z.getCurrentMessageId();if(i){const c=Z.getForMessage(i);return c.sources?.length?c.sources:null}}return null},()=>null);return u.jsx(j.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(j.MessagePrimitive.Parts,{components:{Text:({text:i})=>u.jsx(at,{content:i||""}),Reasoning:({text:i})=>u.jsx(bs,{text:i||""})}}),e&&!t&&u.jsx(ws,{}),s&&s.length>0&&u.jsx(mr,{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 Cs({models:e,selectedModelId:t,onModelChange:r}){const[a,n]=x.useState(!1),s=e.find(c=>c.id===t)||e[0];if(!s)return null;const i=c=>{n(!1),c!==t&&r?.(c)};return u.jsxs("div",{className:"cuadra-relative",children:[u.jsxs("button",{type:"button",onClick:()=>n(!a),className:"cuadra-flex cuadra-items-center cuadra-gap-1.5 cuadra-px-2.5 cuadra-py-1.5 cuadra-rounded-lg cuadra-text-sm md:cuadra-text-base cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-colors font-brand",children:[u.jsx("span",{children:s.name}),u.jsx(Ye,{className:"cuadra-h-3.5 cuadra-w-3.5"})]}),a&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"cuadra-hidden md:cuadra-block cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:()=>n(!1)}),u.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:[u.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-end cuadra-px-4 cuadra-py-3 cuadra-min-h-[48px]",children:u.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:u.jsx(Me,{className:"cuadra-h-5 cuadra-w-5"})})}),u.jsx("div",{className:"cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto cuadra-py-1",children:e.map(c=>u.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:()=>i(c.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:c.name}),c.supportsReasoning&&u.jsx(Te,{label:"Reasoning",children:u.jsx(ut,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})}),c.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"})})]}),c.description&&u.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground",children:c.description})]}),c.id===t&&u.jsx(We,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-primary cuadra-flex-shrink-0"})]},c.id))})]}),u.jsx("div",{className:"cuadra-hidden md:cuadra-block cuadra-absolute cuadra-top-full cuadra-left-1/2 cuadra--translate-x-1/2 cuadra-mt-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(c=>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:()=>i(c.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:c.name}),c.supportsReasoning&&u.jsx(Te,{label:"Reasoning",children:u.jsx(ut,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})}),c.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"})})]}),c.description&&u.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground",children:c.description})]}),c.id===t&&u.jsx(We,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-primary cuadra-flex-shrink-0"})]},c.id))})]})]})}function vs(){const e=j.useAuiState(({threadListItem:n})=>n?.title??null),[t,r]=x.useState(!1),a=e||"Untitled chat";return u.jsxs("div",{className:"cuadra-relative",children:[u.jsxs("button",{type:"button",onClick:()=>r(!t),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:[u.jsx("span",{className:"cuadra-font-medium cuadra-truncate cuadra-max-w-[200px]",children:a}),u.jsx(Ye,{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":""}`})]}),u.jsx("button",{type:"button",onClick:()=>r(!t),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:u.jsx(Yr,{className:"cuadra-h-5 cuadra-w-5"})}),t&&u.jsx(js,{onClose:()=>r(!1)})]})}function js({onClose:e}){return u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"cuadra-hidden md:cuadra-block cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:e}),u.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:[u.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-end cuadra-px-4 cuadra-py-3 cuadra-min-h-[48px]",children:u.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:u.jsx(Me,{className:"cuadra-h-5 cuadra-w-5"})})}),u.jsxs(j.ThreadListPrimitive.Root,{className:"cuadra-flex cuadra-flex-col cuadra-flex-1 cuadra-min-h-0",children:[u.jsx("div",{className:"cuadra-px-3 cuadra-py-2",children:u.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:[u.jsx(He,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"New Chat"]})}),u.jsx(jt,{onSelect:e,fullHeight:!0})]})]}),u.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:u.jsxs(j.ThreadListPrimitive.Root,{className:"cuadra-flex cuadra-flex-col",children:[u.jsx("div",{className:"cuadra-px-2 cuadra-py-1.5",children:u.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:[u.jsx(He,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"New Chat"]})}),u.jsx(jt,{onSelect:e})]})})]})}function jt({onSelect:e,fullHeight:t}){const r=j.useAuiState(({threads:s})=>s?.threadIds??[]),a=j.useAuiState(({threads:s})=>s?.newThreadId);return r.some(s=>s!==a)?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 scrollbar-thin ${t?"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:t?void 0:{maxHeight:"340px"},children:u.jsx(j.ThreadListPrimitive.Items,{components:{ThreadListItem:s=>u.jsx(Ts,{...s,onSelect:e,fullHeight:t})}})})]}):null}function Ts({onSelect:e,fullHeight:t}){const r=j.useThreadListItem(),a=j.useThreadListItemRuntime(),n=j.useAssistantRuntime(),s=j.useThread(g=>g.threadId),i=r?.id===s,[c,o]=x.useState(!1),[l,m]=x.useState(!1),[d,h]=x.useState(r?.title||""),[y,f]=x.useState(!1),b=async()=>{if(!r?.remoteId||!d||d===r.title){m(!1);return}try{f(!0),await a.rename(d)}catch{}finally{f(!1),m(!1)}},w=async g=>{g.stopPropagation();try{await a.delete(),i&&await n.switchToNewThread()}catch(k){console.error("[CuadraChat] Failed to delete thread:",k)}};return x.useEffect(()=>{r?.title&&!l&&h(r.title)},[r?.title,l]),r?t?u.jsxs(j.ThreadListItemPrimitive.Root,{className:`cuadra-relative cuadra-flex cuadra-items-center cuadra-rounded-xl cuadra-transition-colors cuadra-cursor-pointer ${i?"cuadra-bg-primary/10 cuadra-ring-1 cuadra-ring-primary/20":"cuadra-bg-muted/40"}`,children:[l?u.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: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:d,onChange:g=>h(g.target.value),onKeyDown:g=>{g.stopPropagation(),g.key==="Enter"&&b(),g.key==="Escape"&&(m(!1),h(r.title||""))},onBlur:()=>void b(),disabled:y,autoFocus:!0})}):u.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:u.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground cuadra-truncate cuadra-block cuadra-text-left font-brand",children:r.title||"Chat"})}),!l&&u.jsx(Ss,{onRename:()=>{m(!0),h(r.title||"Chat")},onDelete:w})]}):u.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 ${i?"cuadra-bg-muted":"hover:cuadra-bg-muted/60"}`,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),children:[l?u.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: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:d,onChange:g=>h(g.target.value),onKeyDown:g=>{g.stopPropagation(),g.key==="Enter"&&b(),g.key==="Escape"&&(m(!1),h(r.title||""))},onBlur:()=>void b(),disabled:y,autoFocus:!0})}):u.jsx(j.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:r.title||"Chat"})}),(c||i)&&!l&&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:g=>{g.stopPropagation(),m(!0),h(r.title||"Chat")},title:"Rename",children:u.jsx(Pt,{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(_t,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-destructive"})})]})]}):null}function Ss({onRename:e,onDelete:t}){const[r,a]=x.useState(!1);return u.jsxs("div",{className:"cuadra-relative cuadra-flex-shrink-0 cuadra-mr-2",children:[u.jsx("button",{type:"button",className:"cuadra-p-2 cuadra-rounded-lg cuadra-text-muted-foreground hover:cuadra-bg-background/60 cuadra-transition-colors",onClick:n=>{n.stopPropagation(),a(!r)},children:u.jsx(Or,{className:"cuadra-h-4 cuadra-w-4"})}),r&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-50",onClick:n=>{n.stopPropagation(),a(!1)}}),u.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:[u.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:n=>{n.stopPropagation(),a(!1),e()},children:[u.jsx(Pt,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"Rename"]}),u.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:n=>{n.stopPropagation(),a(!1),t(n)},children:[u.jsx(_t,{className:"cuadra-h-4 cuadra-w-4"}),"Delete"]})]})]})]})}const Be=({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}),Ms=x.createContext(void 0),qe=({children:e,value:t})=>u.jsx(Ms.Provider,{value:t,children:e});function Is(){x.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:me&&me.tagName.toUpperCase()==="SCRIPT"&&me.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 As=x.forwardRef(function({config:t},r){Is();const a=x.useRef(null),n=x.useRef(!1),{baseUrl:s,proxyUrl:i,sessionToken:c,mode:o="multiChat",modelMode:l="fixed",modelId:m,onModelChange:d,ephemeral:h=!1,systemPrompt:y,enableReasoning:f=!1,initialThreadId:b,welcomeTitle:w,welcomeSubtitle:g,extraTopPadding:k,suggestions:C,inputPlaceholder:S,preMadeResponseDelay:P=1e3,streamingSpeed:A=50,initialMessage:z,initialPreMadeQA:F,theme:Q="system",onError:p,onChatCreated:_,onUserMessage:$,onThreadIdUpdate:G,enableAttachments:L=!1,supportsVision:K,onBeforeRequest:ae,mockResponseOnBlocked:se}=t;x.useImperativeHandle(r,()=>({sendMessage:E=>{a.current?.sendMessage(E)},sendPreMadeQA:(E,ue,Cr)=>{a.current?.sendPreMadeQA(E,ue,Cr)},clearChat:()=>{a.current?.clearChat()}}),[]),x.useEffect(()=>{if(n.current)return;const E=setTimeout(()=>{F?(n.current=!0,a.current?.sendPreMadeQA(F.question,F.answer,{delay:P,streamingSpeed:A})):z&&(n.current=!0,a.current?.sendMessage(z))},500);return()=>clearTimeout(E)},[z,F,P,A]);const M=i||s||"",N=!!i,v=x.useMemo(()=>new Rt(M,c||void 0,N),[M,c,N]),[T,R]=x.useState(null),[U,q]=x.useState(!1),[I,V]=x.useState(null),[oe,ce]=x.useState(!1);x.useEffect(()=>{o==="multiChat"&&ce(!0)},[o]);const J=x.useCallback(async()=>{if(l==="selector"){q(!0),V(null);try{const E=await v.listModels();R(E)}catch(E){V(E instanceof Error?E:new Error("Failed to load models"))}finally{q(!1)}}},[v,l]);x.useEffect(()=>{l==="selector"&&J()},[l,J]),x.useEffect(()=>(typeof window<"u"&&(window.__cuadraUIKitRefetchModels=J),()=>{typeof window<"u"&&delete window.__cuadraUIKitRefetchModels}),[J]);const[H,X]=x.useState(l==="fixed"&&m||null),Re=x.useRef(H),Ce=x.useCallback(E=>{X(E),Re.current=E,d?.(E)},[d,o]);x.useEffect(()=>{if(l==="selector"&&T?.items&&T.items.length>0&&!H){const E=T.items[0];if(E?.id){const ue=E.id;X(ue),d?.(ue)}}},[l,T?.items,H,d]);const br=l==="fixed"?!!m:!!H,wr=x.useMemo(()=>K!==void 0?K:l==="selector"&&H&&T?.items?T.items.find(ue=>ue.id===H)?.supportsVision??!0:!0,[K,l,H,T?.items]),Le=x.useMemo(()=>(T?.items||[]).filter(E=>E?.id&&E?.displayName).map(E=>({id:E.id,name:E.displayName,supportsVision:E.supportsVision??!1,supportsReasoning:E.supportsReasoning??!1})),[T]),De=x.useMemo(()=>({currentModelId:H||"",models:Le,modelsLoading:U,modelsError:I,onModelChange:Ce,refetchModels:J}),[H,Le,U,I,Ce,J]),kr=x.useCallback(()=>{o==="multiChat"&&ce(!1)},[o]);return l==="selector"&&U||o==="multiChat"&&oe?u.jsx(qe,{value:De,children:u.jsx(Be,{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"&&!br&&I?u.jsx(qe,{value:De,children:u.jsx(Be,{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(qe,{value:De,children:u.jsx(Na,{baseUrl:N?M:s||M,sessionToken:c,isProxyMode:N,mode:o,modelMode:l,modelId:H||m||void 0,onModelChange:Ce,ephemeral:h,systemPrompt:y,enableReasoning:f,initialThreadId:b,enableAttachments:L,supportsVision:wr,onError:p,onChatCreated:_,onUserMessage:$,onThreadIdUpdate:G,onBeforeRequest:ae,mockResponseOnBlocked:se,onChatsLoaded:kr,children:u.jsx(Be,{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(gs,{ref:a,welcomeTitle:w,welcomeSubtitle:g,extraTopPadding:k,suggestions:C,inputPlaceholder:S,enableAttachments:L,preMadeResponseDelay:P,streamingSpeed:A,safeArea:t.safeArea,showChatHeader:o==="multiChat",models:l==="selector"?Le:void 0,selectedModelId:H||void 0,onModelChange:l==="selector"?Ce:void 0,theme:Q})})})})})})})})});function pr(e,t=":root"){if(typeof document>"u")return;const r=document.documentElement,a=[];if(e.light){Ps(e.light,r);const n=Tt(e.light);n&&a.push(`.cuadra-uikit { ${n} }`)}if(e.dark){const n=Tt(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 Ns={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 gr(e){const t=Ns[e];return t?`--cuadra-${t}`:`--cuadra-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function Ps(e,t){Object.entries(e).forEach(([r,a])=>{if(a){const n=gr(r);t.style.setProperty(n,a)}})}function Tt(e){return Object.entries(e).map(([t,r])=>r?`${gr(t)}: ${r};`:"").filter(Boolean).join(" ")}function _s(){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 Es({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 it extends x.Component{constructor(r){super(r);D(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(Es,{error:a,onReset:this.reset})}return this.props.children}}function Rs(e,t){const r=a=>u.jsx(it,{...t,children:u.jsx(e,{...a})});return r.displayName=`withErrorBoundary(${e.displayName||e.name||"Component"})`,r}const ge=x.createContext(null);ge.displayName="CuadraChatContext";function Ls(){const e=x.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 Ds(){const e=x.useContext(ge);return e===null?null:{controls:e.controls,isReady:e.controls!==null}}function Fs({children:e}){const[t,r]=x.useState(null),a=x.useCallback(i=>{r(i)},[]),n=x.useCallback(()=>{r(null)},[]),s=x.useMemo(()=>({controls:t,registerControls:a,unregisterControls:n}),[t,a,n]);return u.jsx(ge.Provider,{value:s,children:e})}function xr(e){return"connection"in e&&typeof e.connection=="object"}function yr(e){return xr(e)?Us(e):zs(e)}function Us(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 zs(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}}let St=!1;const $s=x.forwardRef(function({config:t},r){const a=x.useRef(null),n=x.useContext(ge);x.useEffect(()=>{t.ui.customTheme&&pr(t.ui.customTheme)},[t.ui.customTheme]),x.useEffect(()=>{if(t.ui.primaryColor&&typeof document<"u"){const c=document.documentElement,o=l=>{const m=l.replace("#",""),d=parseInt(m.slice(0,2),16)/255,h=parseInt(m.slice(2,4),16)/255,y=parseInt(m.slice(4,6),16)/255,f=Math.max(d,h,y),b=Math.min(d,h,y);let w=0,g=0;const k=(f+b)/2;if(f!==b){const C=f-b;switch(g=k>.5?C/(2-f-b):C/(f+b),f){case d:w=((h-y)/C+(h<y?6:0))/6;break;case h:w=((y-d)/C+2)/6;break;case y:w=((d-h)/C+4)/6;break}}return`${Math.round(w*360)} ${Math.round(g*100)}% ${Math.round(k*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=x.useMemo(()=>({sendMessage:c=>a.current?.sendMessage(c),sendPreMadeQA:(c,o,l)=>a.current?.sendPreMadeQA(c,o,l),clearChat:()=>a.current?.clearChat()}),[]);x.useImperativeHandle(r,()=>s,[]),x.useEffect(()=>{if(n)return n.registerControls(s),()=>n.unregisterControls()},[n,s]),x.useEffect(()=>(typeof window<"u"&&(process.env.NODE_ENV==="development"&&!St&&(St=!0,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(As,{ref:a,config:i})}),Os=x.forwardRef(function(t,r){const a=yr(t),n=a.errorFallback;return u.jsx(it,{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($s,{ref:r,config:a})})});exports.AttachmentValidationError=le;exports.Badge=nt;exports.CuadraChat=Os;exports.CuadraChatContext=ge;exports.CuadraChatProvider=Fs;exports.CuadraErrorBoundary=it;exports.SourceCitations=mr;exports.applyTheme=pr;exports.createAttachmentAdapter=Xe;exports.escapeHtml=ua;exports.generateSecureUUID=Et;exports.isV2Props=xr;exports.isValidUrl=sa;exports.normalizeCuadraChatProps=yr;exports.removeTheme=_s;exports.sanitizeSystemPrompt=ia;exports.streamingMetadataStore=Z;exports.useCuadraChat=Ls;exports.useCuadraChatOptional=Ds;exports.validateBaseUrl=oa;exports.withErrorBoundary=Rs;
23
23
  //# sourceMappingURL=index.cjs.map