@cuadra-ai/uikit 0.4.9 → 0.4.10
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 +13 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +559 -549
- package/dist/index.mjs.map +1 -1
- package/dist/uikit.css +1 -1
- package/dist/utils/applyTheme.d.ts +8 -4
- package/dist/utils/applyTheme.d.ts.map +1 -1
- package/dist/widget/cuadra-uikit.css +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,22 +1,23 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var br=Object.defineProperty;var wr=(e,r,t)=>r in e?br(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var z=(e,r,t)=>wr(e,typeof r!="symbol"?r+"":r,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("react/jsx-runtime"),y=require("react"),T=require("@assistant-ui/react");require("@assistant-ui/react-markdown/styles/dot.css");const qe=require("@assistant-ui/react-markdown");var fe=typeof document<"u"?document.currentScript:null;let xe=!1,it=!1;function st(){if(it||(it=!0,typeof document>"u"||typeof window>"u"))return;const e=document.querySelector("link[data-cuadra-uikit-styles]"),r=document.querySelector("style[data-cuadra-uikit-styles]");if(e||r){xe=!0;return}try{const t=document.createElement("div");t.className="cuadra-flex",t.style.visibility="hidden",t.style.position="absolute",t.style.pointerEvents="none",document.body.appendChild(t);const a=window.getComputedStyle(t).display==="flex";if(document.body.removeChild(t),a){xe=!0;return}}catch{}kr()}function kr(){if(xe)return;const e=document.createElement("link");e.setAttribute("data-cuadra-uikit-styles","true"),e.rel="stylesheet",e.type="text/css";try{const r=new URL(typeof document>"u"?require("url").pathToFileURL(__filename).href:fe&&fe.tagName.toUpperCase()==="SCRIPT"&&fe.src||new URL("index.cjs",document.baseURI).href),t=new URL("../dist/uikit.css",r);e.href=t.href}catch{e.href="/node_modules/@cuadra-ai/uikit/dist/uikit.css"}e.onload=()=>{xe=!0},e.onerror=()=>{const r=["/node_modules/@cuadra-ai/uikit/dist/uikit.css","https://unpkg.com/@cuadra-ai/uikit@latest/dist/uikit.css"];let t=0;const a=()=>{t<r.length&&(e.href=r[t++],e.onerror=a,e.onload=()=>{xe=!0})};a()},document.head.appendChild(e)}typeof document<"u"&&typeof window<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",st):st());const Cr=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),vr=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(r,t,a)=>a?a.toUpperCase():t.toLowerCase()),ot=e=>{const r=vr(e);return r.charAt(0).toUpperCase()+r.slice(1)},St=(...e)=>e.filter((r,t,a)=>!!r&&r.trim()!==""&&a.indexOf(r)===t).join(" ").trim(),Tr=e=>{for(const r in e)if(r.startsWith("aria-")||r==="role"||r==="title")return!0};var jr={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Sr=y.forwardRef(({color:e="currentColor",size:r=24,strokeWidth:t=2,absoluteStrokeWidth:a,className:i="",children:s,iconNode:n,...c},o)=>y.createElement("svg",{ref:o,...jr,width:r,height:r,stroke:e,strokeWidth:a?Number(t)*24/Number(r):t,className:St("lucide",i),...!s&&!Tr(c)&&{"aria-hidden":"true"},...c},[...n.map(([l,f])=>y.createElement(l,f)),...Array.isArray(s)?s:[s]]));const q=(e,r)=>{const t=y.forwardRef(({className:a,...i},s)=>y.createElement(Sr,{ref:s,iconNode:r,className:St(`lucide-${Cr(ot(e))}`,`lucide-${e}`,a),...i}));return t.displayName=ot(e),t};const Ir=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Mr=q("arrow-up",Ir);const Ar=[["path",{d:"M12 18V5",key:"adv99a"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4",key:"1e3is1"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5",key:"1gqd8o"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77",key:"iwvgf7"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464",key:"efp6ie"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517",key:"1gq6am"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464",key:"k1g0md"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77",key:"q97ue3"}]],ct=q("brain",Ar);const Nr=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],It=q("check",Nr);const _r=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Ke=q("chevron-down",_r);const Pr=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],Er=q("circle-alert",Pr);const Rr=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Lr=q("copy",Rr);const Dr=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],lt=q("eye",Dr);const Fr=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]],Ur=q("file-spreadsheet",Fr);const zr=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Mt=q("file-text",zr);const $r=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M11 18h2",key:"12mj7e"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M9 13v-.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 .5.5v.5",key:"qbrxap"}]],Or=q("file-type",$r);const Br=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],At=q("loader-circle",Br);const qr=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],Nt=q("paperclip",qr);const Vr=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],Wr=q("pencil",Vr);const Hr=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],_t=q("plus",Hr);const Kr=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Qr=q("trash-2",Kr);const Gr=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],Yr=q("upload",Gr);const Jr=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],ut=q("x",Jr),Xr=[/\[INST\]/gi,/\[\/INST\]/gi,/<<SYS>>/gi,/<<\/SYS>>/gi,/<\|.*?\|>/g,/<\|im_start\|>/gi,/<\|im_end\|>/gi,/\[HUMAN\]/gi,/\[ASSISTANT\]/gi,/^(system|user|assistant):\s*/gim];function Zr(e){if(!e||typeof e!="string")return"";let r=e;for(const t of Xr)r=r.replace(t,"");return r=r.replace(/\n{3,}/g,`
|
|
2
2
|
|
|
3
|
-
`).replace(/ {2,}/g," ").trim(),r}function
|
|
3
|
+
`).replace(/ {2,}/g," ").trim(),r}function ea(e){if(!e||typeof e!="string")return!1;try{const r=new URL(e);return["http:","https:"].includes(r.protocol)}catch{return!1}}function ta(e){if(!e)return{valid:!1,error:"URL is required"};if(typeof e!="string")return{valid:!1,error:"URL must be a string"};if(e.startsWith("/")||e.startsWith("./"))return{valid:!0};try{const r=new URL(e);return["http:","https:"].includes(r.protocol)?r.protocol==="http:"&&!ra(e)?{valid:!0,parsed:r,error:"Warning: Using HTTP for non-localhost URL. Consider using HTTPS."}:{valid:!0,parsed:r}:{valid:!1,error:`Invalid protocol "${r.protocol}". Only http and https are allowed.`}}catch{return{valid:!1,error:"Invalid URL format"}}}function ra(e){try{const r=new URL(e);return["localhost","127.0.0.1","[::1]"].includes(r.hostname)}catch{return!1}}function aa(e){if(!e||typeof e!="string")return"";const r={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};return e.replace(/[&<>"'/]/g,t=>r[t]||t)}function Pt(){if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&crypto.getRandomValues){const e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const r=Array.from(e,t=>t.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}return typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn("[CuadraUIKit] Using non-cryptographic fallback for UUID generation"),`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`}class Et{constructor(r,t,a=!1){z(this,"baseUrl");z(this,"sessionToken",null);z(this,"isProxyMode",!1);this.baseUrl=r.replace(/\/$/,""),this.isProxyMode=a,t&&(this.sessionToken=t)}setSessionToken(r){this.sessionToken=r}getUrl(r){if(this.isProxyMode){const t=`${this.baseUrl}${r.replace("/v1","")}`;return t.startsWith("/")||t.startsWith("./"),t}return`${this.baseUrl}${r}`}async createOrContinueChat(r,t){const a=this.getUrl("/v1/chats"),s={"Content-Type":"application/json",Accept:"text/event-stream","Accept-Encoding":"identity","Cache-Control":"no-cache","X-Accel-Buffering":"no","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(s.Authorization=`Bearer ${this.sessionToken}`);const n={...r,stream:!0},c=await fetch(a,{method:"POST",headers:s,body:JSON.stringify(n),signal:t,cache:"no-store"});if(!c.ok){const o=await c.json().catch(()=>({}));throw new Error(o.detail||o.message||`API error: ${c.status} ${c.statusText}`)}if(!c.body)throw new Error("Response body is null");return c.body}async getChat(r){const t=this.getUrl(`/v1/chats/${r}`),a={"Content-Type":"application/json"};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const i=await fetch(t,{method:"GET",headers:a});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${i.status} ${i.statusText}`)}return i.json()}async listChats(r){const t=this.getUrl("/v1/chats"),a=t.startsWith("/")||t.startsWith("./")?new URL(t,window.location.origin):new URL(t);r?.limit&&a.searchParams.set("limit",r.limit.toString()),r?.cursor&&a.searchParams.set("cursor",r.cursor),r?.["expand[]"]&&r["expand[]"].forEach(n=>{a.searchParams.append("expand[]",n)});const i={"Content-Type":"application/json"};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const s=await fetch(a.toString(),{method:"GET",headers:i});if(!s.ok){const n=await s.json().catch(()=>({}));throw new Error(n.detail||n.message||`API error: ${s.status} ${s.statusText}`)}return s.json()}generateIdempotencyKey(){return Pt()}async updateChat(r,t){const a=`/v1/chats/${r}`,i=this.getUrl(a),s=i.startsWith("/")||i.startsWith("./")?new URL(i,window.location.origin):new URL(i),c={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(c.Authorization=`Bearer ${this.sessionToken}`);const o=await fetch(s.toString(),{method:"PATCH",headers:c,body:JSON.stringify(t)});if(!o.ok){const f=await o.text();let d={};try{d=JSON.parse(f)}catch{d={detail:f}}throw new Error(d.detail||d.message||`API error: ${o.status} ${o.statusText}`)}if(o.status===204)return{};const l=await o.text();if(!l)return{};try{return JSON.parse(l)}catch{return{}}}async deleteChat(r){const t=`/v1/chats/${r}`,a=this.getUrl(t),i=a.startsWith("/")||a.startsWith("./")?new URL(a,window.location.origin):new URL(a),n={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const c=await fetch(i.toString(),{method:"DELETE",headers:n});if(!c.ok){const o=await c.json().catch(()=>({}));throw new Error(o.detail||o.message||`API error: ${c.status} ${c.statusText}`)}}async generateChatTitle(r,t){const a=`/v1/chats/${r}/title`,i=this.getUrl(a),s=i.startsWith("/")||i.startsWith("./")?new URL(i,window.location.origin):new URL(i),c={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(c.Authorization=`Bearer ${this.sessionToken}`);const o=await fetch(s.toString(),{method:"POST",headers:c,body:t?JSON.stringify(t):void 0});if(!o.ok){const l=await o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}return o.json()}async listModels(r){const t=this.getUrl("/v1/models"),a=t.startsWith("/")||t.startsWith("./")?new URL(t,window.location.origin):new URL(t);r?.limit&&a.searchParams.set("limit",r.limit.toString()),r?.cursor&&a.searchParams.set("cursor",r.cursor),r?.["expand[]"]&&r["expand[]"].forEach(n=>{a.searchParams.append("expand[]",n)});const i={"Content-Type":"application/json"};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const s=await fetch(a.toString(),{method:"GET",headers:i});if(!s.ok){const n=await s.json().catch(()=>({}));throw new Error(n.detail||n.message||`API error: ${s.status} ${s.statusText}`)}return s.json()}async getModel(r){const t=this.getUrl(`/v1/models/${r}`),a={"Content-Type":"application/json"};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const i=await fetch(t,{method:"GET",headers:a});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${i.status} ${i.statusText}`)}return i.json()}async uploadFile(r,t,a){const i=this.getUrl("/v1/files"),s=this.generateIdempotencyKey(),n=new FormData;n.append("file",r),t&&n.append("resource_type",t),a&&n.append("resource_id",a);const c={"Idempotency-Key":s};this.sessionToken&&(c.Authorization=`Bearer ${this.sessionToken}`);const o=await fetch(i,{method:"POST",headers:c,body:n});if(!o.ok){const l=await o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}return o.json()}}async function*na(e,r){const t=e.getReader(),a=new TextDecoder;let i="";try{for(;;){if(r?.aborted){t.cancel();break}const{done:s,value:n}=await t.read();if(s)break;i+=a.decode(n,{stream:!0});const c=i.split(`
|
|
4
4
|
|
|
5
|
-
`);i=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{t.releaseLock()}}function na(e){return e.map(r=>{let t="";if(typeof r.content=="string")t=r.content;else if(Array.isArray(r.content)){const a=r.content.find(i=>i.type==="text");a&&typeof a=="object"&&"text"in a&&(t=a.text)}return{role:r.role,content:t}})}function ia(e){return{id:e.id,role:e.role,content:[{type:"text",text:e.content}],createdAt:new Date(e.createdAt),metadata:{custom:{}},...e.role==="assistant"&&{status:{type:"complete",reason:"stop"},metadata:{unstable_state:null,unstable_annotations:[],unstable_data:[],steps:[],custom:{}}},...e.role==="user"&&{attachments:[]}}}var sa=function(){let e,r;const t=new Promise((a,i)=>{e=a,r=i});if(!e||!r)throw new Error("Failed to create promise");return{promise:t,resolve:e,reject:r}},oa=()=>{const e=[];let r=!1,t,a;const i=n=>{n.promise||(n.promise=n.reader.read().then(({done:c,value:o})=>{n.promise=void 0,c?(e.splice(e.indexOf(n),1),r&&e.length===0&&t.close()):t.enqueue(o),a?.resolve(),a=void 0}).catch(c=>{console.error(c),e.forEach(o=>{o.reader.cancel()}),e.length=0,t.error(c),a?.reject(c),a=void 0}))};return{readable:new ReadableStream({start(n){t=n},pull(){return a=sa(),e.forEach(n=>{i(n)}),a.promise},cancel(){e.forEach(n=>{n.reader.cancel()}),e.length=0}}),isSealed(){return r},seal(){r=!0,e.length===0&&t.close()},addStream(n){if(r)throw new Error("Cannot add streams after the run callback has settled.");const c={reader:n.getReader()};e.push(c),i(c)},enqueue(n){this.addStream(new ReadableStream({start(c){c.enqueue(n),c.close()}}))}}},dt=class{constructor(e){z(this,"_controller");z(this,"_isClosed",!1);this._controller=e}append(e){return this._controller.enqueue({type:"text-delta",path:[],textDelta:e}),this}close(){this._isClosed||(this._isClosed=!0,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}},Et=e=>new ReadableStream({start(r){return e.start?.(new dt(r))},pull(r){return e.pull?.(new dt(r))},cancel(r){return e.cancel?.(r)}}),ht=()=>{let e;return[Et({start(t){e=t}}),e]},ft=class{constructor(e){z(this,"_isClosed",!1);z(this,"_mergeTask");z(this,"_argsTextController");this._controller=e;const r=Et({start:a=>{this._argsTextController=a}});let t=!1;this._mergeTask=r.pipeTo(new WritableStream({write:a=>{switch(a.type){case"text-delta":t=!0,this._controller.enqueue(a);break;case"part-finish":t||this._controller.enqueue({type:"text-delta",textDelta:"{}",path:[]}),this._controller.enqueue({type:"tool-call-args-text-finish",path:[]});break;default:throw new Error(`Unexpected chunk type: ${a.type}`)}}}))}get argsText(){return this._argsTextController}async setResponse(e){this._argsTextController.close(),await Promise.resolve(),this._controller.enqueue({type:"result",path:[],...e.artifact!==void 0?{artifact:e.artifact}:{},result:e.result,isError:e.isError??!1})}async close(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),await this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}},ca=e=>new ReadableStream({start(r){return e.start?.(new ft(r))},pull(r){return e.pull?.(new ft(r))},cancel(r){return e.cancel?.(r)}}),la=()=>{let e;return[ca({start(t){e=t}}),e]},Rt=class{constructor(){z(this,"value",-1)}up(){return++this.value}},ua=class extends TransformStream{constructor(e){super({transform(r,t){t.enqueue({...r,path:[e,...r.path]})}})}};(class extends TransformStream{constructor(e){super({transform(r,t){const{path:[a,...i]}=r;if(e!==a)throw new Error(`Path mismatch: expected ${e}, got ${a}`);t.enqueue({...r,path:i})}})}});var da=class extends TransformStream{constructor(e){const r=new Rt,t=new Map;super({transform(a,i){a.type==="part-start"&&a.path.length===0&&t.set(r.up(),e.up());const[s,...n]=a.path;if(s===void 0){i.enqueue(a);return}const c=t.get(s);if(c===void 0)throw new Error("Path not found");i.enqueue({...a,path:[c,...n]})}})}};let ha=(e,r=21)=>(t=r)=>{let a="",i=t|0;for(;i--;)a+=e[Math.random()*e.length|0];return a};var fa=ha("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),ma=class Lt{constructor(r){z(this,"_state");z(this,"_parentId");this._state=r||{merger:oa(),contentCounter:new Rt}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(r){this._state.closeSubscriber=r}_addPart(r,t){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:"part-start",part:r,path:[]}),this._state.merger.addStream(t.pipeThrough(new ua(this._state.contentCounter.value)))}merge(r){this._state.merger.addStream(r.pipeThrough(new da(this._state.contentCounter)))}appendText(r){this._state.append?.kind!=="text"&&(this._state.append={kind:"text",controller:this.addTextPart()}),this._state.append.controller.append(r)}appendReasoning(r){this._state.append?.kind!=="reasoning"&&(this._state.append={kind:"reasoning",controller:this.addReasoningPart()}),this._state.append.controller.append(r)}addTextPart(){const[r,t]=ht();return this._addPart({type:"text"},r),t}addReasoningPart(){const[r,t]=ht();return this._addPart({type:"reasoning"},r),t}addToolCallPart(r){const t=typeof r=="string"?{toolName:r}:r,a=t.toolName,i=t.toolCallId??fa(),[s,n]=la();return this._addPart({type:"tool-call",toolName:a,toolCallId:i,...this._parentId&&{parentId:this._parentId}},s),t.argsText!==void 0&&(n.argsText.append(t.argsText),n.argsText.close()),t.args!==void 0&&(n.argsText.append(JSON.stringify(t.args)),n.argsText.close()),t.response!==void 0&&n.setResponse(t.response),n}appendSource(r){this._addPart({...r,...this._parentId&&{parentId:this._parentId}},new ReadableStream({start(t){t.enqueue({type:"part-finish",path:[]}),t.close()}}))}appendFile(r){this._addPart(r,new ReadableStream({start(t){t.enqueue({type:"part-finish",path:[]}),t.close()}}))}enqueue(r){this._state.merger.enqueue(r),r.type==="part-start"&&r.path.length===0&&this._state.contentCounter.up()}withParentId(r){const t=new Lt(this._state);return t._parentId=r,t}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}};function pa(e){const r=new ma;return(async()=>{try{await e(r)}catch(a){throw r.__internal_isClosed||r.enqueue({type:"error",path:[],error:String(a)}),a}finally{r.__internal_isClosed||r.close()}})(),r.__internal_getReadable()}const me=new Map,Se=new Map;let ce;function De(e,r){const t=me.get(e);if(t)return t;if(r)for(const a of r){const i=Se.get(a.id);if(i)return me.set(e,i),i}return e}function ga(e,r){return{async list(){const t=[];let i,s=0;do{const c=await e.listChats({limit:50,cursor:i}),o=c.items||[];Array.isArray(o)&&o.length>0&&t.push(...o),i=c.nextCursor||void 0,s++}while(i&&s<50);return{threads:t.map(c=>{const o=c.id;return!o||c.deletedAt?null:{status:"regular",remoteId:o,title:c.title||"New Chat",createdAt:c.createdAt?new Date(c.createdAt):new Date,updatedAt:c.updatedAt?new Date(c.updatedAt):new Date}}).filter(c=>c!==null)}},async initialize(t){return{remoteId:me.get(t)||t,externalId:void 0}},async rename(t,a){const i=De(t);await e.updateChat(i,{title:a})},async archive(t){},async unarchive(t){},async delete(t){const a=De(t);await e.deleteChat(a)},async generateTitle(t,a){const i=De(t,a);let s;try{s=(await e.generateChatTitle(i)).title}catch(n){console.error("[generateTitle] API call failed, falling back to first message",n);const o=a.find(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 pa(n=>{const c=n.addTextPart();s&&c.append(s),c.close(),n.close()})},async fetch(t){try{const a=await e.getChat(t);return{status:"regular",remoteId:a.id||t,title:a.title||"Chat",createdAt:a.createdAt?new Date(a.createdAt):new Date,updatedAt:a.updatedAt?new Date(a.updatedAt):new Date}}catch{return{status:"regular",remoteId:t,createdAt:new Date,updatedAt:new Date}}},updateRemoteId(t,a){me.set(t,a),r?.(t,a)},unstable_Provider:({children:t})=>{const i=T.useThreadListItem()?.remoteId;y.useEffect(()=>{i&&(ce=i)},[i]);const s=y.useMemo(()=>({async load(){if(!i)return{messages:[]};try{const c=await e.getChat(i);if(!c.messages||c.messages.length===0)return{messages:[]};const o=c.messages.map(f=>ia(f)),l=o.map((f,d)=>({message:f,parentId:d>0?o[d-1].id:null}));for(const f of o)Se.set(f.id,i);return{messages:l}}catch{return{messages:[]}}},async append(c){}}),[i,e]),n=y.useMemo(()=>({history:s}),[s]);return u.jsx(T.RuntimeAdapterProvider,{adapters:n,children:t})}}}class xa{constructor(){z(this,"messageMetadata",new Map);z(this,"currentMessageId",null);z(this,"listeners",new Set)}setCurrentMessage(r){this.currentMessageId=r}update(r){if(!this.currentMessageId)return;const t=this.messageMetadata.get(this.currentMessageId)||{},a=r.sources;a&&a.length>0&&(this.messageMetadata.set(this.currentMessageId,{...t,sources:a}),this.notify())}get(){return this.currentMessageId?this.messageMetadata.get(this.currentMessageId)||{}:{}}getForMessage(r){return this.messageMetadata.get(r)||{}}getCurrentMessageId(){return this.currentMessageId}clear(){this.currentMessageId=null}subscribe(r){return this.listeners.add(r),()=>this.listeners.delete(r)}notify(){this.listeners.forEach(r=>r())}}const ee=new xa,mt=new Map,We=[];let Ce=[];function Dt(e,r,t=50,a=800){We.push({question:e,response:r,streamingSpeed:t,initialDelay:a})}function Ft(e,r){const{modelId:t,systemPrompt:a,ephemeral:i,enableReasoning:s,onChatCreated:n,onUserMessage:c,onThreadIdUpdate:o,onBeforeRequest:l,mockResponseOnBlocked:f}=r;let d;return{async*run(m){const{messages:g,abortSignal:h}=m,b=We.shift();if(b){c?.();const k=b.initialDelay??800;if(k>0&&await new Promise(M=>setTimeout(M,k)),h?.aborted)throw new Error("Request aborted");const j=b.response.split(" ");let E="";const U=b.streamingSpeed||50,F=`premade-${Date.now()}`;i&&n?.(F);for(let M=0;M<j.length;M++){if(h?.aborted)throw new Error("Request aborted");E+=(M===0?"":" ")+j[M],yield{content:[{type:"text",text:E}]},await new Promise(W=>setTimeout(W,U+Math.random()*(U*.5)))}yield{content:[{type:"text",text:E}]},Ce.push({role:"user",content:b.question},{role:"assistant",content:b.response});return}let x;for(const k of g){const j=Se.get(k.id);if(j){x=j;break}}if(!x&&g.length>0){const k=g.find(j=>j.role==="user");if(k){const E=(typeof k.content=="string"?k.content:Array.isArray(k.content)&&k.content.find(U=>U.type==="text")?.text||"").substring(0,50);x=mt.get(E)}}!x&&d&&(x=d),c?.();let w=g,C=-1;for(let k=g.length-1;k>=0;k--)if(g[k].role==="assistant"){C=k;break}(x||C>=0)&&C>=0&&(w=g.slice(C+1));const v=na(w);if(Ce.length>0&&!x){const k=Ce.map(j=>({role:j.role,content:j.content}));v.unshift(...k),Ce=[]}const _=[];let S;for(let k=w.length-1;k>=0;k--)if(w[k].role==="user"){S=w[k];break}if(S&&"attachments"in S){const k=S.attachments;if(k&&k.length>0){for(const j of k)if(j.file)try{const E=await e.uploadFile(j.file);_.push(E.id)}catch{}}}const P={messages:v,chatId:x||null,systemPrompt:a,ephemeral:i,enableReasoning:s,stream:!0};if(t&&t.trim()!==""&&(P.modelId=t),_.length>0&&(P.fileIds=_),l&&!await l()){if(f){const j=typeof f=="function"?f():f,E=g.filter(W=>W.role==="user"),U=E.length>0?E[E.length-1]:void 0;let F="Message";U&&(typeof U.content=="string"?F=U.content:Array.isArray(U.content)&&(F=U.content.find(Y=>Y.type==="text")?.text||"Message")),Dt(F,j,40,400);const M=We.shift();if(M){c?.();const W=M.initialDelay??400;if(W>0&&await new Promise(X=>setTimeout(X,W)),h?.aborted)throw new Error("Request aborted");const Y=M.response.split(" ");let J="";const ge=M.streamingSpeed||40,Ee=`mock-${Date.now()}`;i&&n?.(Ee);for(let X=0;X<Y.length;X++){if(h?.aborted)throw new Error("Request aborted");J+=(X===0?"":" ")+Y[X],yield{content:[{type:"text",text:J}]},await new Promise(ne=>setTimeout(ne,ge+Math.random()*(ge*.3)))}yield{content:[{type:"text",text:J}]};return}}throw new Error("Request blocked")}const $=await e.createOrContinueChat(P,h);let A="",L="",p;const R=[];let G=0,H=!1;const I=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;ee.clear(),ee.setCurrentMessage(I);const D=()=>{R.length!==G&&(G=R.length,ee.update({sources:R.length>0?[...R]:void 0}))},B=()=>{D();const k=[];return L&&k.push({type:"reasoning",text:L}),A&&k.push({type:"text",text:A}),k.length===0&&k.push({type:"text",text:""}),{content:k}};for await(const k of aa($,h)){if(h?.aborted)throw new Error("Request aborted");const j=k.id||k.chatId||k.messageId;if(j&&!p){p=j,d=j,n?.(j);for(const M of g)Se.set(M.id,j);if(g.length>0){const M=g.find(W=>W.role==="user");if(M){const Y=(typeof M.content=="string"?M.content:Array.isArray(M.content)&&M.content.find(J=>J.type==="text")?.text||"").substring(0,50);mt.set(Y,j)}}ce&&!me.has(ce)&&me.set(ce,j),o&&ce&&o(ce,j)}const E=k.sources;if(E&&Array.isArray(E)&&E.length>0)for(const M of E)R.some(W=>W.sourceId===M.sourceId)||R.push({sourceId:M.sourceId,filename:M.filename||"Unknown",score:M.score??1,chunkId:M.chunkId,datasetId:M.datasetId});const U=k.reasoning;if(U&&U.length>0&&(L+=U,yield B()),k.type)switch(k.type){case"source-document":k.sourceId&&R.push({sourceId:k.sourceId,filename:k.title||"Unknown",score:1});continue;case"reasoning-start":continue;case"reasoning-delta":k.delta&&(L+=k.delta),(A||L)&&(yield B());continue;case"reasoning-end":(A||L)&&(yield B());continue;case"text-delta":k.delta&&(L&&!H&&!A&&(H=!0,await new Promise(M=>setTimeout(M,400))),A+=k.delta),A&&(yield B());continue;case"error":throw new Error(k.errorText||"Stream error");case"text-start":case"text-end":case"start":case"start-step":case"finish-step":case"finish":continue}const F=k.delta;if(F!=null&&(L&&!H&&!A&&(H=!0,await new Promise(M=>setTimeout(M,400))),A+=F),k.content&&(A+=k.content),k.message&&(A+=k.message.content||""),k.finished){(A||L||R.length>0)&&(yield B());break}(A||L||R.length>0)&&(yield B())}(A||L||R.length>0)&&(yield B())}}}class le extends Error{constructor(r,t,a){super(r),this.code=t,this.file=a,this.name="AttachmentValidationError"}}const ya=["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"],ba=[".pdf",".doc",".docx",".xls",".xlsx",".txt",".md",".csv",".json",".jpg",".jpeg",".png",".gif",".webp",".svg"],wa=10*1024*1024;function pt(e){if(e===0)return"0 Bytes";const r=1024,t=["Bytes","KB","MB","GB"],a=Math.floor(Math.log(e)/Math.log(r));return parseFloat((e/Math.pow(r,a)).toFixed(2))+" "+t[a]}function ka(e){return e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")).toLowerCase():""}function Ca(e,r){const a={"image/jpeg":[".jpg",".jpeg"],"image/png":[".png"],"image/gif":[".gif"],"image/webp":[".webp"],"image/svg+xml":[".svg"],"application/pdf":[".pdf"],"text/plain":[".txt"],"text/markdown":[".md"],"text/csv":[".csv"],"application/json":[".json"]}[e];return a?a.includes(r.toLowerCase()):!0}function va(){return typeof crypto<"u"&&crypto.randomUUID?"attachment-"+crypto.randomUUID():"attachment-"+Date.now()+"-"+Math.random().toString(36).slice(2,11)}function Qe(e={}){const{validation:r={},supportsVision:t=!0,onValidationError:a,onAttachmentAdded:i,onAttachmentRemoved:s}=e,{maxFileSizeBytes:n=wa,allowedMimeTypes:c=ya,allowedExtensions:o=ba,validateContentType:l=!0}=r,f=o.join(",");function d(m){if(m.size>n){const h=new le('File "'+m.name+'" is too large ('+pt(m.size)+"). Maximum size is "+pt(n)+".","FILE_TOO_LARGE",m);throw a?.(h),h}if(!t&&m.type.startsWith("image/")){const h=new le("The current model does not support image inputs. Please select a model with vision capabilities to attach images.","VISION_NOT_SUPPORTED",m);throw a?.(h),h}const g=ka(m.name);if(g&&!o.some(h=>h.toLowerCase()===g)){const h=new le('File type "'+g+'" is not allowed. Allowed types: '+o.join(", "),"INVALID_TYPE",m);throw a?.(h),h}if(m.type&&!c.some(h=>{if(h.endsWith("/*")){const b=h.slice(0,-1);return m.type.startsWith(b)}return m.type===h})){const h=new le('File type "'+m.type+'" is not allowed.',"INVALID_TYPE",m);throw a?.(h),h}if(l&&m.type&&g&&!Ca(m.type,g)){const h=new le('File extension "'+g+'" does not match content type "'+m.type+'".',"VALIDATION_FAILED",m);throw a?.(h),h}}return{accept:f,async add({file:m}){d(m);let g="file";m.type.startsWith("image/")?g="image":(m.type.includes("pdf")||m.type.includes("document")||m.type.includes("text")||m.name.endsWith(".pdf")||m.name.endsWith(".docx")||m.name.endsWith(".txt")||m.name.endsWith(".md")||m.name.endsWith(".csv")||m.name.endsWith(".json"))&&(g="document");const h={id:va(),type:g,name:m.name,contentType:m.type,file:m,status:{type:"requires-action",reason:"composer-send"}};return i?.(h),h},async remove(m){s?.(m.id)},async send(m){if(m.type==="image"&&m.file){const g=await new Promise((h,b)=>{const x=new FileReader;x.onload=()=>h(x.result),x.onerror=()=>b(new Error("Failed to read file")),x.readAsDataURL(m.file)});return{...m,status:{type:"complete"},content:[{type:"image",image:g}]}}return{...m,status:{type:"complete"},content:[]}}}}class Ta{constructor(){z(this,"current",null);z(this,"listeners",new Set);z(this,"getSnapshot",()=>this.current);z(this,"subscribe",r=>(this.listeners.add(r),()=>this.listeners.delete(r)))}push(r,t){this.current={message:r,code:t,timestamp:Date.now()},this.notify()}clear(){this.current&&(this.current=null,this.notify())}notify(){this.listeners.forEach(r=>r())}}const de=new Ta;function ja({children:e,baseUrl:r,sessionToken:t,isProxyMode:a=!1,mode:i="multiChat",modelId:s,onModelChange:n,ephemeral:c=!1,systemPrompt:o,enableReasoning:l=!1,initialThreadId:f,onError:d,onChatCreated:m,onUserMessage:g,onThreadIdUpdate:h,onChatsLoaded:b,enableAttachments:x=!1,supportsVision:w=!0,onBeforeRequest:C,mockResponseOnBlocked:v}){const _=y.useMemo(()=>new Pt(r,t||void 0,a),[r,t,a]),[S,P]=y.useState(s||null);y.useEffect(()=>{s&&P(s)},[s]);const $=y.useCallback(p=>{m?.(p)},[m]),A=y.useCallback((p,R)=>{h?.(p,R)},[h]),L=y.useMemo(()=>Ft(_,{modelId:S||void 0,systemPrompt:o,ephemeral:c,enableReasoning:l,onChatCreated:$,onUserMessage:g,onBeforeRequest:C,mockResponseOnBlocked:v}),[_,S,o,c,l,$,g,C,v]);return i==="singleChat"?u.jsx(Sa,{modelAdapter:L,enableAttachments:x,supportsVision:w,children:e}):u.jsx(Ia,{client:_,modelAdapterOptions:{modelId:S||void 0,systemPrompt:o,ephemeral:c,enableReasoning:l,onChatCreated:$,onUserMessage:g,onBeforeRequest:C,mockResponseOnBlocked:v},initialThreadId:f,onChatsLoaded:b,onThreadIdUpdate:A,onError:d,enableAttachments:x,supportsVision:w,children:e})}function Sa({modelAdapter:e,enableAttachments:r,supportsVision:t=!0,children:a}){const i=y.useMemo(()=>r?Qe({supportsVision:t,onValidationError:n=>{de.push(n.message,n.code)}}):void 0,[r,t]),s=T.useLocalRuntime(e,{adapters:{...i&&{attachments:i}}});return u.jsx(T.AssistantRuntimeProvider,{runtime:s,children:a})}function Ia({client:e,modelAdapterOptions:r,initialThreadId:t,onChatsLoaded:a,onThreadIdUpdate:i,onError:s,enableAttachments:n,supportsVision:c,children:o}){const l=y.useMemo(()=>ga(e,(x,w)=>{i?.(x,w)}),[e,i]),f=y.useCallback((x,w)=>{l.updateRemoteId&&l.updateRemoteId(x,w),i?.(x,w)},[l,i]),d=y.useMemo(()=>({...l,async list(){const x=await l.list();return a?.(),x}}),[l,a]);y.useEffect(()=>{window.__cuadraThreadListAdapter=d,window.__cuadraThreadListRuntime=null},[d]);const m=y.useMemo(()=>Ft(e,{...r,onThreadIdUpdate:f}),[e,r,f]),g=y.useMemo(()=>n?Qe({supportsVision:c,onValidationError:x=>{de.push(x.message,x.code)}}):void 0,[n,c]),h=y.useCallback(()=>T.useLocalRuntime(m,{adapters:{...g&&{attachments:g}}}),[m,g]),b=T.unstable_useRemoteThreadListRuntime({adapter:d,runtimeHook:h});return y.useEffect(()=>{window.__cuadraThreadListRuntime=b},[b]),u.jsx(T.AssistantRuntimeProvider,{runtime:b,children:o})}function gt(e,r){const t=String(e);if(typeof r!="string")throw new TypeError("Expected character");let a=0,i=t.indexOf(r);for(;i!==-1;)a++,i=t.indexOf(r,i+r.length);return a}const ye=Ne(/[A-Za-z]/),Ge=Ne(/[\dA-Za-z]/);function Ma(e){return e!==null&&(e<32||e===127)}function he(e){return e!==null&&e<-2}function V(e){return e!==null&&(e<0||e===32)}function te(e){return e===-2||e===-1||e===32}const Ae=Ne(/\p{P}|\p{S}/u),oe=Ne(/\s/);function Ne(e){return r;function r(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function Aa(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 Ea;if(typeof e=="function")return Pe(e);if(typeof e=="object")return Array.isArray(e)?Na(e):_a(e);if(typeof e=="string")return Pa(e);throw new Error("Expected function, string, or object as test")});function Na(e){const r=[];let t=-1;for(;++t<e.length;)r[t]=_e(e[t]);return Pe(a);function a(...i){let s=-1;for(;++s<r.length;)if(r[s].apply(this,i))return!0;return!1}}function _a(e){const r=e;return Pe(t);function t(a){const i=a;let s;for(s in e)if(i[s]!==r[s])return!1;return!0}}function Pa(e){return Pe(r);function r(t){return t&&t.type===e}}function Pe(e){return r;function r(t,a,i){return!!(Ra(t)&&e.call(this,t,typeof a=="number"?a:void 0,i||void 0))}}function Ea(){return!0}function Ra(e){return e!==null&&typeof e=="object"&&"type"in e}const Ut=[],La=!0,Ve=!1,Da="skip";function zt(e,r,t,a){let i;typeof r=="function"&&typeof t!="function"?(a=t,t=r):i=r;const s=_e(i),n=a?-1:1;c(e,void 0,[])();function c(o,l,f){const d=o&&typeof o=="object"?o:{};if(typeof d.type=="string"){const g=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(m,"name",{value:"node ("+(o.type+(g?"<"+g+">":""))+")"})}return m;function m(){let g=Ut,h,b,x;if((!r||s(o,l,f[f.length-1]||void 0))&&(g=Fa(t(o,f)),g[0]===Ve))return g;if("children"in o&&o.children){const w=o;if(w.children&&g[0]!==Da)for(b=(a?w.children.length:-1)+n,x=f.concat(w);b>-1&&b<w.children.length;){const C=w.children[b];if(h=c(C,b,x)(),h[0]===Ve)return h;b=typeof h[1]=="number"?h[1]:b+n}}return g}}}function Fa(e){return Array.isArray(e)?e:typeof e=="number"?[La,e]:e==null?Ut:[e]}function Ua(e,r,t){const i=_e((t||{}).ignore||[]),s=za(r);let n=-1;for(;++n<s.length;)zt(e,"text",c);function c(l,f){let d=-1,m;for(;++d<f.length;){const g=f[d],h=m?m.children:void 0;if(i(g,h?h.indexOf(g):void 0,m))return;m=g}if(m)return o(l,f)}function o(l,f){const d=f[f.length-1],m=s[n][0],g=s[n][1];let h=0;const x=d.children.indexOf(l);let w=!1,C=[];m.lastIndex=0;let v=m.exec(l.value);for(;v;){const _=v.index,S={index:v.index,input:v.input,stack:[...f,l]};let P=g(...v,S);if(typeof P=="string"&&(P=P.length>0?{type:"text",value:P}:void 0),P===!1?m.lastIndex=_+1:(h!==_&&C.push({type:"text",value:l.value.slice(h,_)}),Array.isArray(P)?C.push(...P):P&&C.push(P),h=_+v[0].length,w=!0),!m.global)break;v=m.exec(l.value)}return w?(h<l.value.length&&C.push({type:"text",value:l.value.slice(h)}),d.children.splice(x,1,...C)):C=[l],x+C.length}}function za(e){const r=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const t=!e[0]||Array.isArray(e[0])?e:[e];let a=-1;for(;++a<t.length;){const i=t[a];r.push([$a(i[0]),Oa(i[1])])}return r}function $a(e){return typeof e=="string"?new RegExp(Aa(e),"g"):e}function Oa(e){return typeof e=="function"?e:function(){return e}}const Fe="phrasing",Ue=["autolink","link","image","label"];function Ba(){return{transforms:[Ga],enter:{literalAutolink:Wa,literalAutolinkEmail:ze,literalAutolinkHttp:ze,literalAutolinkWww:ze},exit:{literalAutolink:Qa,literalAutolinkEmail:Ka,literalAutolinkHttp:Va,literalAutolinkWww:Ha}}}function qa(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Fe,notInConstruct:Ue},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Fe,notInConstruct:Ue},{character:":",before:"[ps]",after:"\\/",inConstruct:Fe,notInConstruct:Ue}]}}function Wa(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function ze(e){this.config.enter.autolinkProtocol.call(this,e)}function Va(e){this.config.exit.autolinkProtocol.call(this,e)}function Ha(e){this.config.exit.data.call(this,e);const r=this.stack[this.stack.length-1];r.type,r.url="http://"+this.sliceSerialize(e)}function Ka(e){this.config.exit.autolinkEmail.call(this,e)}function Qa(e){this.exit(e)}function Ga(e){Ua(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,Ya],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,Ja]],{ignore:["link","linkReference"]})}function Ya(e,r,t,a,i){let s="";if(!$t(i)||(/^w/i.test(r)&&(t=r+t,r="",s="http://"),!Xa(t)))return!1;const n=Za(t+a);if(!n[0])return!1;const c={type:"link",title:null,url:s+r+n[0],children:[{type:"text",value:r+n[0]}]};return n[1]?[c,{type:"text",value:n[1]}]:c}function Ja(e,r,t,a){return!$t(a,!0)||/[-\d_]$/.test(t)?!1:{type:"link",title:null,url:"mailto:"+r+"@"+t,children:[{type:"text",value:r+"@"+t}]}}function Xa(e){const r=e.split(".");return!(r.length<2||r[r.length-1]&&(/_/.test(r[r.length-1])||!/[a-zA-Z\d]/.test(r[r.length-1]))||r[r.length-2]&&(/_/.test(r[r.length-2])||!/[a-zA-Z\d]/.test(r[r.length-2])))}function Za(e){const r=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!r)return[e,void 0];e=e.slice(0,r.index);let t=r[0],a=t.indexOf(")");const i=gt(e,"(");let s=gt(e,")");for(;a!==-1&&i>s;)e+=t.slice(0,a+1),t=t.slice(a+1),a=t.indexOf(")"),s++;return[e,t]}function $t(e,r){const t=e.input.charCodeAt(e.index-1);return(e.index===0||oe(t)||Ae(t))&&(!r||t!==47)}function we(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}Ot.peek=ln;function en(){this.buffer()}function tn(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function rn(){this.buffer()}function an(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function nn(e){const r=this.resume(),t=this.stack[this.stack.length-1];t.type,t.identifier=we(this.sliceSerialize(e)).toLowerCase(),t.label=r}function sn(e){this.exit(e)}function on(e){const r=this.resume(),t=this.stack[this.stack.length-1];t.type,t.identifier=we(this.sliceSerialize(e)).toLowerCase(),t.label=r}function cn(e){this.exit(e)}function ln(){return"["}function Ot(e,r,t,a){const i=t.createTracker(a);let s=i.move("[^");const n=t.enter("footnoteReference"),c=t.enter("reference");return s+=i.move(t.safe(t.associationId(e),{after:"]",before:s})),c(),n(),s+=i.move("]"),s}function un(){return{enter:{gfmFootnoteCallString:en,gfmFootnoteCall:tn,gfmFootnoteDefinitionLabelString:rn,gfmFootnoteDefinition:an},exit:{gfmFootnoteCallString:nn,gfmFootnoteCall:sn,gfmFootnoteDefinitionLabelString:on,gfmFootnoteDefinition:cn}}}function dn(e){let r=!1;return e&&e.firstLineBlank&&(r=!0),{handlers:{footnoteDefinition:t,footnoteReference:Ot},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function t(a,i,s,n){const c=s.createTracker(n);let o=c.move("[^");const l=s.enter("footnoteDefinition"),f=s.enter("label");return o+=c.move(s.safe(s.associationId(a),{before:o,after:"]"})),f(),o+=c.move("]:"),a.children&&a.children.length>0&&(c.shift(4),o+=c.move((r?`
|
|
6
|
-
`:" ")+s.indentLines(s.containerFlow(a,c.current()),r?
|
|
7
|
-
`)}function
|
|
8
|
-
`&&
|
|
9
|
-
`}function
|
|
5
|
+
`);i=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{t.releaseLock()}}function ia(e){return e.map(r=>{let t="";if(typeof r.content=="string")t=r.content;else if(Array.isArray(r.content)){const a=r.content.find(i=>i.type==="text");a&&typeof a=="object"&&"text"in a&&(t=a.text)}return{role:r.role,content:t}})}function sa(e){return{id:e.id,role:e.role,content:[{type:"text",text:e.content}],createdAt:new Date(e.createdAt),metadata:{custom:{}},...e.role==="assistant"&&{status:{type:"complete",reason:"stop"},metadata:{unstable_state:null,unstable_annotations:[],unstable_data:[],steps:[],custom:{}}},...e.role==="user"&&{attachments:[]}}}var oa=function(){let e,r;const t=new Promise((a,i)=>{e=a,r=i});if(!e||!r)throw new Error("Failed to create promise");return{promise:t,resolve:e,reject:r}},ca=()=>{const e=[];let r=!1,t,a;const i=n=>{n.promise||(n.promise=n.reader.read().then(({done:c,value:o})=>{n.promise=void 0,c?(e.splice(e.indexOf(n),1),r&&e.length===0&&t.close()):t.enqueue(o),a?.resolve(),a=void 0}).catch(c=>{console.error(c),e.forEach(o=>{o.reader.cancel()}),e.length=0,t.error(c),a?.reject(c),a=void 0}))};return{readable:new ReadableStream({start(n){t=n},pull(){return a=oa(),e.forEach(n=>{i(n)}),a.promise},cancel(){e.forEach(n=>{n.reader.cancel()}),e.length=0}}),isSealed(){return r},seal(){r=!0,e.length===0&&t.close()},addStream(n){if(r)throw new Error("Cannot add streams after the run callback has settled.");const c={reader:n.getReader()};e.push(c),i(c)},enqueue(n){this.addStream(new ReadableStream({start(c){c.enqueue(n),c.close()}}))}}},dt=class{constructor(e){z(this,"_controller");z(this,"_isClosed",!1);this._controller=e}append(e){return this._controller.enqueue({type:"text-delta",path:[],textDelta:e}),this}close(){this._isClosed||(this._isClosed=!0,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}},Rt=e=>new ReadableStream({start(r){return e.start?.(new dt(r))},pull(r){return e.pull?.(new dt(r))},cancel(r){return e.cancel?.(r)}}),ht=()=>{let e;return[Rt({start(t){e=t}}),e]},ft=class{constructor(e){z(this,"_isClosed",!1);z(this,"_mergeTask");z(this,"_argsTextController");this._controller=e;const r=Rt({start:a=>{this._argsTextController=a}});let t=!1;this._mergeTask=r.pipeTo(new WritableStream({write:a=>{switch(a.type){case"text-delta":t=!0,this._controller.enqueue(a);break;case"part-finish":t||this._controller.enqueue({type:"text-delta",textDelta:"{}",path:[]}),this._controller.enqueue({type:"tool-call-args-text-finish",path:[]});break;default:throw new Error(`Unexpected chunk type: ${a.type}`)}}}))}get argsText(){return this._argsTextController}async setResponse(e){this._argsTextController.close(),await Promise.resolve(),this._controller.enqueue({type:"result",path:[],...e.artifact!==void 0?{artifact:e.artifact}:{},result:e.result,isError:e.isError??!1})}async close(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),await this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}},la=e=>new ReadableStream({start(r){return e.start?.(new ft(r))},pull(r){return e.pull?.(new ft(r))},cancel(r){return e.cancel?.(r)}}),ua=()=>{let e;return[la({start(t){e=t}}),e]},Lt=class{constructor(){z(this,"value",-1)}up(){return++this.value}},da=class extends TransformStream{constructor(e){super({transform(r,t){t.enqueue({...r,path:[e,...r.path]})}})}};(class extends TransformStream{constructor(e){super({transform(r,t){const{path:[a,...i]}=r;if(e!==a)throw new Error(`Path mismatch: expected ${e}, got ${a}`);t.enqueue({...r,path:i})}})}});var ha=class extends TransformStream{constructor(e){const r=new Lt,t=new Map;super({transform(a,i){a.type==="part-start"&&a.path.length===0&&t.set(r.up(),e.up());const[s,...n]=a.path;if(s===void 0){i.enqueue(a);return}const c=t.get(s);if(c===void 0)throw new Error("Path not found");i.enqueue({...a,path:[c,...n]})}})}};let fa=(e,r=21)=>(t=r)=>{let a="",i=t|0;for(;i--;)a+=e[Math.random()*e.length|0];return a};var ma=fa("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),pa=class Dt{constructor(r){z(this,"_state");z(this,"_parentId");this._state=r||{merger:ca(),contentCounter:new Lt}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(r){this._state.closeSubscriber=r}_addPart(r,t){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:"part-start",part:r,path:[]}),this._state.merger.addStream(t.pipeThrough(new da(this._state.contentCounter.value)))}merge(r){this._state.merger.addStream(r.pipeThrough(new ha(this._state.contentCounter)))}appendText(r){this._state.append?.kind!=="text"&&(this._state.append={kind:"text",controller:this.addTextPart()}),this._state.append.controller.append(r)}appendReasoning(r){this._state.append?.kind!=="reasoning"&&(this._state.append={kind:"reasoning",controller:this.addReasoningPart()}),this._state.append.controller.append(r)}addTextPart(){const[r,t]=ht();return this._addPart({type:"text"},r),t}addReasoningPart(){const[r,t]=ht();return this._addPart({type:"reasoning"},r),t}addToolCallPart(r){const t=typeof r=="string"?{toolName:r}:r,a=t.toolName,i=t.toolCallId??ma(),[s,n]=ua();return this._addPart({type:"tool-call",toolName:a,toolCallId:i,...this._parentId&&{parentId:this._parentId}},s),t.argsText!==void 0&&(n.argsText.append(t.argsText),n.argsText.close()),t.args!==void 0&&(n.argsText.append(JSON.stringify(t.args)),n.argsText.close()),t.response!==void 0&&n.setResponse(t.response),n}appendSource(r){this._addPart({...r,...this._parentId&&{parentId:this._parentId}},new ReadableStream({start(t){t.enqueue({type:"part-finish",path:[]}),t.close()}}))}appendFile(r){this._addPart(r,new ReadableStream({start(t){t.enqueue({type:"part-finish",path:[]}),t.close()}}))}enqueue(r){this._state.merger.enqueue(r),r.type==="part-start"&&r.path.length===0&&this._state.contentCounter.up()}withParentId(r){const t=new Dt(this._state);return t._parentId=r,t}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}};function ga(e){const r=new pa;return(async()=>{try{await e(r)}catch(a){throw r.__internal_isClosed||r.enqueue({type:"error",path:[],error:String(a)}),a}finally{r.__internal_isClosed||r.close()}})(),r.__internal_getReadable()}const me=new Map,Se=new Map;let ce;function De(e,r){const t=me.get(e);if(t)return t;if(r)for(const a of r){const i=Se.get(a.id);if(i)return me.set(e,i),i}return e}function xa(e,r){return{async list(){const t=[];let i,s=0;do{const c=await e.listChats({limit:50,cursor:i}),o=c.items||[];Array.isArray(o)&&o.length>0&&t.push(...o),i=c.nextCursor||void 0,s++}while(i&&s<50);return{threads:t.map(c=>{const o=c.id;return!o||c.deletedAt?null:{status:"regular",remoteId:o,title:c.title||"New Chat",createdAt:c.createdAt?new Date(c.createdAt):new Date,updatedAt:c.updatedAt?new Date(c.updatedAt):new Date}}).filter(c=>c!==null)}},async initialize(t){return{remoteId:me.get(t)||t,externalId:void 0}},async rename(t,a){const i=De(t);await e.updateChat(i,{title:a})},async archive(t){},async unarchive(t){},async delete(t){const a=De(t);await e.deleteChat(a)},async generateTitle(t,a){const i=De(t,a);let s;try{s=(await e.generateChatTitle(i)).title}catch(n){console.error("[generateTitle] API call failed, falling back to first message",n);const o=a.find(l=>l.role==="user")?.content?.filter(l=>l.type==="text").map(l=>l.text).join(" ").trim();s=o?o.length>60?o.slice(0,57)+"...":o:void 0}return ga(n=>{const c=n.addTextPart();s&&c.append(s),c.close(),n.close()})},async fetch(t){try{const a=await e.getChat(t);return{status:"regular",remoteId:a.id||t,title:a.title||"Chat",createdAt:a.createdAt?new Date(a.createdAt):new Date,updatedAt:a.updatedAt?new Date(a.updatedAt):new Date}}catch{return{status:"regular",remoteId:t,createdAt:new Date,updatedAt:new Date}}},updateRemoteId(t,a){me.set(t,a),r?.(t,a)},unstable_Provider:({children:t})=>{const i=T.useThreadListItem()?.remoteId;y.useEffect(()=>{i&&(ce=i)},[i]);const s=y.useMemo(()=>({async load(){if(!i)return{messages:[]};try{const c=await e.getChat(i);if(!c.messages||c.messages.length===0)return{messages:[]};const o=c.messages.map(f=>sa(f)),l=o.map((f,d)=>({message:f,parentId:d>0?o[d-1].id:null}));for(const f of o)Se.set(f.id,i);return{messages:l}}catch{return{messages:[]}}},async append(c){}}),[i,e]),n=y.useMemo(()=>({history:s}),[s]);return u.jsx(T.RuntimeAdapterProvider,{adapters:n,children:t})}}}class ya{constructor(){z(this,"messageMetadata",new Map);z(this,"currentMessageId",null);z(this,"listeners",new Set)}setCurrentMessage(r){this.currentMessageId=r}update(r){if(!this.currentMessageId)return;const t=this.messageMetadata.get(this.currentMessageId)||{},a=r.sources;a&&a.length>0&&(this.messageMetadata.set(this.currentMessageId,{...t,sources:a}),this.notify())}get(){return this.currentMessageId?this.messageMetadata.get(this.currentMessageId)||{}:{}}getForMessage(r){return this.messageMetadata.get(r)||{}}getCurrentMessageId(){return this.currentMessageId}clear(){this.currentMessageId=null}subscribe(r){return this.listeners.add(r),()=>this.listeners.delete(r)}notify(){this.listeners.forEach(r=>r())}}const ee=new ya,mt=new Map,Ve=[];let Ce=[];function Ft(e,r,t=50,a=800){Ve.push({question:e,response:r,streamingSpeed:t,initialDelay:a})}function Ut(e,r){const{modelId:t,systemPrompt:a,ephemeral:i,enableReasoning:s,onChatCreated:n,onUserMessage:c,onThreadIdUpdate:o,onBeforeRequest:l,mockResponseOnBlocked:f}=r;let d;return{async*run(m){const{messages:g,abortSignal:h}=m,b=Ve.shift();if(b){c?.();const k=b.initialDelay??800;if(k>0&&await new Promise(M=>setTimeout(M,k)),h?.aborted)throw new Error("Request aborted");const j=b.response.split(" ");let E="";const U=b.streamingSpeed||50,F=`premade-${Date.now()}`;i&&n?.(F);for(let M=0;M<j.length;M++){if(h?.aborted)throw new Error("Request aborted");E+=(M===0?"":" ")+j[M],yield{content:[{type:"text",text:E}]},await new Promise(V=>setTimeout(V,U+Math.random()*(U*.5)))}yield{content:[{type:"text",text:E}]},Ce.push({role:"user",content:b.question},{role:"assistant",content:b.response});return}let x;for(const k of g){const j=Se.get(k.id);if(j){x=j;break}}if(!x&&g.length>0){const k=g.find(j=>j.role==="user");if(k){const E=(typeof k.content=="string"?k.content:Array.isArray(k.content)&&k.content.find(U=>U.type==="text")?.text||"").substring(0,50);x=mt.get(E)}}!x&&d&&(x=d),c?.();let w=g,C=-1;for(let k=g.length-1;k>=0;k--)if(g[k].role==="assistant"){C=k;break}(x||C>=0)&&C>=0&&(w=g.slice(C+1));const v=ia(w);if(Ce.length>0&&!x){const k=Ce.map(j=>({role:j.role,content:j.content}));v.unshift(...k),Ce=[]}const _=[];let S;for(let k=w.length-1;k>=0;k--)if(w[k].role==="user"){S=w[k];break}if(S&&"attachments"in S){const k=S.attachments;if(k&&k.length>0){for(const j of k)if(j.file)try{const E=await e.uploadFile(j.file);_.push(E.id)}catch{}}}const P={messages:v,chatId:x||null,systemPrompt:a,ephemeral:i,enableReasoning:s,stream:!0};if(t&&t.trim()!==""&&(P.modelId=t),_.length>0&&(P.fileIds=_),l&&!await l()){if(f){const j=typeof f=="function"?f():f,E=g.filter(V=>V.role==="user"),U=E.length>0?E[E.length-1]:void 0;let F="Message";U&&(typeof U.content=="string"?F=U.content:Array.isArray(U.content)&&(F=U.content.find(Y=>Y.type==="text")?.text||"Message")),Ft(F,j,40,400);const M=Ve.shift();if(M){c?.();const V=M.initialDelay??400;if(V>0&&await new Promise(X=>setTimeout(X,V)),h?.aborted)throw new Error("Request aborted");const Y=M.response.split(" ");let J="";const ge=M.streamingSpeed||40,Ee=`mock-${Date.now()}`;i&&n?.(Ee);for(let X=0;X<Y.length;X++){if(h?.aborted)throw new Error("Request aborted");J+=(X===0?"":" ")+Y[X],yield{content:[{type:"text",text:J}]},await new Promise(ne=>setTimeout(ne,ge+Math.random()*(ge*.3)))}yield{content:[{type:"text",text:J}]};return}}throw new Error("Request blocked")}const $=await e.createOrContinueChat(P,h);let A="",L="",p;const R=[];let G=0,H=!1;const I=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;ee.clear(),ee.setCurrentMessage(I);const D=()=>{R.length!==G&&(G=R.length,ee.update({sources:R.length>0?[...R]:void 0}))},B=()=>{D();const k=[];return L&&k.push({type:"reasoning",text:L}),A&&k.push({type:"text",text:A}),k.length===0&&k.push({type:"text",text:""}),{content:k}};for await(const k of na($,h)){if(h?.aborted)throw new Error("Request aborted");const j=k.id||k.chatId||k.messageId;if(j&&!p){p=j,d=j,n?.(j);for(const M of g)Se.set(M.id,j);if(g.length>0){const M=g.find(V=>V.role==="user");if(M){const Y=(typeof M.content=="string"?M.content:Array.isArray(M.content)&&M.content.find(J=>J.type==="text")?.text||"").substring(0,50);mt.set(Y,j)}}ce&&!me.has(ce)&&me.set(ce,j),o&&ce&&o(ce,j)}const E=k.sources;if(E&&Array.isArray(E)&&E.length>0)for(const M of E)R.some(V=>V.sourceId===M.sourceId)||R.push({sourceId:M.sourceId,filename:M.filename||"Unknown",score:M.score??1,chunkId:M.chunkId,datasetId:M.datasetId});const U=k.reasoning;if(U&&U.length>0&&(L+=U,yield B()),k.type)switch(k.type){case"source-document":k.sourceId&&R.push({sourceId:k.sourceId,filename:k.title||"Unknown",score:1});continue;case"reasoning-start":continue;case"reasoning-delta":k.delta&&(L+=k.delta),(A||L)&&(yield B());continue;case"reasoning-end":(A||L)&&(yield B());continue;case"text-delta":k.delta&&(L&&!H&&!A&&(H=!0,await new Promise(M=>setTimeout(M,400))),A+=k.delta),A&&(yield B());continue;case"error":throw new Error(k.errorText||"Stream error");case"text-start":case"text-end":case"start":case"start-step":case"finish-step":case"finish":continue}const F=k.delta;if(F!=null&&(L&&!H&&!A&&(H=!0,await new Promise(M=>setTimeout(M,400))),A+=F),k.content&&(A+=k.content),k.message&&(A+=k.message.content||""),k.finished){(A||L||R.length>0)&&(yield B());break}(A||L||R.length>0)&&(yield B())}(A||L||R.length>0)&&(yield B())}}}class le extends Error{constructor(r,t,a){super(r),this.code=t,this.file=a,this.name="AttachmentValidationError"}}const ba=["image/jpeg","image/png","image/gif","image/webp","image/svg+xml","application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","text/plain","text/markdown","text/csv","application/json"],wa=[".pdf",".doc",".docx",".xls",".xlsx",".txt",".md",".csv",".json",".jpg",".jpeg",".png",".gif",".webp",".svg"],ka=10*1024*1024;function pt(e){if(e===0)return"0 Bytes";const r=1024,t=["Bytes","KB","MB","GB"],a=Math.floor(Math.log(e)/Math.log(r));return parseFloat((e/Math.pow(r,a)).toFixed(2))+" "+t[a]}function Ca(e){return e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")).toLowerCase():""}function va(e,r){const a={"image/jpeg":[".jpg",".jpeg"],"image/png":[".png"],"image/gif":[".gif"],"image/webp":[".webp"],"image/svg+xml":[".svg"],"application/pdf":[".pdf"],"text/plain":[".txt"],"text/markdown":[".md"],"text/csv":[".csv"],"application/json":[".json"]}[e];return a?a.includes(r.toLowerCase()):!0}function Ta(){return typeof crypto<"u"&&crypto.randomUUID?"attachment-"+crypto.randomUUID():"attachment-"+Date.now()+"-"+Math.random().toString(36).slice(2,11)}function Qe(e={}){const{validation:r={},supportsVision:t=!0,onValidationError:a,onAttachmentAdded:i,onAttachmentRemoved:s}=e,{maxFileSizeBytes:n=ka,allowedMimeTypes:c=ba,allowedExtensions:o=wa,validateContentType:l=!0}=r,f=o.join(",");function d(m){if(m.size>n){const h=new le('File "'+m.name+'" is too large ('+pt(m.size)+"). Maximum size is "+pt(n)+".","FILE_TOO_LARGE",m);throw a?.(h),h}if(!t&&m.type.startsWith("image/")){const h=new le("The current model does not support image inputs. Please select a model with vision capabilities to attach images.","VISION_NOT_SUPPORTED",m);throw a?.(h),h}const g=Ca(m.name);if(g&&!o.some(h=>h.toLowerCase()===g)){const h=new le('File type "'+g+'" is not allowed. Allowed types: '+o.join(", "),"INVALID_TYPE",m);throw a?.(h),h}if(m.type&&!c.some(h=>{if(h.endsWith("/*")){const b=h.slice(0,-1);return m.type.startsWith(b)}return m.type===h})){const h=new le('File type "'+m.type+'" is not allowed.',"INVALID_TYPE",m);throw a?.(h),h}if(l&&m.type&&g&&!va(m.type,g)){const h=new le('File extension "'+g+'" does not match content type "'+m.type+'".',"VALIDATION_FAILED",m);throw a?.(h),h}}return{accept:f,async add({file:m}){d(m);let g="file";m.type.startsWith("image/")?g="image":(m.type.includes("pdf")||m.type.includes("document")||m.type.includes("text")||m.name.endsWith(".pdf")||m.name.endsWith(".docx")||m.name.endsWith(".txt")||m.name.endsWith(".md")||m.name.endsWith(".csv")||m.name.endsWith(".json"))&&(g="document");const h={id:Ta(),type:g,name:m.name,contentType:m.type,file:m,status:{type:"requires-action",reason:"composer-send"}};return i?.(h),h},async remove(m){s?.(m.id)},async send(m){if(m.type==="image"&&m.file){const g=await new Promise((h,b)=>{const x=new FileReader;x.onload=()=>h(x.result),x.onerror=()=>b(new Error("Failed to read file")),x.readAsDataURL(m.file)});return{...m,status:{type:"complete"},content:[{type:"image",image:g}]}}return{...m,status:{type:"complete"},content:[]}}}}class ja{constructor(){z(this,"current",null);z(this,"listeners",new Set);z(this,"getSnapshot",()=>this.current);z(this,"subscribe",r=>(this.listeners.add(r),()=>this.listeners.delete(r)))}push(r,t){this.current={message:r,code:t,timestamp:Date.now()},this.notify()}clear(){this.current&&(this.current=null,this.notify())}notify(){this.listeners.forEach(r=>r())}}const de=new ja;function Sa({children:e,baseUrl:r,sessionToken:t,isProxyMode:a=!1,mode:i="multiChat",modelId:s,onModelChange:n,ephemeral:c=!1,systemPrompt:o,enableReasoning:l=!1,initialThreadId:f,onError:d,onChatCreated:m,onUserMessage:g,onThreadIdUpdate:h,onChatsLoaded:b,enableAttachments:x=!1,supportsVision:w=!0,onBeforeRequest:C,mockResponseOnBlocked:v}){const _=y.useMemo(()=>new Et(r,t||void 0,a),[r,t,a]),[S,P]=y.useState(s||null);y.useEffect(()=>{s&&P(s)},[s]);const $=y.useCallback(p=>{m?.(p)},[m]),A=y.useCallback((p,R)=>{h?.(p,R)},[h]),L=y.useMemo(()=>Ut(_,{modelId:S||void 0,systemPrompt:o,ephemeral:c,enableReasoning:l,onChatCreated:$,onUserMessage:g,onBeforeRequest:C,mockResponseOnBlocked:v}),[_,S,o,c,l,$,g,C,v]);return i==="singleChat"?u.jsx(Ia,{modelAdapter:L,enableAttachments:x,supportsVision:w,children:e}):u.jsx(Ma,{client:_,modelAdapterOptions:{modelId:S||void 0,systemPrompt:o,ephemeral:c,enableReasoning:l,onChatCreated:$,onUserMessage:g,onBeforeRequest:C,mockResponseOnBlocked:v},initialThreadId:f,onChatsLoaded:b,onThreadIdUpdate:A,onError:d,enableAttachments:x,supportsVision:w,children:e})}function Ia({modelAdapter:e,enableAttachments:r,supportsVision:t=!0,children:a}){const i=y.useMemo(()=>r?Qe({supportsVision:t,onValidationError:n=>{de.push(n.message,n.code)}}):void 0,[r,t]),s=T.useLocalRuntime(e,{adapters:{...i&&{attachments:i}}});return u.jsx(T.AssistantRuntimeProvider,{runtime:s,children:a})}function Ma({client:e,modelAdapterOptions:r,initialThreadId:t,onChatsLoaded:a,onThreadIdUpdate:i,onError:s,enableAttachments:n,supportsVision:c,children:o}){const l=y.useMemo(()=>xa(e,(x,w)=>{i?.(x,w)}),[e,i]),f=y.useCallback((x,w)=>{l.updateRemoteId&&l.updateRemoteId(x,w),i?.(x,w)},[l,i]),d=y.useMemo(()=>({...l,async list(){const x=await l.list();return a?.(),x}}),[l,a]);y.useEffect(()=>{window.__cuadraThreadListAdapter=d,window.__cuadraThreadListRuntime=null},[d]);const m=y.useMemo(()=>Ut(e,{...r,onThreadIdUpdate:f}),[e,r,f]),g=y.useMemo(()=>n?Qe({supportsVision:c,onValidationError:x=>{de.push(x.message,x.code)}}):void 0,[n,c]),h=y.useCallback(()=>T.useLocalRuntime(m,{adapters:{...g&&{attachments:g}}}),[m,g]),b=T.unstable_useRemoteThreadListRuntime({adapter:d,runtimeHook:h});return y.useEffect(()=>{window.__cuadraThreadListRuntime=b},[b]),u.jsx(T.AssistantRuntimeProvider,{runtime:b,children:o})}function gt(e,r){const t=String(e);if(typeof r!="string")throw new TypeError("Expected character");let a=0,i=t.indexOf(r);for(;i!==-1;)a++,i=t.indexOf(r,i+r.length);return a}const ye=Ne(/[A-Za-z]/),Ge=Ne(/[\dA-Za-z]/);function Aa(e){return e!==null&&(e<32||e===127)}function he(e){return e!==null&&e<-2}function W(e){return e!==null&&(e<0||e===32)}function te(e){return e===-2||e===-1||e===32}const Ae=Ne(/\p{P}|\p{S}/u),oe=Ne(/\s/);function Ne(e){return r;function r(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function Na(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}const _e=(function(e){if(e==null)return Ra;if(typeof e=="function")return Pe(e);if(typeof e=="object")return Array.isArray(e)?_a(e):Pa(e);if(typeof e=="string")return Ea(e);throw new Error("Expected function, string, or object as test")});function _a(e){const r=[];let t=-1;for(;++t<e.length;)r[t]=_e(e[t]);return Pe(a);function a(...i){let s=-1;for(;++s<r.length;)if(r[s].apply(this,i))return!0;return!1}}function Pa(e){const r=e;return Pe(t);function t(a){const i=a;let s;for(s in e)if(i[s]!==r[s])return!1;return!0}}function Ea(e){return Pe(r);function r(t){return t&&t.type===e}}function Pe(e){return r;function r(t,a,i){return!!(La(t)&&e.call(this,t,typeof a=="number"?a:void 0,i||void 0))}}function Ra(){return!0}function La(e){return e!==null&&typeof e=="object"&&"type"in e}const zt=[],Da=!0,We=!1,Fa="skip";function $t(e,r,t,a){let i;typeof r=="function"&&typeof t!="function"?(a=t,t=r):i=r;const s=_e(i),n=a?-1:1;c(e,void 0,[])();function c(o,l,f){const d=o&&typeof o=="object"?o:{};if(typeof d.type=="string"){const g=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(m,"name",{value:"node ("+(o.type+(g?"<"+g+">":""))+")"})}return m;function m(){let g=zt,h,b,x;if((!r||s(o,l,f[f.length-1]||void 0))&&(g=Ua(t(o,f)),g[0]===We))return g;if("children"in o&&o.children){const w=o;if(w.children&&g[0]!==Fa)for(b=(a?w.children.length:-1)+n,x=f.concat(w);b>-1&&b<w.children.length;){const C=w.children[b];if(h=c(C,b,x)(),h[0]===We)return h;b=typeof h[1]=="number"?h[1]:b+n}}return g}}}function Ua(e){return Array.isArray(e)?e:typeof e=="number"?[Da,e]:e==null?zt:[e]}function za(e,r,t){const i=_e((t||{}).ignore||[]),s=$a(r);let n=-1;for(;++n<s.length;)$t(e,"text",c);function c(l,f){let d=-1,m;for(;++d<f.length;){const g=f[d],h=m?m.children:void 0;if(i(g,h?h.indexOf(g):void 0,m))return;m=g}if(m)return o(l,f)}function o(l,f){const d=f[f.length-1],m=s[n][0],g=s[n][1];let h=0;const x=d.children.indexOf(l);let w=!1,C=[];m.lastIndex=0;let v=m.exec(l.value);for(;v;){const _=v.index,S={index:v.index,input:v.input,stack:[...f,l]};let P=g(...v,S);if(typeof P=="string"&&(P=P.length>0?{type:"text",value:P}:void 0),P===!1?m.lastIndex=_+1:(h!==_&&C.push({type:"text",value:l.value.slice(h,_)}),Array.isArray(P)?C.push(...P):P&&C.push(P),h=_+v[0].length,w=!0),!m.global)break;v=m.exec(l.value)}return w?(h<l.value.length&&C.push({type:"text",value:l.value.slice(h)}),d.children.splice(x,1,...C)):C=[l],x+C.length}}function $a(e){const r=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const t=!e[0]||Array.isArray(e[0])?e:[e];let a=-1;for(;++a<t.length;){const i=t[a];r.push([Oa(i[0]),Ba(i[1])])}return r}function Oa(e){return typeof e=="string"?new RegExp(Na(e),"g"):e}function Ba(e){return typeof e=="function"?e:function(){return e}}const Fe="phrasing",Ue=["autolink","link","image","label"];function qa(){return{transforms:[Ya],enter:{literalAutolink:Wa,literalAutolinkEmail:ze,literalAutolinkHttp:ze,literalAutolinkWww:ze},exit:{literalAutolink:Ga,literalAutolinkEmail:Qa,literalAutolinkHttp:Ha,literalAutolinkWww:Ka}}}function Va(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Fe,notInConstruct:Ue},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Fe,notInConstruct:Ue},{character:":",before:"[ps]",after:"\\/",inConstruct:Fe,notInConstruct:Ue}]}}function Wa(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function ze(e){this.config.enter.autolinkProtocol.call(this,e)}function Ha(e){this.config.exit.autolinkProtocol.call(this,e)}function Ka(e){this.config.exit.data.call(this,e);const r=this.stack[this.stack.length-1];r.type,r.url="http://"+this.sliceSerialize(e)}function Qa(e){this.config.exit.autolinkEmail.call(this,e)}function Ga(e){this.exit(e)}function Ya(e){za(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,Ja],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,Xa]],{ignore:["link","linkReference"]})}function Ja(e,r,t,a,i){let s="";if(!Ot(i)||(/^w/i.test(r)&&(t=r+t,r="",s="http://"),!Za(t)))return!1;const n=en(t+a);if(!n[0])return!1;const c={type:"link",title:null,url:s+r+n[0],children:[{type:"text",value:r+n[0]}]};return n[1]?[c,{type:"text",value:n[1]}]:c}function Xa(e,r,t,a){return!Ot(a,!0)||/[-\d_]$/.test(t)?!1:{type:"link",title:null,url:"mailto:"+r+"@"+t,children:[{type:"text",value:r+"@"+t}]}}function Za(e){const r=e.split(".");return!(r.length<2||r[r.length-1]&&(/_/.test(r[r.length-1])||!/[a-zA-Z\d]/.test(r[r.length-1]))||r[r.length-2]&&(/_/.test(r[r.length-2])||!/[a-zA-Z\d]/.test(r[r.length-2])))}function en(e){const r=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!r)return[e,void 0];e=e.slice(0,r.index);let t=r[0],a=t.indexOf(")");const i=gt(e,"(");let s=gt(e,")");for(;a!==-1&&i>s;)e+=t.slice(0,a+1),t=t.slice(a+1),a=t.indexOf(")"),s++;return[e,t]}function Ot(e,r){const t=e.input.charCodeAt(e.index-1);return(e.index===0||oe(t)||Ae(t))&&(!r||t!==47)}function we(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}Bt.peek=un;function tn(){this.buffer()}function rn(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function an(){this.buffer()}function nn(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function sn(e){const r=this.resume(),t=this.stack[this.stack.length-1];t.type,t.identifier=we(this.sliceSerialize(e)).toLowerCase(),t.label=r}function on(e){this.exit(e)}function cn(e){const r=this.resume(),t=this.stack[this.stack.length-1];t.type,t.identifier=we(this.sliceSerialize(e)).toLowerCase(),t.label=r}function ln(e){this.exit(e)}function un(){return"["}function Bt(e,r,t,a){const i=t.createTracker(a);let s=i.move("[^");const n=t.enter("footnoteReference"),c=t.enter("reference");return s+=i.move(t.safe(t.associationId(e),{after:"]",before:s})),c(),n(),s+=i.move("]"),s}function dn(){return{enter:{gfmFootnoteCallString:tn,gfmFootnoteCall:rn,gfmFootnoteDefinitionLabelString:an,gfmFootnoteDefinition:nn},exit:{gfmFootnoteCallString:sn,gfmFootnoteCall:on,gfmFootnoteDefinitionLabelString:cn,gfmFootnoteDefinition:ln}}}function hn(e){let r=!1;return e&&e.firstLineBlank&&(r=!0),{handlers:{footnoteDefinition:t,footnoteReference:Bt},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function t(a,i,s,n){const c=s.createTracker(n);let o=c.move("[^");const l=s.enter("footnoteDefinition"),f=s.enter("label");return o+=c.move(s.safe(s.associationId(a),{before:o,after:"]"})),f(),o+=c.move("]:"),a.children&&a.children.length>0&&(c.shift(4),o+=c.move((r?`
|
|
6
|
+
`:" ")+s.indentLines(s.containerFlow(a,c.current()),r?qt:fn))),l(),o}}function fn(e,r,t){return r===0?e:qt(e,r,t)}function qt(e,r,t){return(t?"":" ")+e}const mn=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Vt.peek=bn;function pn(){return{canContainEols:["delete"],enter:{strikethrough:xn},exit:{strikethrough:yn}}}function gn(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:mn}],handlers:{delete:Vt}}}function xn(e){this.enter({type:"delete",children:[]},e)}function yn(e){this.exit(e)}function Vt(e,r,t,a){const i=t.createTracker(a),s=t.enter("strikethrough");let n=i.move("~~");return n+=t.containerPhrasing(e,{...i.current(),before:n,after:"~"}),n+=i.move("~~"),s(),n}function bn(){return"~"}function wn(e){return e.length}function kn(e,r){const t=r||{},a=(t.align||[]).concat(),i=t.stringLength||wn,s=[],n=[],c=[],o=[];let l=0,f=-1;for(;++f<e.length;){const b=[],x=[];let w=-1;for(e[f].length>l&&(l=e[f].length);++w<e[f].length;){const C=Cn(e[f][w]);if(t.alignDelimiters!==!1){const v=i(C);x[w]=v,(o[w]===void 0||v>o[w])&&(o[w]=v)}b.push(C)}n[f]=b,c[f]=x}let d=-1;if(typeof a=="object"&&"length"in a)for(;++d<l;)s[d]=xt(a[d]);else{const b=xt(a);for(;++d<l;)s[d]=b}d=-1;const m=[],g=[];for(;++d<l;){const b=s[d];let x="",w="";b===99?(x=":",w=":"):b===108?x=":":b===114&&(w=":");let C=t.alignDelimiters===!1?1:Math.max(1,o[d]-x.length-w.length);const v=x+"-".repeat(C)+w;t.alignDelimiters!==!1&&(C=x.length+C+w.length,C>o[d]&&(o[d]=C),g[d]=C),m[d]=v}n.splice(1,0,m),c.splice(1,0,g),f=-1;const h=[];for(;++f<n.length;){const b=n[f],x=c[f];d=-1;const w=[];for(;++d<l;){const C=b[d]||"";let v="",_="";if(t.alignDelimiters!==!1){const S=o[d]-(x[d]||0),P=s[d];P===114?v=" ".repeat(S):P===99?S%2?(v=" ".repeat(S/2+.5),_=" ".repeat(S/2-.5)):(v=" ".repeat(S/2),_=v):_=" ".repeat(S)}t.delimiterStart!==!1&&!d&&w.push("|"),t.padding!==!1&&!(t.alignDelimiters===!1&&C==="")&&(t.delimiterStart!==!1||d)&&w.push(" "),t.alignDelimiters!==!1&&w.push(v),w.push(C),t.alignDelimiters!==!1&&w.push(_),t.padding!==!1&&w.push(" "),(t.delimiterEnd!==!1||d!==l-1)&&w.push("|")}h.push(t.delimiterEnd===!1?w.join("").replace(/ +$/,""):w.join(""))}return h.join(`
|
|
7
|
+
`)}function Cn(e){return e==null?"":String(e)}function xt(e){const r=typeof e=="string"?e.codePointAt(0):0;return r===67||r===99?99:r===76||r===108?108:r===82||r===114?114:0}function vn(e,r,t,a){const i=t.enter("blockquote"),s=t.createTracker(a);s.move("> "),s.shift(2);const n=t.indentLines(t.containerFlow(e,s.current()),Tn);return i(),n}function Tn(e,r,t){return">"+(t?"":" ")+e}function jn(e,r){return yt(e,r.inConstruct,!0)&&!yt(e,r.notInConstruct,!1)}function yt(e,r,t){if(typeof r=="string"&&(r=[r]),!r||r.length===0)return t;let a=-1;for(;++a<r.length;)if(e.includes(r[a]))return!0;return!1}function bt(e,r,t,a){let i=-1;for(;++i<t.unsafe.length;)if(t.unsafe[i].character===`
|
|
8
|
+
`&&jn(t.stack,t.unsafe[i]))return/[ \t]/.test(a.before)?"":" ";return`\\
|
|
9
|
+
`}function Sn(e,r){const t=String(e);let a=t.indexOf(r),i=a,s=0,n=0;if(typeof r!="string")throw new TypeError("Expected substring");for(;a!==-1;)a===i?++s>n&&(n=s):s=1,i=a+r.length,a=t.indexOf(r,i);return n}function In(e,r){return!!(r.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function Mn(e){const r=e.options.fence||"`";if(r!=="`"&&r!=="~")throw new Error("Cannot serialize code with `"+r+"` for `options.fence`, expected `` ` `` or `~`");return r}function An(e,r,t,a){const i=Mn(t),s=e.value||"",n=i==="`"?"GraveAccent":"Tilde";if(In(e,t)){const d=t.enter("codeIndented"),m=t.indentLines(s,Nn);return d(),m}const c=t.createTracker(a),o=i.repeat(Math.max(Sn(s,i)+1,3)),l=t.enter("codeFenced");let f=c.move(o);if(e.lang){const d=t.enter(`codeFencedLang${n}`);f+=c.move(t.safe(e.lang,{before:f,after:" ",encode:["`"],...c.current()})),d()}if(e.lang&&e.meta){const d=t.enter(`codeFencedMeta${n}`);f+=c.move(" "),f+=c.move(t.safe(e.meta,{before:f,after:`
|
|
10
10
|
`,encode:["`"],...c.current()})),d()}return f+=c.move(`
|
|
11
11
|
`),s&&(f+=c.move(s+`
|
|
12
|
-
`)),f+=c.move(o),l(),f}function
|
|
13
|
-
`,...o.current()}))),c(),e.title&&(c=t.enter(`title${s}`),l+=o.move(" "+i),l+=o.move(t.safe(e.title,{before:l,after:i,...o.current()})),l+=o.move(i),c()),n(),l}function
|
|
12
|
+
`)),f+=c.move(o),l(),f}function Nn(e,r,t){return(t?"":" ")+e}function Ye(e){const r=e.options.quote||'"';if(r!=='"'&&r!=="'")throw new Error("Cannot serialize title with `"+r+"` for `options.quote`, expected `\"`, or `'`");return r}function _n(e,r,t,a){const i=Ye(t),s=i==='"'?"Quote":"Apostrophe",n=t.enter("definition");let c=t.enter("label");const o=t.createTracker(a);let l=o.move("[");return l+=o.move(t.safe(t.associationId(e),{before:l,after:"]",...o.current()})),l+=o.move("]: "),c(),!e.url||/[\0- \u007F]/.test(e.url)?(c=t.enter("destinationLiteral"),l+=o.move("<"),l+=o.move(t.safe(e.url,{before:l,after:">",...o.current()})),l+=o.move(">")):(c=t.enter("destinationRaw"),l+=o.move(t.safe(e.url,{before:l,after:e.title?" ":`
|
|
13
|
+
`,...o.current()}))),c(),e.title&&(c=t.enter(`title${s}`),l+=o.move(" "+i),l+=o.move(t.safe(e.title,{before:l,after:i,...o.current()})),l+=o.move(i),c()),n(),l}function Pn(e){const r=e.options.emphasis||"*";if(r!=="*"&&r!=="_")throw new Error("Cannot serialize emphasis with `"+r+"` for `options.emphasis`, expected `*`, or `_`");return r}function be(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Ie(e){if(e===null||W(e)||oe(e))return 1;if(Ae(e))return 2}function Me(e,r,t){const a=Ie(e),i=Ie(r);return a===void 0?i===void 0?t==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:a===1?i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Wt.peek=En;function Wt(e,r,t,a){const i=Pn(t),s=t.enter("emphasis"),n=t.createTracker(a),c=n.move(i);let o=n.move(t.containerPhrasing(e,{after:i,before:c,...n.current()}));const l=o.charCodeAt(0),f=Me(a.before.charCodeAt(a.before.length-1),l,i);f.inside&&(o=be(l)+o.slice(1));const d=o.charCodeAt(o.length-1),m=Me(a.after.charCodeAt(0),d,i);m.inside&&(o=o.slice(0,-1)+be(d));const g=n.move(i);return s(),t.attentionEncodeSurroundingInfo={after:m.outside,before:f.outside},c+o+g}function En(e,r,t){return t.options.emphasis||"*"}function Rn(e,r,t,a){let i,s,n;typeof r=="function"&&typeof t!="function"?(s=void 0,n=r,i=t):(s=r,n=t,i=a),$t(e,s,c,i);function c(o,l){const f=l[l.length-1],d=f?f.children.indexOf(o):void 0;return n(o,d,f)}}const Ln={};function Ht(e,r){const t=Ln,a=typeof t.includeImageAlt=="boolean"?t.includeImageAlt:!0,i=typeof t.includeHtml=="boolean"?t.includeHtml:!0;return Kt(e,a,i)}function Kt(e,r,t){if(Dn(e)){if("value"in e)return e.type==="html"&&!t?"":e.value;if(r&&"alt"in e&&e.alt)return e.alt;if("children"in e)return wt(e.children,r,t)}return Array.isArray(e)?wt(e,r,t):""}function wt(e,r,t){const a=[];let i=-1;for(;++i<e.length;)a[i]=Kt(e[i],r,t);return a.join("")}function Dn(e){return!!(e&&typeof e=="object")}function Fn(e,r){let t=!1;return Rn(e,function(a){if("value"in a&&/\r?\n|\r/.test(a.value)||a.type==="break")return t=!0,We}),!!((!e.depth||e.depth<3)&&Ht(e)&&(r.options.setext||t))}function Un(e,r,t,a){const i=Math.max(Math.min(6,e.depth||1),1),s=t.createTracker(a);if(Fn(e,t)){const f=t.enter("headingSetext"),d=t.enter("phrasing"),m=t.containerPhrasing(e,{...s.current(),before:`
|
|
14
14
|
`,after:`
|
|
15
15
|
`});return d(),f(),m+`
|
|
16
16
|
`+(i===1?"=":"-").repeat(m.length-(Math.max(m.lastIndexOf("\r"),m.lastIndexOf(`
|
|
17
17
|
`))+1))}const n="#".repeat(i),c=t.enter("headingAtx"),o=t.enter("phrasing");s.move(n+" ");let l=t.containerPhrasing(e,{before:"# ",after:`
|
|
18
|
-
`,...s.current()});return/^[\t ]/.test(l)&&(l=be(l.charCodeAt(0))+l.slice(1)),l=l?n+" "+l:n,t.options.closeAtx&&(l+=" "+n),o(),c(),l}
|
|
18
|
+
`,...s.current()});return/^[\t ]/.test(l)&&(l=be(l.charCodeAt(0))+l.slice(1)),l=l?n+" "+l:n,t.options.closeAtx&&(l+=" "+n),o(),c(),l}Qt.peek=zn;function Qt(e){return e.value||""}function zn(){return"<"}Gt.peek=$n;function Gt(e,r,t,a){const i=Ye(t),s=i==='"'?"Quote":"Apostrophe",n=t.enter("image");let c=t.enter("label");const o=t.createTracker(a);let l=o.move("![");return l+=o.move(t.safe(e.alt,{before:l,after:"]",...o.current()})),l+=o.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=t.enter("destinationLiteral"),l+=o.move("<"),l+=o.move(t.safe(e.url,{before:l,after:">",...o.current()})),l+=o.move(">")):(c=t.enter("destinationRaw"),l+=o.move(t.safe(e.url,{before:l,after:e.title?" ":")",...o.current()}))),c(),e.title&&(c=t.enter(`title${s}`),l+=o.move(" "+i),l+=o.move(t.safe(e.title,{before:l,after:i,...o.current()})),l+=o.move(i),c()),l+=o.move(")"),n(),l}function $n(){return"!"}Yt.peek=On;function Yt(e,r,t,a){const i=e.referenceType,s=t.enter("imageReference");let n=t.enter("label");const c=t.createTracker(a);let o=c.move("![");const l=t.safe(e.alt,{before:o,after:"]",...c.current()});o+=c.move(l+"]["),n();const f=t.stack;t.stack=[],n=t.enter("reference");const d=t.safe(t.associationId(e),{before:o,after:"]",...c.current()});return n(),t.stack=f,s(),i==="full"||!l||l!==d?o+=c.move(d+"]"):i==="shortcut"?o=o.slice(0,-1):o+=c.move("]"),o}function On(){return"!"}Jt.peek=Bn;function Jt(e,r,t){let a=e.value||"",i="`",s=-1;for(;new RegExp("(^|[^`])"+i+"([^`]|$)").test(a);)i+="`";for(/[^ \r\n]/.test(a)&&(/^[ \r\n]/.test(a)&&/[ \r\n]$/.test(a)||/^`|`$/.test(a))&&(a=" "+a+" ");++s<t.unsafe.length;){const n=t.unsafe[s],c=t.compilePattern(n);let o;if(n.atBreak)for(;o=c.exec(a);){let l=o.index;a.charCodeAt(l)===10&&a.charCodeAt(l-1)===13&&l--,a=a.slice(0,l)+" "+a.slice(o.index+1)}}return i+a+i}function Bn(){return"`"}function Xt(e,r){const t=Ht(e);return!!(!r.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(t===e.url||"mailto:"+t===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}Zt.peek=qn;function Zt(e,r,t,a){const i=Ye(t),s=i==='"'?"Quote":"Apostrophe",n=t.createTracker(a);let c,o;if(Xt(e,t)){const f=t.stack;t.stack=[],c=t.enter("autolink");let d=n.move("<");return d+=n.move(t.containerPhrasing(e,{before:d,after:">",...n.current()})),d+=n.move(">"),c(),t.stack=f,d}c=t.enter("link"),o=t.enter("label");let l=n.move("[");return l+=n.move(t.containerPhrasing(e,{before:l,after:"](",...n.current()})),l+=n.move("]("),o(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(o=t.enter("destinationLiteral"),l+=n.move("<"),l+=n.move(t.safe(e.url,{before:l,after:">",...n.current()})),l+=n.move(">")):(o=t.enter("destinationRaw"),l+=n.move(t.safe(e.url,{before:l,after:e.title?" ":")",...n.current()}))),o(),e.title&&(o=t.enter(`title${s}`),l+=n.move(" "+i),l+=n.move(t.safe(e.title,{before:l,after:i,...n.current()})),l+=n.move(i),o()),l+=n.move(")"),c(),l}function qn(e,r,t){return Xt(e,t)?"<":"["}er.peek=Vn;function er(e,r,t,a){const i=e.referenceType,s=t.enter("linkReference");let n=t.enter("label");const c=t.createTracker(a);let o=c.move("[");const l=t.containerPhrasing(e,{before:o,after:"]",...c.current()});o+=c.move(l+"]["),n();const f=t.stack;t.stack=[],n=t.enter("reference");const d=t.safe(t.associationId(e),{before:o,after:"]",...c.current()});return n(),t.stack=f,s(),i==="full"||!l||l!==d?o+=c.move(d+"]"):i==="shortcut"?o=o.slice(0,-1):o+=c.move("]"),o}function Vn(){return"["}function Je(e){const r=e.options.bullet||"*";if(r!=="*"&&r!=="+"&&r!=="-")throw new Error("Cannot serialize items with `"+r+"` for `options.bullet`, expected `*`, `+`, or `-`");return r}function Wn(e){const r=Je(e),t=e.options.bulletOther;if(!t)return r==="*"?"-":"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(t===r)throw new Error("Expected `bullet` (`"+r+"`) and `bulletOther` (`"+t+"`) to be different");return t}function Hn(e){const r=e.options.bulletOrdered||".";if(r!=="."&&r!==")")throw new Error("Cannot serialize items with `"+r+"` for `options.bulletOrdered`, expected `.` or `)`");return r}function tr(e){const r=e.options.rule||"*";if(r!=="*"&&r!=="-"&&r!=="_")throw new Error("Cannot serialize rules with `"+r+"` for `options.rule`, expected `*`, `-`, or `_`");return r}function Kn(e,r,t,a){const i=t.enter("list"),s=t.bulletCurrent;let n=e.ordered?Hn(t):Je(t);const c=e.ordered?n==="."?")":".":Wn(t);let o=r&&t.bulletLastUsed?n===t.bulletLastUsed:!1;if(!e.ordered){const f=e.children?e.children[0]:void 0;if((n==="*"||n==="-")&&f&&(!f.children||!f.children[0])&&t.stack[t.stack.length-1]==="list"&&t.stack[t.stack.length-2]==="listItem"&&t.stack[t.stack.length-3]==="list"&&t.stack[t.stack.length-4]==="listItem"&&t.indexStack[t.indexStack.length-1]===0&&t.indexStack[t.indexStack.length-2]===0&&t.indexStack[t.indexStack.length-3]===0&&(o=!0),tr(t)===n&&f){let d=-1;for(;++d<e.children.length;){const m=e.children[d];if(m&&m.type==="listItem"&&m.children&&m.children[0]&&m.children[0].type==="thematicBreak"){o=!0;break}}}}o&&(n=c),t.bulletCurrent=n;const l=t.containerFlow(e,a);return t.bulletLastUsed=n,t.bulletCurrent=s,i(),l}function Qn(e){const r=e.options.listItemIndent||"one";if(r!=="tab"&&r!=="one"&&r!=="mixed")throw new Error("Cannot serialize items with `"+r+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return r}function Gn(e,r,t,a){const i=Qn(t);let s=t.bulletCurrent||Je(t);r&&r.type==="list"&&r.ordered&&(s=(typeof r.start=="number"&&r.start>-1?r.start:1)+(t.options.incrementListMarker===!1?0:r.children.indexOf(e))+s);let n=s.length+1;(i==="tab"||i==="mixed"&&(r&&r.type==="list"&&r.spread||e.spread))&&(n=Math.ceil(n/4)*4);const c=t.createTracker(a);c.move(s+" ".repeat(n-s.length)),c.shift(n);const o=t.enter("listItem"),l=t.indentLines(t.containerFlow(e,c.current()),f);return o(),l;function f(d,m,g){return m?(g?"":" ".repeat(n))+d:(g?s:s+" ".repeat(n-s.length))+d}}function Yn(e,r,t,a){const i=t.enter("paragraph"),s=t.enter("phrasing"),n=t.containerPhrasing(e,a);return s(),i(),n}const Jn=_e(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function Xn(e,r,t,a){return(e.children.some(function(n){return Jn(n)})?t.containerPhrasing:t.containerFlow).call(t,e,a)}function Zn(e){const r=e.options.strong||"*";if(r!=="*"&&r!=="_")throw new Error("Cannot serialize strong with `"+r+"` for `options.strong`, expected `*`, or `_`");return r}rr.peek=ei;function rr(e,r,t,a){const i=Zn(t),s=t.enter("strong"),n=t.createTracker(a),c=n.move(i+i);let o=n.move(t.containerPhrasing(e,{after:i,before:c,...n.current()}));const l=o.charCodeAt(0),f=Me(a.before.charCodeAt(a.before.length-1),l,i);f.inside&&(o=be(l)+o.slice(1));const d=o.charCodeAt(o.length-1),m=Me(a.after.charCodeAt(0),d,i);m.inside&&(o=o.slice(0,-1)+be(d));const g=n.move(i+i);return s(),t.attentionEncodeSurroundingInfo={after:m.outside,before:f.outside},c+o+g}function ei(e,r,t){return t.options.strong||"*"}function ti(e,r,t,a){return t.safe(e.value,a)}function ri(e){const r=e.options.ruleRepetition||3;if(r<3)throw new Error("Cannot serialize rules with repetition `"+r+"` for `options.ruleRepetition`, expected `3` or more");return r}function ai(e,r,t){const a=(tr(t)+(t.options.ruleSpaces?" ":"")).repeat(ri(t));return t.options.ruleSpaces?a.slice(0,-1):a}const ar={blockquote:vn,break:bt,code:An,definition:_n,emphasis:Wt,hardBreak:bt,heading:Un,html:Qt,image:Gt,imageReference:Yt,inlineCode:Jt,link:Zt,linkReference:er,list:Kn,listItem:Gn,paragraph:Yn,root:Xn,strong:rr,text:ti,thematicBreak:ai};function ni(){return{enter:{table:ii,tableData:kt,tableHeader:kt,tableRow:oi},exit:{codeText:ci,table:si,tableData:$e,tableHeader:$e,tableRow:$e}}}function ii(e){const r=e._align;this.enter({type:"table",align:r.map(function(t){return t==="none"?null:t}),children:[]},e),this.data.inTable=!0}function si(e){this.exit(e),this.data.inTable=void 0}function oi(e){this.enter({type:"tableRow",children:[]},e)}function $e(e){this.exit(e)}function kt(e){this.enter({type:"tableCell",children:[]},e)}function ci(e){let r=this.resume();this.data.inTable&&(r=r.replace(/\\([\\|])/g,li));const t=this.stack[this.stack.length-1];t.type,t.value=r,this.exit(e)}function li(e,r){return r==="|"?r:e}function ui(e){const r=e||{},t=r.tableCellPadding,a=r.tablePipeAlign,i=r.stringLength,s=t?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
19
19
|
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:m,table:n,tableCell:o,tableRow:c}};function n(g,h,b,x){return l(f(g,b,x),g.align)}function c(g,h,b,x){const w=d(g,b,x),C=l([w]);return C.slice(0,C.indexOf(`
|
|
20
|
-
`))}function o(g,h,b,x){const w=b.enter("tableCell"),C=b.enter("phrasing"),v=b.containerPhrasing(g,{...x,before:s,after:s});return C(),w(),v}function l(g,h){return wn(g,{align:h,alignDelimiters:a,padding:t,stringLength:i})}function f(g,h,b){const x=g.children;let w=-1;const C=[],v=h.enter("table");for(;++w<x.length;)C[w]=d(x[w],h,b);return v(),C}function d(g,h,b){const x=g.children;let w=-1;const C=[],v=h.enter("tableRow");for(;++w<x.length;)C[w]=o(x[w],g,h,b);return v(),C}function m(g,h,b){let x=rr.inlineCode(g,h,b);return b.stack.includes("tableCell")&&(x=x.replace(/\|/g,"\\$&")),x}}function ui(){return{exit:{taskListCheckValueChecked:Ct,taskListCheckValueUnchecked:Ct,paragraph:hi}}}function di(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:fi}}}function Ct(e){const r=this.stack[this.stack.length-2];r.type,r.checked=e.type==="taskListCheckValueChecked"}function hi(e){const r=this.stack[this.stack.length-2];if(r&&r.type==="listItem"&&typeof r.checked=="boolean"){const t=this.stack[this.stack.length-1];t.type;const a=t.children[0];if(a&&a.type==="text"){const i=r.children;let s=-1,n;for(;++s<i.length;){const c=i[s];if(c.type==="paragraph"){n=c;break}}n===t&&(a.value=a.value.slice(1),a.value.length===0?t.children.shift():t.position&&a.position&&typeof a.position.start.offset=="number"&&(a.position.start.column++,a.position.start.offset++,t.position.start=Object.assign({},a.position.start)))}}this.exit(e)}function fi(e,r,t,a){const i=e.children[0],s=typeof e.checked=="boolean"&&i&&i.type==="paragraph",n="["+(e.checked?"x":" ")+"] ",c=t.createTracker(a);s&&c.move(n);let o=rr.listItem(e,r,t,{...a,...c.current()});return s&&(o=o.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,l)),o;function l(f){return f+n}}function mi(){return[Ba(),un(),mn(),ai(),ui()]}function pi(e){return{extensions:[qa(),dn(e),pn(),li(e),di()]}}function je(e,r,t,a){const i=e.length;let s=0,n;if(r<0?r=-r>i?0:i+r:r=r>i?i:r,t=t>0?t:0,a.length<1e4)n=Array.from(a),n.unshift(r,t),e.splice(...n);else for(t&&e.splice(r,t);s<a.length;)n=a.slice(s,s+1e4),n.unshift(r,0),e.splice(...n),s+=1e4,r+=1e4}const vt={}.hasOwnProperty;function gi(e){const r={};let t=-1;for(;++t<e.length;)xi(r,e[t]);return r}function xi(e,r){let t;for(t in r){const i=(vt.call(e,t)?e[t]:void 0)||(e[t]={}),s=r[t];let n;if(s)for(n in s){vt.call(i,n)||(i[n]=[]);const c=s[n];yi(i[n],Array.isArray(c)?c:c?[c]:[])}}}function yi(e,r){let t=-1;const a=[];for(;++t<r.length;)(r[t].add==="after"?e:a).push(r[t]);je(e,0,0,a)}const bi={tokenize:ji,partial:!0},ar={tokenize:Si,partial:!0},nr={tokenize:Ii,partial:!0},ir={tokenize:Mi,partial:!0},wi={tokenize:Ai,partial:!0},sr={name:"wwwAutolink",tokenize:vi,previous:cr},or={name:"protocolAutolink",tokenize:Ti,previous:lr},ae={name:"emailAutolink",tokenize:Ci,previous:ur},Q={};function ki(){return{text:Q}}let se=48;for(;se<123;)Q[se]=ae,se++,se===58?se=65:se===91&&(se=97);Q[43]=ae;Q[45]=ae;Q[46]=ae;Q[95]=ae;Q[72]=[ae,or];Q[104]=[ae,or];Q[87]=[ae,sr];Q[119]=[ae,sr];function Ci(e,r,t){const a=this;let i,s;return n;function n(d){return!He(d)||!ur.call(a,a.previous)||Xe(a.events)?t(d):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(d))}function c(d){return He(d)?(e.consume(d),c):d===64?(e.consume(d),o):t(d)}function o(d){return d===46?e.check(wi,f,l)(d):d===45||d===95||Ge(d)?(s=!0,e.consume(d),o):f(d)}function l(d){return e.consume(d),i=!0,o}function f(d){return s&&i&&ye(a.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),r(d)):t(d)}}function vi(e,r,t){const a=this;return i;function i(n){return n!==87&&n!==119||!cr.call(a,a.previous)||Xe(a.events)?t(n):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(bi,e.attempt(ar,e.attempt(nr,s),t),t)(n))}function s(n){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),r(n)}}function Ti(e,r,t){const a=this;let i="",s=!1;return n;function n(d){return(d===72||d===104)&&lr.call(a,a.previous)&&!Xe(a.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),i+=String.fromCodePoint(d),e.consume(d),c):t(d)}function c(d){if(ye(d)&&i.length<5)return i+=String.fromCodePoint(d),e.consume(d),c;if(d===58){const m=i.toLowerCase();if(m==="http"||m==="https")return e.consume(d),o}return t(d)}function o(d){return d===47?(e.consume(d),s?l:(s=!0,o)):t(d)}function l(d){return d===null||Ma(d)||V(d)||oe(d)||Ae(d)?t(d):e.attempt(ar,e.attempt(nr,f),t)(d)}function f(d){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),r(d)}}function ji(e,r,t){let a=0;return i;function i(n){return(n===87||n===119)&&a<3?(a++,e.consume(n),i):n===46&&a===3?(e.consume(n),s):t(n)}function s(n){return n===null?t(n):r(n)}}function Si(e,r,t){let a,i,s;return n;function n(l){return l===46||l===95?e.check(ir,o,c)(l):l===null||V(l)||oe(l)||l!==45&&Ae(l)?o(l):(s=!0,e.consume(l),n)}function c(l){return l===95?a=!0:(i=a,a=void 0),e.consume(l),n}function o(l){return i||a||!s?t(l):r(l)}}function Ii(e,r){let t=0,a=0;return i;function i(n){return n===40?(t++,e.consume(n),i):n===41&&a<t?s(n):n===33||n===34||n===38||n===39||n===41||n===42||n===44||n===46||n===58||n===59||n===60||n===63||n===93||n===95||n===126?e.check(ir,r,s)(n):n===null||V(n)||oe(n)?r(n):(e.consume(n),i)}function s(n){return n===41&&a++,e.consume(n),i}}function Mi(e,r,t){return a;function a(c){return c===33||c===34||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===63||c===95||c===126?(e.consume(c),a):c===38?(e.consume(c),s):c===93?(e.consume(c),i):c===60||c===null||V(c)||oe(c)?r(c):t(c)}function i(c){return c===null||c===40||c===91||V(c)||oe(c)?r(c):a(c)}function s(c){return ye(c)?n(c):t(c)}function n(c){return c===59?(e.consume(c),a):ye(c)?(e.consume(c),n):t(c)}}function Ai(e,r,t){return a;function a(s){return e.consume(s),i}function i(s){return Ge(s)?t(s):r(s)}}function cr(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||V(e)}function lr(e){return!ye(e)}function ur(e){return!(e===47||He(e))}function He(e){return e===43||e===45||e===46||e===95||Ge(e)}function Xe(e){let r=e.length,t=!1;for(;r--;){const a=e[r][1];if((a.type==="labelLink"||a.type==="labelImage")&&!a._balanced){t=!0;break}if(a._gfmAutolinkLiteralWalkedInto){t=!1;break}}return e.length>0&&!t&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),t}function Ni(e,r,t){const a=[];let i=-1;for(;++i<e.length;){const s=e[i].resolveAll;s&&!a.includes(s)&&(r=s(r,t),a.push(s))}return r}function re(e,r,t,a){const i=a?a-1:Number.POSITIVE_INFINITY;let s=0;return n;function n(o){return te(o)?(e.enter(t),c(o)):r(o)}function c(o){return te(o)&&s++<i?(e.consume(o),c):(e.exit(t),r(o))}}const _i={partial:!0,tokenize:Pi};function Pi(e,r,t){return a;function a(s){return te(s)?re(e,i,"linePrefix")(s):i(s)}function i(s){return s===null||he(s)?r(s):t(s)}}const Ei={tokenize:Oi,partial:!0};function Ri(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Ui,continuation:{tokenize:zi},exit:$i}},text:{91:{name:"gfmFootnoteCall",tokenize:Fi},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Li,resolveTo:Di}}}}function Li(e,r,t){const a=this;let i=a.events.length;const s=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let n;for(;i--;){const o=a.events[i][1];if(o.type==="labelImage"){n=o;break}if(o.type==="gfmFootnoteCall"||o.type==="labelLink"||o.type==="label"||o.type==="image"||o.type==="link")break}return c;function c(o){if(!n||!n._balanced)return t(o);const l=we(a.sliceSerialize({start:n.end,end:a.now()}));return l.codePointAt(0)!==94||!s.includes(l.slice(1))?t(o):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(o),e.exit("gfmFootnoteCallLabelMarker"),r(o))}}function Di(e,r){let t=e.length;for(;t--;)if(e[t][1].type==="labelImage"&&e[t][0]==="enter"){e[t][1];break}e[t+1][1].type="data",e[t+3][1].type="gfmFootnoteCallLabelMarker";const a={type:"gfmFootnoteCall",start:Object.assign({},e[t+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:"gfmFootnoteCallMarker",start:Object.assign({},e[t+3][1].end),end:Object.assign({},e[t+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;const s={type:"gfmFootnoteCallString",start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},n={type:"chunkString",contentType:"string",start:Object.assign({},s.start),end:Object.assign({},s.end)},c=[e[t+1],e[t+2],["enter",a,r],e[t+3],e[t+4],["enter",i,r],["exit",i,r],["enter",s,r],["enter",n,r],["exit",n,r],["exit",s,r],e[e.length-2],e[e.length-1],["exit",a,r]];return e.splice(t,e.length-t+1,...c),e}function Fi(e,r,t){const a=this,i=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let s=0,n;return c;function c(d){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),o}function o(d){return d!==94?t(d):(e.enter("gfmFootnoteCallMarker"),e.consume(d),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",l)}function l(d){if(s>999||d===93&&!n||d===null||d===91||V(d))return t(d);if(d===93){e.exit("chunkString");const m=e.exit("gfmFootnoteCallString");return i.includes(we(a.sliceSerialize(m)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),r):t(d)}return V(d)||(n=!0),s++,e.consume(d),d===92?f:l}function f(d){return d===91||d===92||d===93?(e.consume(d),s++,l):l(d)}}function Ui(e,r,t){const a=this,i=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let s,n=0,c;return o;function o(h){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(h),e.exit("gfmFootnoteDefinitionLabelMarker"),l}function l(h){return h===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(h),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",f):t(h)}function f(h){if(n>999||h===93&&!c||h===null||h===91||V(h))return t(h);if(h===93){e.exit("chunkString");const b=e.exit("gfmFootnoteDefinitionLabelString");return s=we(a.sliceSerialize(b)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(h),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),m}return V(h)||(c=!0),n++,e.consume(h),h===92?d:f}function d(h){return h===91||h===92||h===93?(e.consume(h),n++,f):f(h)}function m(h){return h===58?(e.enter("definitionMarker"),e.consume(h),e.exit("definitionMarker"),i.includes(s)||i.push(s),re(e,g,"gfmFootnoteDefinitionWhitespace")):t(h)}function g(h){return r(h)}}function zi(e,r,t){return e.check(_i,r,e.attempt(Ei,r,t))}function $i(e){e.exit("gfmFootnoteDefinition")}function Oi(e,r,t){const a=this;return re(e,i,"gfmFootnoteDefinitionIndent",5);function i(s){const n=a.events[a.events.length-1];return n&&n[1].type==="gfmFootnoteDefinitionIndent"&&n[2].sliceSerialize(n[1],!0).length===4?r(s):t(s)}}function Bi(e){let t=(e||{}).singleTilde;const a={name:"strikethrough",tokenize:s,resolveAll:i};return t==null&&(t=!0),{text:{126:a},insideSpan:{null:[a]},attentionMarkers:{null:[126]}};function i(n,c){let o=-1;for(;++o<n.length;)if(n[o][0]==="enter"&&n[o][1].type==="strikethroughSequenceTemporary"&&n[o][1]._close){let l=o;for(;l--;)if(n[l][0]==="exit"&&n[l][1].type==="strikethroughSequenceTemporary"&&n[l][1]._open&&n[o][1].end.offset-n[o][1].start.offset===n[l][1].end.offset-n[l][1].start.offset){n[o][1].type="strikethroughSequence",n[l][1].type="strikethroughSequence";const f={type:"strikethrough",start:Object.assign({},n[l][1].start),end:Object.assign({},n[o][1].end)},d={type:"strikethroughText",start:Object.assign({},n[l][1].end),end:Object.assign({},n[o][1].start)},m=[["enter",f,c],["enter",n[l][1],c],["exit",n[l][1],c],["enter",d,c]],g=c.parser.constructs.insideSpan.null;g&&je(m,m.length,0,Ni(g,n.slice(l+1,o),c)),je(m,m.length,0,[["exit",d,c],["enter",n[o][1],c],["exit",n[o][1],c],["exit",f,c]]),je(n,l-1,o-l+3,m),o=l+m.length-2;break}}for(o=-1;++o<n.length;)n[o][1].type==="strikethroughSequenceTemporary"&&(n[o][1].type="data");return n}function s(n,c,o){const l=this.previous,f=this.events;let d=0;return m;function m(h){return l===126&&f[f.length-1][1].type!=="characterEscape"?o(h):(n.enter("strikethroughSequenceTemporary"),g(h))}function g(h){const b=Ie(l);if(h===126)return d>1?o(h):(n.consume(h),d++,g);if(d<2&&!t)return o(h);const x=n.exit("strikethroughSequenceTemporary"),w=Ie(h);return x._open=!w||w===2&&!!b,x._close=!b||b===2&&!!w,c(h)}}}class qi{constructor(){this.map=[]}add(r,t,a){Wi(this,r,t,a)}consume(r){if(this.map.sort(function(s,n){return s[0]-n[0]}),this.map.length===0)return;let t=this.map.length;const a=[];for(;t>0;)t-=1,a.push(r.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),r.length=this.map[t][0];a.push(r.slice()),r.length=0;let i=a.pop();for(;i;){for(const s of i)r.push(s);i=a.pop()}this.map.length=0}}function Wi(e,r,t,a){let i=0;if(!(t===0&&a.length===0)){for(;i<e.map.length;){if(e.map[i][0]===r){e.map[i][1]+=t,e.map[i][2].push(...a);return}i+=1}e.map.push([r,t,a])}}function Vi(e,r){let t=!1;const a=[];for(;r<e.length;){const i=e[r];if(t){if(i[0]==="enter")i[1].type==="tableContent"&&a.push(e[r+1][1].type==="tableDelimiterMarker"?"left":"none");else if(i[1].type==="tableContent"){if(e[r-1][1].type==="tableDelimiterMarker"){const s=a.length-1;a[s]=a[s]==="left"?"center":"right"}}else if(i[1].type==="tableDelimiterRow")break}else i[0]==="enter"&&i[1].type==="tableDelimiterRow"&&(t=!0);r+=1}return a}function Hi(){return{flow:{null:{name:"table",tokenize:Ki,resolveAll:Qi}}}}function Ki(e,r,t){const a=this;let i=0,s=0,n;return c;function c(p){let R=a.events.length-1;for(;R>-1;){const I=a.events[R][1].type;if(I==="lineEnding"||I==="linePrefix")R--;else break}const G=R>-1?a.events[R][1].type:null,H=G==="tableHead"||G==="tableRow"?P:o;return H===P&&a.parser.lazy[a.now().line]?t(p):H(p)}function o(p){return e.enter("tableHead"),e.enter("tableRow"),l(p)}function l(p){return p===124||(n=!0,s+=1),f(p)}function f(p){return p===null?t(p):he(p)?s>1?(s=0,a.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),g):t(p):te(p)?re(e,f,"whitespace")(p):(s+=1,n&&(n=!1,i+=1),p===124?(e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),n=!0,f):(e.enter("data"),d(p)))}function d(p){return p===null||p===124||V(p)?(e.exit("data"),f(p)):(e.consume(p),p===92?m:d)}function m(p){return p===92||p===124?(e.consume(p),d):d(p)}function g(p){return a.interrupt=!1,a.parser.lazy[a.now().line]?t(p):(e.enter("tableDelimiterRow"),n=!1,te(p)?re(e,h,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(p):h(p))}function h(p){return p===45||p===58?x(p):p===124?(n=!0,e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),b):S(p)}function b(p){return te(p)?re(e,x,"whitespace")(p):x(p)}function x(p){return p===58?(s+=1,n=!0,e.enter("tableDelimiterMarker"),e.consume(p),e.exit("tableDelimiterMarker"),w):p===45?(s+=1,w(p)):p===null||he(p)?_(p):S(p)}function w(p){return p===45?(e.enter("tableDelimiterFiller"),C(p)):S(p)}function C(p){return p===45?(e.consume(p),C):p===58?(n=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(p),e.exit("tableDelimiterMarker"),v):(e.exit("tableDelimiterFiller"),v(p))}function v(p){return te(p)?re(e,_,"whitespace")(p):_(p)}function _(p){return p===124?h(p):p===null||he(p)?!n||i!==s?S(p):(e.exit("tableDelimiterRow"),e.exit("tableHead"),r(p)):S(p)}function S(p){return t(p)}function P(p){return e.enter("tableRow"),$(p)}function $(p){return p===124?(e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),$):p===null||he(p)?(e.exit("tableRow"),r(p)):te(p)?re(e,$,"whitespace")(p):(e.enter("data"),A(p))}function A(p){return p===null||p===124||V(p)?(e.exit("data"),$(p)):(e.consume(p),p===92?L:A)}function L(p){return p===92||p===124?(e.consume(p),A):A(p)}}function Qi(e,r){let t=-1,a=!0,i=0,s=[0,0,0,0],n=[0,0,0,0],c=!1,o=0,l,f,d;const m=new qi;for(;++t<e.length;){const g=e[t],h=g[1];g[0]==="enter"?h.type==="tableHead"?(c=!1,o!==0&&(Tt(m,r,o,l,f),f=void 0,o=0),l={type:"table",start:Object.assign({},h.start),end:Object.assign({},h.end)},m.add(t,0,[["enter",l,r]])):h.type==="tableRow"||h.type==="tableDelimiterRow"?(a=!0,d=void 0,s=[0,0,0,0],n=[0,t+1,0,0],c&&(c=!1,f={type:"tableBody",start:Object.assign({},h.start),end:Object.assign({},h.end)},m.add(t,0,[["enter",f,r]])),i=h.type==="tableDelimiterRow"?2:f?3:1):i&&(h.type==="data"||h.type==="tableDelimiterMarker"||h.type==="tableDelimiterFiller")?(a=!1,n[2]===0&&(s[1]!==0&&(n[0]=n[1],d=ve(m,r,s,i,void 0,d),s=[0,0,0,0]),n[2]=t)):h.type==="tableCellDivider"&&(a?a=!1:(s[1]!==0&&(n[0]=n[1],d=ve(m,r,s,i,void 0,d)),s=n,n=[s[1],t,0,0])):h.type==="tableHead"?(c=!0,o=t):h.type==="tableRow"||h.type==="tableDelimiterRow"?(o=t,s[1]!==0?(n[0]=n[1],d=ve(m,r,s,i,t,d)):n[1]!==0&&(d=ve(m,r,n,i,t,d)),i=0):i&&(h.type==="data"||h.type==="tableDelimiterMarker"||h.type==="tableDelimiterFiller")&&(n[3]=t)}for(o!==0&&Tt(m,r,o,l,f),m.consume(r.events),t=-1;++t<r.events.length;){const g=r.events[t];g[0]==="enter"&&g[1].type==="table"&&(g[1]._align=Vi(r.events,t))}return e}function ve(e,r,t,a,i,s){const n=a===1?"tableHeader":a===2?"tableDelimiter":"tableData",c="tableContent";t[0]!==0&&(s.end=Object.assign({},ue(r.events,t[0])),e.add(t[0],0,[["exit",s,r]]));const o=ue(r.events,t[1]);if(s={type:n,start:Object.assign({},o),end:Object.assign({},o)},e.add(t[1],0,[["enter",s,r]]),t[2]!==0){const l=ue(r.events,t[2]),f=ue(r.events,t[3]),d={type:c,start:Object.assign({},l),end:Object.assign({},f)};if(e.add(t[2],0,[["enter",d,r]]),a!==2){const m=r.events[t[2]],g=r.events[t[3]];if(m[1].end=Object.assign({},g[1].end),m[1].type="chunkText",m[1].contentType="text",t[3]>t[2]+1){const h=t[2]+1,b=t[3]-t[2]-1;e.add(h,b,[])}}e.add(t[3]+1,0,[["exit",d,r]])}return i!==void 0&&(s.end=Object.assign({},ue(r.events,i)),e.add(i,0,[["exit",s,r]]),s=void 0),s}function Tt(e,r,t,a,i){const s=[],n=ue(r.events,t);i&&(i.end=Object.assign({},n),s.push(["exit",i,r])),a.end=Object.assign({},n),s.push(["exit",a,r]),e.add(t+1,0,s)}function ue(e,r){const t=e[r],a=t[0]==="enter"?"start":"end";return t[1][a]}const Gi={name:"tasklistCheck",tokenize:Ji};function Yi(){return{text:{91:Gi}}}function Ji(e,r,t){const a=this;return i;function i(o){return a.previous!==null||!a._gfmTasklistFirstContentOfListItem?t(o):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(o),e.exit("taskListCheckMarker"),s)}function s(o){return V(o)?(e.enter("taskListCheckValueUnchecked"),e.consume(o),e.exit("taskListCheckValueUnchecked"),n):o===88||o===120?(e.enter("taskListCheckValueChecked"),e.consume(o),e.exit("taskListCheckValueChecked"),n):t(o)}function n(o){return o===93?(e.enter("taskListCheckMarker"),e.consume(o),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):t(o)}function c(o){return he(o)?r(o):te(o)?e.check({tokenize:Xi},r,t)(o):t(o)}}function Xi(e,r,t){return re(e,a,"whitespace");function a(i){return i===null?t(i):r(i)}}function Zi(e){return gi([ki(),Ri(),Bi(e),Hi(),Yi()])}const es={};function ts(e){const r=this,t=e||es,a=r.data(),i=a.micromarkExtensions||(a.micromarkExtensions=[]),s=a.fromMarkdownExtensions||(a.fromMarkdownExtensions=[]),n=a.toMarkdownExtensions||(a.toMarkdownExtensions=[]);i.push(Zi(t)),s.push(mi()),n.push(pi(t))}function O(...e){return e.filter(Boolean).join(" ")}const rs=({content:e})=>u.jsx(qe.MarkdownTextPrimitive,{remarkPlugins:[ts],className:"cuadra-aui-md",components:is,children:e}),Ze=y.memo(rs),as=({language:e,code:r})=>{const{isCopied:t,copyToClipboard:a}=ns(),i=()=>{!r||t||a(r)};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:i,className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-muted cuadra-transition-colors","aria-label":"Copy code",children:[!t&&u.jsx(Rr,{className:"cuadra-h-4 cuadra-w-4"}),t&&u.jsx(St,{className:"cuadra-h-4 cuadra-w-4"})]})]})},ns=({copiedDuration:e=3e3}={})=>{const[r,t]=y.useState(!1);return{isCopied:r,copyToClipboard:i=>{i&&navigator.clipboard.writeText(i).then(()=>{t(!0),setTimeout(()=>t(!1),e)})}}},is=qe.unstable_memoizeMarkdownComponents({h1:({className:e,...r})=>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),...r}),h2:({className:e,...r})=>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),...r}),h3:({className:e,...r})=>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),...r}),h4:({className:e,...r})=>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),...r}),h5:({className:e,...r})=>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),...r}),h6:({className:e,...r})=>u.jsx("h6",{className:O("cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand",e),...r}),p:({className:e,...r})=>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),...r}),a:({className:e,...r})=>u.jsx("a",{className:O("cuadra-text-primary cuadra-font-medium cuadra-underline cuadra-underline-offset-4 font-brand",e),...r}),blockquote:({className:e,...r})=>u.jsx("blockquote",{className:O("cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand",e),...r}),ul:({className:e,...r})=>u.jsx("ul",{className:O("cuadra-my-5 cuadra-ml-6 cuadra-list-disc [&>li]:cuadra-mt-2 font-brand",e),...r}),ol:({className:e,...r})=>u.jsx("ol",{className:O("cuadra-my-5 cuadra-ml-6 cuadra-list-decimal [&>li]:cuadra-mt-2 font-brand",e),...r}),hr:({className:e,...r})=>u.jsx("hr",{className:O("cuadra-my-5 cuadra-border-b",e),...r}),table:({className:e,...r})=>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),...r}),th:({className:e,...r})=>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),...r}),td:({className:e,...r})=>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),...r}),tr:({className:e,...r})=>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),...r}),sup:({className:e,...r})=>u.jsx("sup",{className:O("[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand",e),...r}),pre:({className:e,...r})=>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),...r}),code:function({className:r,...t}){const a=qe.useIsMarkdownCodeBlock();return u.jsx("code",{className:O(!a&&"cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand",r),...t})},CodeHeader:as});function et({className:e="",variant:r="default",...t}){const a="cuadra-inline-flex cuadra-items-center cuadra-rounded-md cuadra-px-3 cuadra-py-1.5 cuadra-text-xs cuadra-font-medium font-brand",i={default:"cuadra-border cuadra-border-border cuadra-bg-muted cuadra-text-muted-foreground",subtle:"cuadra-border cuadra-border-border/50 cuadra-bg-muted/50 cuadra-text-muted-foreground",outline:"cuadra-border cuadra-border-border cuadra-bg-background cuadra-text-foreground",ghost:"cuadra-text-muted-foreground"};return u.jsx("div",{className:`${a} ${i[r]||i.default} ${e}`,...t})}function ss(e){const r=new Map;for(const t of e){const a=r.get(t.filename);(!a||t.score>a.score)&&r.set(t.filename,t)}return Array.from(r.values()).sort((t,a)=>a.score-t.score)}function dr({sources:e,maxVisible:r=3}){if(!e||e.length===0)return null;const t=ss(e),a=t.slice(0,r),i=t.length-r;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,n)=>u.jsx(cs,{source:s},s.sourceId||n)),i>0&&u.jsxs(et,{variant:"subtle",children:["+",i," more"]})]})]})}function os(e){switch(e.split(".").pop()?.toLowerCase()){case"csv":case"xlsx":case"xls":return Fr;case"md":case"txt":return $r;default:return It}}function cs({source:e}){const{filename:r,score:t}=e,a=os(r);return u.jsxs(et,{className:"cuadra-gap-2 cuadra-cursor-default",title:t<1?`${Math.round(t*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:r}),t<1&&t>0&&u.jsxs("span",{className:"cuadra-opacity-50 cuadra-text-[10px] cuadra-tabular-nums",children:[Math.round(t*100),"%"]})]})}const ls=y.forwardRef(function({welcomeTitle:r="What shall we explore today?",extraTopPadding:t,suggestions:a,inputPlaceholder:i="Reply...",enableAttachments:s=!1,preMadeResponseDelay:n=1e3,streamingSpeed:c=50,safeArea:o=!1,composerBorder:l=!1,models:f,selectedModelId:d,onModelChange:m,showChatHeader:g=!1},h){const b=T.useThreadRuntime(),x=T.useAssistantApi(),[w,C]=y.useState(!1),[v,_]=y.useState(null),[S,P]=y.useState(!1),$=y.useSyncExternalStore(de.subscribe,de.getSnapshot);y.useEffect(()=>{if($){const I=setTimeout(()=>de.clear(),4e3);return()=>clearTimeout(I)}},[$]);const A=T.useThread(I=>{const D=I.messages;return!D||D.length===0}),L=A&&!w,p=y.useCallback((I,D,B)=>{if(!S)try{const k=B?.streamingSpeed??c,j=B?.delay??n;Dt(I,D,k,j),x.composer().setText(I),setTimeout(()=>{x.composer().send()},10)}catch{}},[S,c,n,x]),R=y.useCallback(I=>{try{x.composer().setText(I),setTimeout(()=>{x.composer().send()},10)}catch{}},[x]),G=y.useCallback(async I=>{if(!(S||!b))try{if(I.response){const D=I.responseDelay??n;await p(I.prompt,I.response,{delay:D,streamingSpeed:c})}else R(I.prompt)}catch{}},[b,S,n,c,p,R]),H=y.useCallback(async()=>{try{const D=window.__cuadraThreadListRuntime?.threadList;D?.switchToNewThread&&await D.switchToNewThread()}catch{}},[]);return y.useImperativeHandle(h,()=>({sendMessage:R,sendPreMadeQA:p,clearChat:H}),[R,p,H]),y.useEffect(()=>{if(!b){C(!1);return}try{const I=b?.store;if(!I){C(!1);return}const D=I.subscribe?.(k=>{const j=k?.threadId,E=k?.messages||[],U=k?.isLoadingHistory||!1,F=E.length;j&&j!==v&&_(j),C(U&&F===0)}),B=I.getState?.();if(B){const k=B?.threadId,j=B?.messages||[],E=B?.isLoadingHistory||!1,U=j.length;k&&k!==v&&_(k),C(E&&U===0)}return()=>{D&&D()}}catch{C(!1)}},[b,v]),u.jsxs(T.ThreadPrimitive.Root,{className:"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full cuadra-relative",children:[g&&u.jsx(gs,{}),u.jsxs(T.ComposerPrimitive.AttachmentDropzone,{disabled:!s,className:`cuadra-flex-1 cuadra-flex cuadra-flex-col cuadra-min-h-0 cuadra-relative ${L?"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(Gr,{className:"cuadra-h-6 cuadra-w-6"})}),u.jsx("p",{className:"cuadra-text-sm cuadra-font-medium cuadra-text-foreground font-brand",children:"Drop files here"})]})}),u.jsx(T.ThreadPrimitive.Viewport,{className:`cuadra-w-full cuadra-bg-inherit cuadra-relative scrollbar-thin ${L?"cuadra-flex-none":"cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto"}`,style:{paddingTop:L?"0":t||(g?"0.5rem":"2rem")},children:w?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(Mt,{className:"cuadra-h-5 cuadra-w-5 cuadra-animate-spin cuadra-text-muted-foreground"}),u.jsx("p",{className:"cuadra-text-sm cuadra-text-muted-foreground font-brand",children:"Loading messages..."})]})}):u.jsxs("div",{className:"cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full cuadra-px-4",children:[u.jsx(T.ThreadPrimitive.Empty,{children:u.jsx(us,{title:r})}),u.jsx(T.ThreadPrimitive.Messages,{components:{UserMessage:ds,AssistantMessage:ms}})]})}),u.jsx("div",{className:`cuadra-w-full cuadra-px-4 cuadra-pt-2 ${L?"cuadra-pb-2":"cuadra-pb-4"}`,style:o?{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:[$&&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(Pr,{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:$.message}),u.jsx("button",{type:"button",onClick:()=>de.clear(),className:"cuadra-flex-shrink-0 cuadra-p-0.5 cuadra-rounded hover:cuadra-bg-black/5 cuadra-transition-colors","aria-label":"Dismiss",children:u.jsx(ut,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})]}),s&&u.jsx(T.ComposerPrimitive.Attachments,{components:{Attachment:()=>{const I=T.useAssistantState(({attachment:D})=>D);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(At,{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(T.AttachmentPrimitive.Remove,{asChild:!0,children:u.jsx("button",{type:"button",className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-4 cuadra-rounded-full hover:cuadra-bg-background/60 cuadra-transition-colors cuadra-ml-1","aria-label":"Remove attachment",children:u.jsx(ut,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})})]}):null}}}),u.jsxs(T.ComposerPrimitive.Root,{className:"cuadra-relative cuadra-w-full cuadra-rounded-2xl cuadra-transition-shadow cuadra-duration-300 cuadra-flex cuadra-flex-col",style:{backgroundColor:"var(--cuadra-composer)",boxShadow:"var(--cuadra-composer-shadow)",border:l?"1px solid hsl(var(--cuadra-border))":"none"},children:[u.jsx(T.ComposerPrimitive.Input,{asChild:!0,children:u.jsx("textarea",{rows:1,placeholder:i,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:s&&u.jsx(T.ComposerPrimitive.AddAttachment,{multiple:!0,asChild:!0,children:u.jsxs("button",{type:"button",className:"cuadra-group cuadra-relative cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-8 cuadra-rounded-lg hover:cuadra-bg-muted/60 cuadra-transition-colors","aria-label":"Attach files",children:[u.jsx(Nt,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground",strokeWidth:1.5}),u.jsx("span",{className:"cuadra-pointer-events-none cuadra-absolute cuadra-bottom-full cuadra-left-1/2 cuadra--translate-x-1/2 cuadra-mb-1.5 cuadra-whitespace-nowrap cuadra-rounded-md cuadra-px-2.5 cuadra-py-1 cuadra-text-xs cuadra-text-foreground cuadra-opacity-0 group-hover:cuadra-opacity-100 cuadra-transition-opacity cuadra-duration-150 cuadra-delay-300 font-brand",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"},children:"Attach files"})]})})}),u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[f&&f.length>0&&u.jsx(ps,{models:f,selectedModelId:d,onModelChange:m,threadIsEmpty:A,onNewChat:H}),u.jsx(T.ComposerPrimitive.Send,{asChild:!0,children:u.jsx("button",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-8 cuadra-rounded-full cuadra-transition-all cuadra-duration-200 hover:cuadra-opacity-90 disabled:cuadra-opacity-30 disabled:cuadra-cursor-not-allowed",style:{backgroundColor:"var(--cuadra-primary)",color:"white"},"aria-label":"Send message",type:"button",children:u.jsx(Ir,{className:"cuadra-h-4 cuadra-w-4",strokeWidth:2})})})]})]})]})]})}),L&&a&&a.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:a.map((I,D)=>u.jsx("button",{type:"button",onClick:()=>G(I),disabled:S,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-${D}`))})]})]})});function us({title:e}){return u.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-text-center cuadra-py-6",children:u.jsx("h2",{className:"cuadra-text-4xl cuadra-font-normal cuadra-text-muted-foreground cuadra-tracking-tight",style:{fontFamily:"var(--cuadra-font-logo), Outfit, -apple-system, sans-serif"},children:e})})}function ds(){return u.jsx(T.MessagePrimitive.Root,{className:"cuadra-flex cuadra-w-full cuadra-justify-end cuadra-py-2.5",children:u.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-end cuadra-gap-2 cuadra-max-w-[80%]",children:[u.jsx(T.MessagePrimitive.Attachments,{components:{Attachment:()=>{const e=T.useAssistantState(({attachment:s})=>s);if(!e)return null;const r=e.type==="image",t=e.file,a=e.content?.find(s=>s.type==="image"),i=t?URL.createObjectURL(t):a?.image;return u.jsx("div",{className:"cuadra-mb-1",children:r&&i?u.jsx("img",{src:i,alt:e.name||"Attachment",className:"cuadra-rounded-2xl cuadra-max-h-64 cuadra-max-w-full cuadra-object-contain",style:{border:"1px solid rgba(0,0,0,0.06)"}}):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(At,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground"}),u.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground font-brand",children:e.name||"Attachment"})]})})}}}),u.jsx("div",{className:"cuadra-break-words cuadra-text-foreground font-brand",style:{borderRadius:"1.25rem",backgroundColor:"var(--cuadra-muted)",paddingLeft:"1rem",paddingRight:"1rem",paddingTop:"0.625rem",paddingBottom:"0.625rem",wordBreak:"break-word",fontSize:"0.9375rem",lineHeight:"1.625"},children:u.jsx(T.MessagePrimitive.Parts,{components:{Text:({text:e})=>u.jsx(Ze,{content:e||""})}})})]})})}function hs({text:e}){const[r,t]=y.useState(!1),a=T.useAssistantState(({message:i})=>i?.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:()=>t(!r),className:"cuadra-flex cuadra-items-center cuadra-gap-1.5 cuadra-py-1 cuadra-text-sm cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-colors font-brand",children:[u.jsx(Ke,{className:`cuadra-h-3.5 cuadra-w-3.5 cuadra-shrink-0 cuadra-transition-transform cuadra-duration-200 ${r?"":"cuadra--rotate-90"}`}),u.jsx("span",{children:"Reasoning"})]}),u.jsx("div",{className:`cuadra-overflow-hidden cuadra-transition-all cuadra-duration-200 cuadra-ease-out ${r?"cuadra-max-h-[2000px] cuadra-opacity-100":"cuadra-max-h-0 cuadra-opacity-0"}`,children:u.jsx("div",{className:"cuadra-pl-5 cuadra-pt-2 cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand",children:u.jsx(Ze,{content:e})})})]}):null}function fs(){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 ms(){const e=T.useAssistantState(({message:n})=>n?.status?.type==="running"),r=T.useAssistantState(({message:n})=>{const c=n?.content;return!c||!Array.isArray(c)?!1:c.some(o=>!!(o.type==="text"&&o.text&&o.text.length>0||o.type==="reasoning"&&o.text&&o.text.length>0))}),t=y.useRef(!1),[a,i]=y.useState(null);y.useEffect(()=>{if(e&&r&&!t.current){const n=ee.getCurrentMessageId();n&&(t.current=!0,i(n))}},[e,r]);const s=y.useSyncExternalStore(n=>ee.subscribe(n),()=>{if(a){const n=ee.getForMessage(a);return n.sources?.length?n.sources:null}if(e&&r){const n=ee.getCurrentMessageId();if(n){const c=ee.getForMessage(n);return c.sources?.length?c.sources:null}}return null},()=>null);return u.jsx(T.MessagePrimitive.Root,{className:"cuadra-flex cuadra-w-full cuadra-justify-start cuadra-py-2.5",children:u.jsxs("div",{className:"cuadra-text-foreground cuadra-max-w-full cuadra-break-words font-brand",style:{fontSize:"0.9375rem",lineHeight:"1.75"},children:[u.jsx(T.MessagePrimitive.Parts,{components:{Text:({text:n})=>u.jsx(Ze,{content:n||""}),Reasoning:({text:n})=>u.jsx(hs,{text:n||""})}}),e&&!r&&u.jsx(fs,{}),s&&s.length>0&&u.jsx(dr,{sources:s})]})})}function Te({label:e,children:r}){return u.jsxs("span",{className:"cuadra-relative cuadra-inline-flex cuadra-group/tip",children:[r,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 ps({models:e,selectedModelId:r,onModelChange:t,threadIsEmpty:a,onNewChat:i}){const[s,n]=y.useState(!1),c=e.find(l=>l.id===r)||e[0];if(!c)return null;const o=async l=>{n(!1),!a&&l!==r&&await i?.(),t?.(l)};return u.jsxs("div",{className:"cuadra-relative",children:[u.jsxs("button",{type:"button",onClick:()=>n(!s),className:"cuadra-flex cuadra-items-center cuadra-gap-1 cuadra-px-2.5 cuadra-py-1.5 cuadra-rounded-lg cuadra-text-xs cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-colors font-brand",children:[u.jsx("span",{children:c.name}),c.supportsReasoning&&u.jsx(Te,{label:"Reasoning",children:u.jsx(ct,{className:"cuadra-h-3 cuadra-w-3"})}),c.supportsVision&&u.jsx(Te,{label:"Vision",children:u.jsx(lt,{className:"cuadra-h-3 cuadra-w-3"})}),u.jsx(Ke,{className:"cuadra-h-3 cuadra-w-3"})]}),s&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:()=>n(!1)}),u.jsx("div",{className:"cuadra-absolute cuadra-bottom-full cuadra-right-0 cuadra-mb-2 cuadra-z-50 cuadra-rounded-xl cuadra-min-w-[200px] cuadra-py-1",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 4px 24px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)"},children:e.map(l=>u.jsxs("button",{type:"button",className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-justify-between cuadra-gap-3 cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted/60 cuadra-transition-colors font-brand",onClick:()=>o(l.id),children:[u.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-min-w-0",children:[u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1.5",children:[u.jsx("span",{className:"cuadra-text-foreground cuadra-truncate",children:l.name}),l.supportsReasoning&&u.jsx(Te,{label:"Reasoning",children:u.jsx(ct,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})}),l.supportsVision&&u.jsx(Te,{label:"Vision",children:u.jsx(lt,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})})]}),l.description&&u.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground",children:l.description})]}),l.id===r&&u.jsx(St,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-primary cuadra-flex-shrink-0"})]},l.id))})]})]})}function gs(){const e=T.useAssistantState(({threadListItem:i})=>i?.title??null),[r,t]=y.useState(!1),a=e||"Untitled chat";return u.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-px-3 cuadra-py-2 cuadra-min-h-[48px]",children:u.jsxs("div",{className:"cuadra-relative",children:[u.jsxs("button",{type:"button",onClick:()=>t(!r),className:"cuadra-flex cuadra-items-center cuadra-gap-1 cuadra-text-sm cuadra-text-foreground hover:cuadra-bg-muted/60 cuadra-rounded-lg cuadra-px-2 cuadra-py-1.5 cuadra-transition-colors font-brand",children:[u.jsx("span",{className:"cuadra-font-medium cuadra-truncate cuadra-max-w-[200px]",children:a}),u.jsx(Ke,{className:`cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground cuadra-flex-shrink-0 cuadra-transition-transform cuadra-duration-200 ${r?"cuadra-rotate-180":""}`})]}),r&&u.jsx(xs,{onClose:()=>t(!1)})]})})}function xs({onClose:e}){return u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:e}),u.jsx("div",{className:"cuadra-absolute cuadra-left-0 cuadra-top-full cuadra-mt-1 cuadra-z-50 cuadra-w-[300px] cuadra-rounded-xl cuadra-overflow-hidden cuadra-flex cuadra-flex-col",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 4px 24px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)"},children:u.jsxs(T.ThreadListPrimitive.Root,{className:"cuadra-flex cuadra-flex-col",children:[u.jsx("div",{className:"cuadra-px-2 cuadra-py-1.5",children:u.jsxs(T.ThreadListPrimitive.New,{className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-gap-2.5 cuadra-px-3 cuadra-py-2 cuadra-rounded-lg cuadra-text-sm cuadra-text-foreground hover:cuadra-bg-muted cuadra-transition-colors cuadra-cursor-pointer font-brand",onClick:e,children:[u.jsx(Nt,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"New Chat"]})}),u.jsx(ys,{onSelect:e})]})})]})}function ys({onSelect:e}){const r=T.useAssistantState(({threads:i})=>i?.threadIds??[]),t=T.useAssistantState(({threads:i})=>i?.newThreadId);return r.some(i=>i!==t)?u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"cuadra-mx-3 cuadra-my-0.5",style:{borderTop:"1px solid rgba(0,0,0,0.06)"}}),u.jsx("div",{className:"cuadra-overflow-y-auto cuadra-px-2 cuadra-pb-1.5 scrollbar-thin",style:{maxHeight:"340px"},children:u.jsx(T.ThreadListPrimitive.Items,{components:{ThreadListItem:i=>u.jsx(bs,{...i,onSelect:e})}})})]}):null}function bs({onSelect:e}){const r=T.useThreadListItem(),t=T.useThreadListItemRuntime(),a=T.useAssistantRuntime(),i=T.useThread(x=>x.threadId),s=r?.id===i,[n,c]=y.useState(!1),[o,l]=y.useState(!1),[f,d]=y.useState(r?.title||""),[m,g]=y.useState(!1),h=async()=>{if(!r?.remoteId||!f||f===r.title){l(!1);return}try{g(!0),await t.rename(f)}catch{}finally{g(!1),l(!1)}},b=async x=>{x.stopPropagation();try{await t.delete(),s&&await a.switchToNewThread()}catch(w){console.error("[CuadraChat] Failed to delete thread:",w)}};return y.useEffect(()=>{r?.title&&!o&&d(r.title)},[r?.title,o]),r?u.jsxs(T.ThreadListItemPrimitive.Root,{className:`cuadra-relative cuadra-flex cuadra-items-center cuadra-rounded-lg cuadra-transition-colors cuadra-cursor-pointer ${s?"cuadra-bg-muted":"hover:cuadra-bg-muted/60"}`,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:[o?u.jsx("div",{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0",onClick:x=>x.stopPropagation(),onMouseDown:x=>x.stopPropagation(),onKeyDown:x=>x.stopPropagation(),onKeyUp:x=>x.stopPropagation(),onKeyPress:x=>x.stopPropagation(),children:u.jsx("input",{className:"cuadra-w-full cuadra-bg-transparent cuadra-border-0 cuadra-border-b cuadra-text-sm cuadra-text-foreground cuadra-py-0.5 cuadra-px-0 cuadra-outline-none font-brand",style:{borderBottomColor:"var(--cuadra-primary)",borderBottomWidth:"1.5px"},value:f,onChange:x=>d(x.target.value),onKeyDown:x=>{x.stopPropagation(),x.key==="Enter"&&h(),x.key==="Escape"&&(l(!1),d(r.title||""))},onBlur:()=>void h(),disabled:m,autoFocus:!0})}):u.jsx(T.ThreadListItemPrimitive.Trigger,{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0 cuadra-cursor-pointer",onClick:()=>e?.(),children:u.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground cuadra-truncate cuadra-block cuadra-text-left font-brand",children:r.title||"Chat"})}),(n||s)&&!o&&u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-0.5 cuadra-mr-1.5 cuadra-flex-shrink-0",children:[u.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-background/60 cuadra-transition-colors",onClick:x=>{x.stopPropagation(),l(!0),d(r.title||"Chat")},title:"Rename",children:u.jsx(Wr,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})}),u.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-destructive/10 cuadra-transition-colors",onClick:b,title:"Delete",children:u.jsx(Kr,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-destructive"})})]})]}):null}const Oe=({children:e,className:r="",paddingX:t="px-0",paddingY:a="py-0",borderSizePx:i=2,style:s,contentStyle:n})=>u.jsx("div",{className:`cuadra-relative cuadra-bg-background md:cuadra-rounded-lg cuadra-overflow-hidden cuadra-flex cuadra-flex-col ${t} ${a} ${r}`,style:{border:i>0?`${i}px solid var(--cuadra-primary)`:"none",...s,...n},children:e}),ws=y.createContext(void 0),Be=({children:e,value:r})=>u.jsx(ws.Provider,{value:r,children:e});function ks(){y.useEffect(()=>{if(document.querySelector("style[data-cuadra-uikit]"))return;const r=document.createElement("div");r.className="cuadra-flex",document.body.appendChild(r);const t=window.getComputedStyle(r).display==="flex";if(document.body.removeChild(r),t)return;const a=document.createElement("link");a.setAttribute("data-cuadra-uikit","true"),a.rel="stylesheet",a.type="text/css";const i=["/node_modules/@cuadra-ai/uikit/dist/uikit.css",new URL("../dist/uikit.css",typeof document>"u"?require("url").pathToFileURL(__filename).href:fe&&fe.tagName.toUpperCase()==="SCRIPT"&&fe.src||new URL("index.cjs",document.baseURI).href).href];let s=!1;for(const n of i)if(a.href=n,a.onload=()=>{s=!0},a.onerror=()=>{},document.head.appendChild(a),s)break},[])}const Cs=y.forwardRef(function({config:r},t){ks();const a=y.useRef(null),i=y.useRef(!1),{baseUrl:s,proxyUrl:n,sessionToken:c,mode:o="multiChat",modelMode:l="fixed",modelId:f,onModelChange:d,ephemeral:m=!1,systemPrompt:g,enableReasoning:h=!1,initialThreadId:b,welcomeTitle:x,welcomeSubtitle:w,extraTopPadding:C,suggestions:v,inputPlaceholder:_,preMadeResponseDelay:S=1e3,streamingSpeed:P=50,initialMessage:$,initialPreMadeQA:A,theme:L="system",onError:p,onChatCreated:R,onUserMessage:G,onThreadIdUpdate:H,enableAttachments:I=!1,supportsVision:D,onBeforeRequest:B,mockResponseOnBlocked:k}=r;y.useImperativeHandle(t,()=>({sendMessage:N=>{a.current?.sendMessage(N)},sendPreMadeQA:(N,Z,ie)=>{a.current?.sendPreMadeQA(N,Z,ie)},clearChat:()=>{a.current?.clearChat()}}),[]),y.useEffect(()=>{if(i.current)return;const N=setTimeout(()=>{A?(i.current=!0,a.current?.sendPreMadeQA(A.question,A.answer,{delay:S,streamingSpeed:P})):$&&(i.current=!0,a.current?.sendMessage($))},500);return()=>clearTimeout(N)},[$,A,S,P]);const j=n||s||"",E=!!n,U=y.useMemo(()=>new Pt(j,c||void 0,E),[j,c,E]),[F,M]=y.useState(null),[W,Y]=y.useState(!1),[J,ge]=y.useState(null),[Ee,X]=y.useState(!1);y.useEffect(()=>{o==="multiChat"&&X(!0)},[o]);const ne=y.useCallback(async()=>{if(l==="selector"){Y(!0),ge(null);try{const N=await U.listModels();M(N)}catch(N){ge(N instanceof Error?N:new Error("Failed to load models"))}finally{Y(!1)}}},[U,l]);y.useEffect(()=>{l==="selector"&&ne()},[l,ne]),y.useEffect(()=>(typeof window<"u"&&(window.__cuadraUIKitRefetchModels=ne),()=>{typeof window<"u"&&delete window.__cuadraUIKitRefetchModels}),[ne]);const[K,rt]=y.useState(l==="fixed"&&f||null),at=y.useRef(K),ke=y.useCallback(N=>{const Z=at.current;rt(N),at.current=N,d?.(N),Z!==null&&Z!==N&&o==="multiChat"&&setTimeout(()=>{const ie=window.__cuadraThreadListRuntime;if(ie?.threads?.switchToNewThread)try{ie.threads.switchToNewThread()}catch{}else if(ie?.threads?.createThread)try{ie.threads.createThread()}catch{}else if(ie?.switchToNewThread)try{ie.switchToNewThread()}catch{}},100)},[d,o]);y.useEffect(()=>{if(l==="selector"&&F?.items&&F.items.length>0&&!K){const N=F.items[0];if(N?.id){const Z=N.id;rt(Z),d?.(Z)}}},[l,F?.items,K,d]);const gr=l==="fixed"?!!f:!!K,xr=y.useMemo(()=>D!==void 0?D:l==="selector"&&K&&F?.items?F.items.find(Z=>Z.id===K)?.supportsVision??!0:!0,[D,l,K,F?.items]),Re=y.useMemo(()=>(F?.items||[]).filter(N=>N?.id&&N?.displayName).map(N=>({id:N.id,name:N.displayName,supportsVision:N.supportsVision??!1,supportsReasoning:N.supportsReasoning??!1})),[F]),Le=y.useMemo(()=>({currentModelId:K||"",models:Re,modelsLoading:W,modelsError:J,onModelChange:ke,refetchModels:ne}),[K,Re,W,J,ke,ne]);return l==="selector"&&W||o==="multiChat"&&Ee?u.jsx(Be,{value:Le,children:u.jsx(Oe,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",borderSizePx:r.borderless?0:2,children:u.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:u.jsx(Mt,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"})})})}):l==="selector"&&!gr&&J?u.jsx(Be,{value:Le,children:u.jsx(Oe,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",children:u.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:u.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2",children:u.jsx("p",{className:"cuadra-text-sm cuadra-text-destructive font-brand",children:"Failed to load models"})})})})}):u.jsx("div",{className:"cuadra-uikit cuadra-h-full cuadra-w-full",style:{height:"100%",width:"100%"},children:u.jsx(Be,{value:Le,children:u.jsx(ja,{baseUrl:E?j:s||j,sessionToken:c,isProxyMode:E,mode:o,modelMode:l,modelId:K||f||void 0,onModelChange:ke,ephemeral:m,systemPrompt:g,enableReasoning:h,initialThreadId:b,enableAttachments:I,supportsVision:xr,onError:p,onChatCreated:R,onUserMessage:G,onThreadIdUpdate:H,onBeforeRequest:B,mockResponseOnBlocked:k,onChatsLoaded:()=>{o==="multiChat"&&X(!1)},children:u.jsx(Oe,{paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",className:`cuadra-h-full ${r.containerClass||""}`,borderSizePx:r.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(ls,{ref:a,welcomeTitle:x,welcomeSubtitle:w,extraTopPadding:C,suggestions:v,inputPlaceholder:_,enableAttachments:I,preMadeResponseDelay:S,streamingSpeed:P,safeArea:r.safeArea,showChatHeader:o==="multiChat",models:l==="selector"?Re:void 0,selectedModelId:K||void 0,onModelChange:l==="selector"?ke:void 0,theme:L})})})})})})})})});function hr(e,r=":root"){if(typeof document>"u")return;const t=document.documentElement;if(e.light&&Ts(e.light,t),e.dark){let a=document.getElementById("cuadra-theme-dark");a||(a=document.createElement("style"),a.id="cuadra-theme-dark",document.head.appendChild(a));const i=js(e.dark);a.textContent=`.dark { ${i} }`}}const vs={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 fr(e){const r=vs[e];return r?`--cuadra-${r}`:`--cuadra-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function Ts(e,r){Object.entries(e).forEach(([t,a])=>{if(a){const i=fr(t);r.style.setProperty(i,a)}})}function js(e){return Object.entries(e).map(([r,t])=>t?`${fr(r)}: ${t};`:"").filter(Boolean).join(" ")}function Ss(){if(typeof document>"u")return;const e=document.documentElement;Array.from(e.style).filter(a=>a.startsWith("--cuadra-")).forEach(a=>e.style.removeProperty(a));const t=document.getElementById("cuadra-theme-dark");t&&t.remove()}function Is({onReset:e,error:r}){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:r?.message||"An unexpected error occurred. Please try again."}),u.jsx("button",{onClick:e,className:"cuadra-px-4 cuadra-py-2 cuadra-text-sm cuadra-font-medium cuadra-rounded-md cuadra-transition-colors",style:{backgroundColor:"var(--cuadra-primary)",color:"hsl(var(--cuadra-primary-foreground))"},children:"Try Again"})]})}class tt extends y.Component{constructor(t){super(t);z(this,"reset",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,a){this.props.onError?.(t,a)}render(){if(this.state.hasError){const{fallback:t}=this.props,{error:a}=this.state;return typeof t=="function"?t(a,this.reset):t||u.jsx(Is,{error:a,onReset:this.reset})}return this.props.children}}function Ms(e,r){const t=a=>u.jsx(tt,{...r,children:u.jsx(e,{...a})});return t.displayName=`withErrorBoundary(${e.displayName||e.name||"Component"})`,t}const pe=y.createContext(null);pe.displayName="CuadraChatContext";function As(){const e=y.useContext(pe);if(e===null)throw new Error("useCuadraChat must be used within a CuadraChatProvider. Wrap your component tree with <CuadraChatProvider>...</CuadraChatProvider>");return{controls:e.controls,isReady:e.controls!==null}}function Ns(){const e=y.useContext(pe);return e===null?null:{controls:e.controls,isReady:e.controls!==null}}function _s({children:e}){const[r,t]=y.useState(null),a=y.useCallback(n=>{t(n)},[]),i=y.useCallback(()=>{t(null)},[]),s=y.useMemo(()=>({controls:r,registerControls:a,unregisterControls:i}),[r,a,i]);return u.jsx(pe.Provider,{value:s,children:e})}function mr(e){return"connection"in e&&typeof e.connection=="object"}function pr(e){return mr(e)?Ps(e):Es(e)}function Ps(e){return{connection:{baseUrl:e.connection.baseUrl||"",proxyUrl:e.connection.proxyUrl||"",sessionToken:e.connection.sessionToken??null},chat:{mode:e.chat?.mode??"multiChat",modelMode:e.chat?.modelMode??"fixed",modelId:e.chat?.modelId??"",systemPrompt:e.chat?.systemPrompt??"",ephemeral:e.chat?.ephemeral??!1,enableReasoning:e.chat?.enableReasoning??!1,enableAttachments:e.chat?.enableAttachments??!1,supportsVision:e.chat?.supportsVision,initialThreadId:e.chat?.initialThreadId},ui:{theme:e.ui?.theme??"system",customTheme:e.ui?.customTheme,showThemeToggle:e.ui?.showThemeToggle??!0,language:e.ui?.language,welcomeTitle:e.ui?.welcomeTitle??"Hi, how can I help you today?",welcomeSubtitle:e.ui?.welcomeSubtitle??"Start exploring our platform and discover what you can build.",suggestions:e.ui?.suggestions,inputPlaceholder:e.ui?.inputPlaceholder??"Type your message...",extraTopPadding:e.ui?.extraTopPadding,borderless:e.ui?.borderless,safeArea:e.ui?.safeArea,orgName:e.ui?.orgName,primaryColor:e.ui?.primaryColor},preMade:{responseDelay:e.preMade?.responseDelay??1e3,streamingSpeed:e.preMade?.streamingSpeed??50},initial:{message:e.initial?.message,preMadeQA:e.initial?.preMadeQA},interceptors:{onBeforeRequest:e.interceptors?.onBeforeRequest,mockResponseOnBlocked:e.interceptors?.mockResponseOnBlocked},callbacks:{onChatCreated:e.callbacks?.onChatCreated,onError:e.callbacks?.onError,onUserMessage:e.callbacks?.onUserMessage,onModelChange:e.callbacks?.onModelChange,onThreadIdUpdate:e.callbacks?.onThreadIdUpdate,onLogout:e.callbacks?.onLogout},className:e.className,errorFallback:e.errorFallback}}function Es(e){return typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[CuadraUIKit] Using legacy flat props format. Consider migrating to grouped props for better organization.
|
|
21
|
-
|
|
20
|
+
`))}function o(g,h,b,x){const w=b.enter("tableCell"),C=b.enter("phrasing"),v=b.containerPhrasing(g,{...x,before:s,after:s});return C(),w(),v}function l(g,h){return kn(g,{align:h,alignDelimiters:a,padding:t,stringLength:i})}function f(g,h,b){const x=g.children;let w=-1;const C=[],v=h.enter("table");for(;++w<x.length;)C[w]=d(x[w],h,b);return v(),C}function d(g,h,b){const x=g.children;let w=-1;const C=[],v=h.enter("tableRow");for(;++w<x.length;)C[w]=o(x[w],g,h,b);return v(),C}function m(g,h,b){let x=ar.inlineCode(g,h,b);return b.stack.includes("tableCell")&&(x=x.replace(/\|/g,"\\$&")),x}}function di(){return{exit:{taskListCheckValueChecked:Ct,taskListCheckValueUnchecked:Ct,paragraph:fi}}}function hi(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:mi}}}function Ct(e){const r=this.stack[this.stack.length-2];r.type,r.checked=e.type==="taskListCheckValueChecked"}function fi(e){const r=this.stack[this.stack.length-2];if(r&&r.type==="listItem"&&typeof r.checked=="boolean"){const t=this.stack[this.stack.length-1];t.type;const a=t.children[0];if(a&&a.type==="text"){const i=r.children;let s=-1,n;for(;++s<i.length;){const c=i[s];if(c.type==="paragraph"){n=c;break}}n===t&&(a.value=a.value.slice(1),a.value.length===0?t.children.shift():t.position&&a.position&&typeof a.position.start.offset=="number"&&(a.position.start.column++,a.position.start.offset++,t.position.start=Object.assign({},a.position.start)))}}this.exit(e)}function mi(e,r,t,a){const i=e.children[0],s=typeof e.checked=="boolean"&&i&&i.type==="paragraph",n="["+(e.checked?"x":" ")+"] ",c=t.createTracker(a);s&&c.move(n);let o=ar.listItem(e,r,t,{...a,...c.current()});return s&&(o=o.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,l)),o;function l(f){return f+n}}function pi(){return[qa(),dn(),pn(),ni(),di()]}function gi(e){return{extensions:[Va(),hn(e),gn(),ui(e),hi()]}}function je(e,r,t,a){const i=e.length;let s=0,n;if(r<0?r=-r>i?0:i+r:r=r>i?i:r,t=t>0?t:0,a.length<1e4)n=Array.from(a),n.unshift(r,t),e.splice(...n);else for(t&&e.splice(r,t);s<a.length;)n=a.slice(s,s+1e4),n.unshift(r,0),e.splice(...n),s+=1e4,r+=1e4}const vt={}.hasOwnProperty;function xi(e){const r={};let t=-1;for(;++t<e.length;)yi(r,e[t]);return r}function yi(e,r){let t;for(t in r){const i=(vt.call(e,t)?e[t]:void 0)||(e[t]={}),s=r[t];let n;if(s)for(n in s){vt.call(i,n)||(i[n]=[]);const c=s[n];bi(i[n],Array.isArray(c)?c:c?[c]:[])}}}function bi(e,r){let t=-1;const a=[];for(;++t<r.length;)(r[t].add==="after"?e:a).push(r[t]);je(e,0,0,a)}const wi={tokenize:Si,partial:!0},nr={tokenize:Ii,partial:!0},ir={tokenize:Mi,partial:!0},sr={tokenize:Ai,partial:!0},ki={tokenize:Ni,partial:!0},or={name:"wwwAutolink",tokenize:Ti,previous:lr},cr={name:"protocolAutolink",tokenize:ji,previous:ur},ae={name:"emailAutolink",tokenize:vi,previous:dr},Q={};function Ci(){return{text:Q}}let se=48;for(;se<123;)Q[se]=ae,se++,se===58?se=65:se===91&&(se=97);Q[43]=ae;Q[45]=ae;Q[46]=ae;Q[95]=ae;Q[72]=[ae,cr];Q[104]=[ae,cr];Q[87]=[ae,or];Q[119]=[ae,or];function vi(e,r,t){const a=this;let i,s;return n;function n(d){return!He(d)||!dr.call(a,a.previous)||Xe(a.events)?t(d):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(d))}function c(d){return He(d)?(e.consume(d),c):d===64?(e.consume(d),o):t(d)}function o(d){return d===46?e.check(ki,f,l)(d):d===45||d===95||Ge(d)?(s=!0,e.consume(d),o):f(d)}function l(d){return e.consume(d),i=!0,o}function f(d){return s&&i&&ye(a.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),r(d)):t(d)}}function Ti(e,r,t){const a=this;return i;function i(n){return n!==87&&n!==119||!lr.call(a,a.previous)||Xe(a.events)?t(n):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(wi,e.attempt(nr,e.attempt(ir,s),t),t)(n))}function s(n){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),r(n)}}function ji(e,r,t){const a=this;let i="",s=!1;return n;function n(d){return(d===72||d===104)&&ur.call(a,a.previous)&&!Xe(a.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),i+=String.fromCodePoint(d),e.consume(d),c):t(d)}function c(d){if(ye(d)&&i.length<5)return i+=String.fromCodePoint(d),e.consume(d),c;if(d===58){const m=i.toLowerCase();if(m==="http"||m==="https")return e.consume(d),o}return t(d)}function o(d){return d===47?(e.consume(d),s?l:(s=!0,o)):t(d)}function l(d){return d===null||Aa(d)||W(d)||oe(d)||Ae(d)?t(d):e.attempt(nr,e.attempt(ir,f),t)(d)}function f(d){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),r(d)}}function Si(e,r,t){let a=0;return i;function i(n){return(n===87||n===119)&&a<3?(a++,e.consume(n),i):n===46&&a===3?(e.consume(n),s):t(n)}function s(n){return n===null?t(n):r(n)}}function Ii(e,r,t){let a,i,s;return n;function n(l){return l===46||l===95?e.check(sr,o,c)(l):l===null||W(l)||oe(l)||l!==45&&Ae(l)?o(l):(s=!0,e.consume(l),n)}function c(l){return l===95?a=!0:(i=a,a=void 0),e.consume(l),n}function o(l){return i||a||!s?t(l):r(l)}}function Mi(e,r){let t=0,a=0;return i;function i(n){return n===40?(t++,e.consume(n),i):n===41&&a<t?s(n):n===33||n===34||n===38||n===39||n===41||n===42||n===44||n===46||n===58||n===59||n===60||n===63||n===93||n===95||n===126?e.check(sr,r,s)(n):n===null||W(n)||oe(n)?r(n):(e.consume(n),i)}function s(n){return n===41&&a++,e.consume(n),i}}function Ai(e,r,t){return a;function a(c){return c===33||c===34||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===63||c===95||c===126?(e.consume(c),a):c===38?(e.consume(c),s):c===93?(e.consume(c),i):c===60||c===null||W(c)||oe(c)?r(c):t(c)}function i(c){return c===null||c===40||c===91||W(c)||oe(c)?r(c):a(c)}function s(c){return ye(c)?n(c):t(c)}function n(c){return c===59?(e.consume(c),a):ye(c)?(e.consume(c),n):t(c)}}function Ni(e,r,t){return a;function a(s){return e.consume(s),i}function i(s){return Ge(s)?t(s):r(s)}}function lr(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||W(e)}function ur(e){return!ye(e)}function dr(e){return!(e===47||He(e))}function He(e){return e===43||e===45||e===46||e===95||Ge(e)}function Xe(e){let r=e.length,t=!1;for(;r--;){const a=e[r][1];if((a.type==="labelLink"||a.type==="labelImage")&&!a._balanced){t=!0;break}if(a._gfmAutolinkLiteralWalkedInto){t=!1;break}}return e.length>0&&!t&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),t}function _i(e,r,t){const a=[];let i=-1;for(;++i<e.length;){const s=e[i].resolveAll;s&&!a.includes(s)&&(r=s(r,t),a.push(s))}return r}function re(e,r,t,a){const i=a?a-1:Number.POSITIVE_INFINITY;let s=0;return n;function n(o){return te(o)?(e.enter(t),c(o)):r(o)}function c(o){return te(o)&&s++<i?(e.consume(o),c):(e.exit(t),r(o))}}const Pi={partial:!0,tokenize:Ei};function Ei(e,r,t){return a;function a(s){return te(s)?re(e,i,"linePrefix")(s):i(s)}function i(s){return s===null||he(s)?r(s):t(s)}}const Ri={tokenize:Bi,partial:!0};function Li(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:zi,continuation:{tokenize:$i},exit:Oi}},text:{91:{name:"gfmFootnoteCall",tokenize:Ui},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Di,resolveTo:Fi}}}}function Di(e,r,t){const a=this;let i=a.events.length;const s=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let n;for(;i--;){const o=a.events[i][1];if(o.type==="labelImage"){n=o;break}if(o.type==="gfmFootnoteCall"||o.type==="labelLink"||o.type==="label"||o.type==="image"||o.type==="link")break}return c;function c(o){if(!n||!n._balanced)return t(o);const l=we(a.sliceSerialize({start:n.end,end:a.now()}));return l.codePointAt(0)!==94||!s.includes(l.slice(1))?t(o):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(o),e.exit("gfmFootnoteCallLabelMarker"),r(o))}}function Fi(e,r){let t=e.length;for(;t--;)if(e[t][1].type==="labelImage"&&e[t][0]==="enter"){e[t][1];break}e[t+1][1].type="data",e[t+3][1].type="gfmFootnoteCallLabelMarker";const a={type:"gfmFootnoteCall",start:Object.assign({},e[t+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:"gfmFootnoteCallMarker",start:Object.assign({},e[t+3][1].end),end:Object.assign({},e[t+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;const s={type:"gfmFootnoteCallString",start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},n={type:"chunkString",contentType:"string",start:Object.assign({},s.start),end:Object.assign({},s.end)},c=[e[t+1],e[t+2],["enter",a,r],e[t+3],e[t+4],["enter",i,r],["exit",i,r],["enter",s,r],["enter",n,r],["exit",n,r],["exit",s,r],e[e.length-2],e[e.length-1],["exit",a,r]];return e.splice(t,e.length-t+1,...c),e}function Ui(e,r,t){const a=this,i=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let s=0,n;return c;function c(d){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),o}function o(d){return d!==94?t(d):(e.enter("gfmFootnoteCallMarker"),e.consume(d),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",l)}function l(d){if(s>999||d===93&&!n||d===null||d===91||W(d))return t(d);if(d===93){e.exit("chunkString");const m=e.exit("gfmFootnoteCallString");return i.includes(we(a.sliceSerialize(m)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),r):t(d)}return W(d)||(n=!0),s++,e.consume(d),d===92?f:l}function f(d){return d===91||d===92||d===93?(e.consume(d),s++,l):l(d)}}function zi(e,r,t){const a=this,i=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let s,n=0,c;return o;function o(h){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(h),e.exit("gfmFootnoteDefinitionLabelMarker"),l}function l(h){return h===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(h),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",f):t(h)}function f(h){if(n>999||h===93&&!c||h===null||h===91||W(h))return t(h);if(h===93){e.exit("chunkString");const b=e.exit("gfmFootnoteDefinitionLabelString");return s=we(a.sliceSerialize(b)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(h),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),m}return W(h)||(c=!0),n++,e.consume(h),h===92?d:f}function d(h){return h===91||h===92||h===93?(e.consume(h),n++,f):f(h)}function m(h){return h===58?(e.enter("definitionMarker"),e.consume(h),e.exit("definitionMarker"),i.includes(s)||i.push(s),re(e,g,"gfmFootnoteDefinitionWhitespace")):t(h)}function g(h){return r(h)}}function $i(e,r,t){return e.check(Pi,r,e.attempt(Ri,r,t))}function Oi(e){e.exit("gfmFootnoteDefinition")}function Bi(e,r,t){const a=this;return re(e,i,"gfmFootnoteDefinitionIndent",5);function i(s){const n=a.events[a.events.length-1];return n&&n[1].type==="gfmFootnoteDefinitionIndent"&&n[2].sliceSerialize(n[1],!0).length===4?r(s):t(s)}}function qi(e){let t=(e||{}).singleTilde;const a={name:"strikethrough",tokenize:s,resolveAll:i};return t==null&&(t=!0),{text:{126:a},insideSpan:{null:[a]},attentionMarkers:{null:[126]}};function i(n,c){let o=-1;for(;++o<n.length;)if(n[o][0]==="enter"&&n[o][1].type==="strikethroughSequenceTemporary"&&n[o][1]._close){let l=o;for(;l--;)if(n[l][0]==="exit"&&n[l][1].type==="strikethroughSequenceTemporary"&&n[l][1]._open&&n[o][1].end.offset-n[o][1].start.offset===n[l][1].end.offset-n[l][1].start.offset){n[o][1].type="strikethroughSequence",n[l][1].type="strikethroughSequence";const f={type:"strikethrough",start:Object.assign({},n[l][1].start),end:Object.assign({},n[o][1].end)},d={type:"strikethroughText",start:Object.assign({},n[l][1].end),end:Object.assign({},n[o][1].start)},m=[["enter",f,c],["enter",n[l][1],c],["exit",n[l][1],c],["enter",d,c]],g=c.parser.constructs.insideSpan.null;g&&je(m,m.length,0,_i(g,n.slice(l+1,o),c)),je(m,m.length,0,[["exit",d,c],["enter",n[o][1],c],["exit",n[o][1],c],["exit",f,c]]),je(n,l-1,o-l+3,m),o=l+m.length-2;break}}for(o=-1;++o<n.length;)n[o][1].type==="strikethroughSequenceTemporary"&&(n[o][1].type="data");return n}function s(n,c,o){const l=this.previous,f=this.events;let d=0;return m;function m(h){return l===126&&f[f.length-1][1].type!=="characterEscape"?o(h):(n.enter("strikethroughSequenceTemporary"),g(h))}function g(h){const b=Ie(l);if(h===126)return d>1?o(h):(n.consume(h),d++,g);if(d<2&&!t)return o(h);const x=n.exit("strikethroughSequenceTemporary"),w=Ie(h);return x._open=!w||w===2&&!!b,x._close=!b||b===2&&!!w,c(h)}}}class Vi{constructor(){this.map=[]}add(r,t,a){Wi(this,r,t,a)}consume(r){if(this.map.sort(function(s,n){return s[0]-n[0]}),this.map.length===0)return;let t=this.map.length;const a=[];for(;t>0;)t-=1,a.push(r.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),r.length=this.map[t][0];a.push(r.slice()),r.length=0;let i=a.pop();for(;i;){for(const s of i)r.push(s);i=a.pop()}this.map.length=0}}function Wi(e,r,t,a){let i=0;if(!(t===0&&a.length===0)){for(;i<e.map.length;){if(e.map[i][0]===r){e.map[i][1]+=t,e.map[i][2].push(...a);return}i+=1}e.map.push([r,t,a])}}function Hi(e,r){let t=!1;const a=[];for(;r<e.length;){const i=e[r];if(t){if(i[0]==="enter")i[1].type==="tableContent"&&a.push(e[r+1][1].type==="tableDelimiterMarker"?"left":"none");else if(i[1].type==="tableContent"){if(e[r-1][1].type==="tableDelimiterMarker"){const s=a.length-1;a[s]=a[s]==="left"?"center":"right"}}else if(i[1].type==="tableDelimiterRow")break}else i[0]==="enter"&&i[1].type==="tableDelimiterRow"&&(t=!0);r+=1}return a}function Ki(){return{flow:{null:{name:"table",tokenize:Qi,resolveAll:Gi}}}}function Qi(e,r,t){const a=this;let i=0,s=0,n;return c;function c(p){let R=a.events.length-1;for(;R>-1;){const I=a.events[R][1].type;if(I==="lineEnding"||I==="linePrefix")R--;else break}const G=R>-1?a.events[R][1].type:null,H=G==="tableHead"||G==="tableRow"?P:o;return H===P&&a.parser.lazy[a.now().line]?t(p):H(p)}function o(p){return e.enter("tableHead"),e.enter("tableRow"),l(p)}function l(p){return p===124||(n=!0,s+=1),f(p)}function f(p){return p===null?t(p):he(p)?s>1?(s=0,a.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),g):t(p):te(p)?re(e,f,"whitespace")(p):(s+=1,n&&(n=!1,i+=1),p===124?(e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),n=!0,f):(e.enter("data"),d(p)))}function d(p){return p===null||p===124||W(p)?(e.exit("data"),f(p)):(e.consume(p),p===92?m:d)}function m(p){return p===92||p===124?(e.consume(p),d):d(p)}function g(p){return a.interrupt=!1,a.parser.lazy[a.now().line]?t(p):(e.enter("tableDelimiterRow"),n=!1,te(p)?re(e,h,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(p):h(p))}function h(p){return p===45||p===58?x(p):p===124?(n=!0,e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),b):S(p)}function b(p){return te(p)?re(e,x,"whitespace")(p):x(p)}function x(p){return p===58?(s+=1,n=!0,e.enter("tableDelimiterMarker"),e.consume(p),e.exit("tableDelimiterMarker"),w):p===45?(s+=1,w(p)):p===null||he(p)?_(p):S(p)}function w(p){return p===45?(e.enter("tableDelimiterFiller"),C(p)):S(p)}function C(p){return p===45?(e.consume(p),C):p===58?(n=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(p),e.exit("tableDelimiterMarker"),v):(e.exit("tableDelimiterFiller"),v(p))}function v(p){return te(p)?re(e,_,"whitespace")(p):_(p)}function _(p){return p===124?h(p):p===null||he(p)?!n||i!==s?S(p):(e.exit("tableDelimiterRow"),e.exit("tableHead"),r(p)):S(p)}function S(p){return t(p)}function P(p){return e.enter("tableRow"),$(p)}function $(p){return p===124?(e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),$):p===null||he(p)?(e.exit("tableRow"),r(p)):te(p)?re(e,$,"whitespace")(p):(e.enter("data"),A(p))}function A(p){return p===null||p===124||W(p)?(e.exit("data"),$(p)):(e.consume(p),p===92?L:A)}function L(p){return p===92||p===124?(e.consume(p),A):A(p)}}function Gi(e,r){let t=-1,a=!0,i=0,s=[0,0,0,0],n=[0,0,0,0],c=!1,o=0,l,f,d;const m=new Vi;for(;++t<e.length;){const g=e[t],h=g[1];g[0]==="enter"?h.type==="tableHead"?(c=!1,o!==0&&(Tt(m,r,o,l,f),f=void 0,o=0),l={type:"table",start:Object.assign({},h.start),end:Object.assign({},h.end)},m.add(t,0,[["enter",l,r]])):h.type==="tableRow"||h.type==="tableDelimiterRow"?(a=!0,d=void 0,s=[0,0,0,0],n=[0,t+1,0,0],c&&(c=!1,f={type:"tableBody",start:Object.assign({},h.start),end:Object.assign({},h.end)},m.add(t,0,[["enter",f,r]])),i=h.type==="tableDelimiterRow"?2:f?3:1):i&&(h.type==="data"||h.type==="tableDelimiterMarker"||h.type==="tableDelimiterFiller")?(a=!1,n[2]===0&&(s[1]!==0&&(n[0]=n[1],d=ve(m,r,s,i,void 0,d),s=[0,0,0,0]),n[2]=t)):h.type==="tableCellDivider"&&(a?a=!1:(s[1]!==0&&(n[0]=n[1],d=ve(m,r,s,i,void 0,d)),s=n,n=[s[1],t,0,0])):h.type==="tableHead"?(c=!0,o=t):h.type==="tableRow"||h.type==="tableDelimiterRow"?(o=t,s[1]!==0?(n[0]=n[1],d=ve(m,r,s,i,t,d)):n[1]!==0&&(d=ve(m,r,n,i,t,d)),i=0):i&&(h.type==="data"||h.type==="tableDelimiterMarker"||h.type==="tableDelimiterFiller")&&(n[3]=t)}for(o!==0&&Tt(m,r,o,l,f),m.consume(r.events),t=-1;++t<r.events.length;){const g=r.events[t];g[0]==="enter"&&g[1].type==="table"&&(g[1]._align=Hi(r.events,t))}return e}function ve(e,r,t,a,i,s){const n=a===1?"tableHeader":a===2?"tableDelimiter":"tableData",c="tableContent";t[0]!==0&&(s.end=Object.assign({},ue(r.events,t[0])),e.add(t[0],0,[["exit",s,r]]));const o=ue(r.events,t[1]);if(s={type:n,start:Object.assign({},o),end:Object.assign({},o)},e.add(t[1],0,[["enter",s,r]]),t[2]!==0){const l=ue(r.events,t[2]),f=ue(r.events,t[3]),d={type:c,start:Object.assign({},l),end:Object.assign({},f)};if(e.add(t[2],0,[["enter",d,r]]),a!==2){const m=r.events[t[2]],g=r.events[t[3]];if(m[1].end=Object.assign({},g[1].end),m[1].type="chunkText",m[1].contentType="text",t[3]>t[2]+1){const h=t[2]+1,b=t[3]-t[2]-1;e.add(h,b,[])}}e.add(t[3]+1,0,[["exit",d,r]])}return i!==void 0&&(s.end=Object.assign({},ue(r.events,i)),e.add(i,0,[["exit",s,r]]),s=void 0),s}function Tt(e,r,t,a,i){const s=[],n=ue(r.events,t);i&&(i.end=Object.assign({},n),s.push(["exit",i,r])),a.end=Object.assign({},n),s.push(["exit",a,r]),e.add(t+1,0,s)}function ue(e,r){const t=e[r],a=t[0]==="enter"?"start":"end";return t[1][a]}const Yi={name:"tasklistCheck",tokenize:Xi};function Ji(){return{text:{91:Yi}}}function Xi(e,r,t){const a=this;return i;function i(o){return a.previous!==null||!a._gfmTasklistFirstContentOfListItem?t(o):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(o),e.exit("taskListCheckMarker"),s)}function s(o){return W(o)?(e.enter("taskListCheckValueUnchecked"),e.consume(o),e.exit("taskListCheckValueUnchecked"),n):o===88||o===120?(e.enter("taskListCheckValueChecked"),e.consume(o),e.exit("taskListCheckValueChecked"),n):t(o)}function n(o){return o===93?(e.enter("taskListCheckMarker"),e.consume(o),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):t(o)}function c(o){return he(o)?r(o):te(o)?e.check({tokenize:Zi},r,t)(o):t(o)}}function Zi(e,r,t){return re(e,a,"whitespace");function a(i){return i===null?t(i):r(i)}}function es(e){return xi([Ci(),Li(),qi(e),Ki(),Ji()])}const ts={};function rs(e){const r=this,t=e||ts,a=r.data(),i=a.micromarkExtensions||(a.micromarkExtensions=[]),s=a.fromMarkdownExtensions||(a.fromMarkdownExtensions=[]),n=a.toMarkdownExtensions||(a.toMarkdownExtensions=[]);i.push(es(t)),s.push(pi()),n.push(gi(t))}function O(...e){return e.filter(Boolean).join(" ")}const as=({content:e})=>u.jsx(qe.MarkdownTextPrimitive,{remarkPlugins:[rs],className:"cuadra-aui-md",components:ss,children:e}),Ze=y.memo(as),ns=({language:e,code:r})=>{const{isCopied:t,copyToClipboard:a}=is(),i=()=>{!r||t||a(r)};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:i,className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-muted cuadra-transition-colors","aria-label":"Copy code",children:[!t&&u.jsx(Lr,{className:"cuadra-h-4 cuadra-w-4"}),t&&u.jsx(It,{className:"cuadra-h-4 cuadra-w-4"})]})]})},is=({copiedDuration:e=3e3}={})=>{const[r,t]=y.useState(!1);return{isCopied:r,copyToClipboard:i=>{i&&navigator.clipboard.writeText(i).then(()=>{t(!0),setTimeout(()=>t(!1),e)})}}},ss=qe.unstable_memoizeMarkdownComponents({h1:({className:e,...r})=>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),...r}),h2:({className:e,...r})=>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),...r}),h3:({className:e,...r})=>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),...r}),h4:({className:e,...r})=>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),...r}),h5:({className:e,...r})=>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),...r}),h6:({className:e,...r})=>u.jsx("h6",{className:O("cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand",e),...r}),p:({className:e,...r})=>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),...r}),a:({className:e,...r})=>u.jsx("a",{className:O("cuadra-text-primary cuadra-font-medium cuadra-underline cuadra-underline-offset-4 font-brand",e),...r}),blockquote:({className:e,...r})=>u.jsx("blockquote",{className:O("cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand",e),...r}),ul:({className:e,...r})=>u.jsx("ul",{className:O("cuadra-my-5 cuadra-ml-6 cuadra-list-disc [&>li]:cuadra-mt-2 font-brand",e),...r}),ol:({className:e,...r})=>u.jsx("ol",{className:O("cuadra-my-5 cuadra-ml-6 cuadra-list-decimal [&>li]:cuadra-mt-2 font-brand",e),...r}),hr:({className:e,...r})=>u.jsx("hr",{className:O("cuadra-my-5 cuadra-border-b",e),...r}),table:({className:e,...r})=>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),...r}),th:({className:e,...r})=>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),...r}),td:({className:e,...r})=>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),...r}),tr:({className:e,...r})=>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),...r}),sup:({className:e,...r})=>u.jsx("sup",{className:O("[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand",e),...r}),pre:({className:e,...r})=>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),...r}),code:function({className:r,...t}){const a=qe.useIsMarkdownCodeBlock();return u.jsx("code",{className:O(!a&&"cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand",r),...t})},CodeHeader:ns});function et({className:e="",variant:r="default",...t}){const a="cuadra-inline-flex cuadra-items-center cuadra-rounded-md cuadra-px-3 cuadra-py-1.5 cuadra-text-xs cuadra-font-medium font-brand",i={default:"cuadra-border cuadra-border-border cuadra-bg-muted cuadra-text-muted-foreground",subtle:"cuadra-border cuadra-border-border/50 cuadra-bg-muted/50 cuadra-text-muted-foreground",outline:"cuadra-border cuadra-border-border cuadra-bg-background cuadra-text-foreground",ghost:"cuadra-text-muted-foreground"};return u.jsx("div",{className:`${a} ${i[r]||i.default} ${e}`,...t})}function os(e){const r=new Map;for(const t of e){const a=r.get(t.filename);(!a||t.score>a.score)&&r.set(t.filename,t)}return Array.from(r.values()).sort((t,a)=>a.score-t.score)}function hr({sources:e,maxVisible:r=3}){if(!e||e.length===0)return null;const t=os(e),a=t.slice(0,r),i=t.length-r;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,n)=>u.jsx(ls,{source:s},s.sourceId||n)),i>0&&u.jsxs(et,{variant:"subtle",children:["+",i," more"]})]})]})}function cs(e){switch(e.split(".").pop()?.toLowerCase()){case"csv":case"xlsx":case"xls":return Ur;case"md":case"txt":return Or;default:return Mt}}function ls({source:e}){const{filename:r,score:t}=e,a=cs(r);return u.jsxs(et,{className:"cuadra-gap-2 cuadra-cursor-default",title:t<1?`${Math.round(t*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:r}),t<1&&t>0&&u.jsxs("span",{className:"cuadra-opacity-50 cuadra-text-[10px] cuadra-tabular-nums",children:[Math.round(t*100),"%"]})]})}const us=y.forwardRef(function({welcomeTitle:r="What shall we explore today?",extraTopPadding:t,suggestions:a,inputPlaceholder:i="Reply...",enableAttachments:s=!1,preMadeResponseDelay:n=1e3,streamingSpeed:c=50,safeArea:o=!1,composerBorder:l=!1,models:f,selectedModelId:d,onModelChange:m,showChatHeader:g=!1},h){const b=T.useThreadRuntime(),x=T.useAssistantApi(),[w,C]=y.useState(!1),[v,_]=y.useState(null),[S,P]=y.useState(!1),$=y.useSyncExternalStore(de.subscribe,de.getSnapshot);y.useEffect(()=>{if($){const I=setTimeout(()=>de.clear(),4e3);return()=>clearTimeout(I)}},[$]);const A=T.useThread(I=>{const D=I.messages;return!D||D.length===0}),L=A&&!w,p=y.useCallback((I,D,B)=>{if(!S)try{const k=B?.streamingSpeed??c,j=B?.delay??n;Ft(I,D,k,j),x.composer().setText(I),setTimeout(()=>{x.composer().send()},10)}catch{}},[S,c,n,x]),R=y.useCallback(I=>{try{x.composer().setText(I),setTimeout(()=>{x.composer().send()},10)}catch{}},[x]),G=y.useCallback(async I=>{if(!(S||!b))try{if(I.response){const D=I.responseDelay??n;await p(I.prompt,I.response,{delay:D,streamingSpeed:c})}else R(I.prompt)}catch{}},[b,S,n,c,p,R]),H=y.useCallback(async()=>{try{const D=window.__cuadraThreadListRuntime?.threadList;D?.switchToNewThread&&await D.switchToNewThread()}catch{}},[]);return y.useImperativeHandle(h,()=>({sendMessage:R,sendPreMadeQA:p,clearChat:H}),[R,p,H]),y.useEffect(()=>{if(!b){C(!1);return}try{const I=b?.store;if(!I){C(!1);return}const D=I.subscribe?.(k=>{const j=k?.threadId,E=k?.messages||[],U=k?.isLoadingHistory||!1,F=E.length;j&&j!==v&&_(j),C(U&&F===0)}),B=I.getState?.();if(B){const k=B?.threadId,j=B?.messages||[],E=B?.isLoadingHistory||!1,U=j.length;k&&k!==v&&_(k),C(E&&U===0)}return()=>{D&&D()}}catch{C(!1)}},[b,v]),u.jsxs(T.ThreadPrimitive.Root,{className:"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full cuadra-relative",children:[g&&u.jsx(xs,{}),u.jsxs(T.ComposerPrimitive.AttachmentDropzone,{disabled:!s,className:`cuadra-flex-1 cuadra-flex cuadra-flex-col cuadra-min-h-0 cuadra-relative ${L?"cuadra-justify-center":""}`,children:[u.jsx("div",{className:"cuadra-dropzone-overlay cuadra-pointer-events-none cuadra-absolute cuadra-inset-0 cuadra-z-50 cuadra-flex cuadra-items-center cuadra-justify-center cuadra-rounded-lg cuadra-transition-opacity cuadra-duration-200",style:{opacity:0},children:u.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-3",children:[u.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-14 cuadra-rounded-2xl",style:{backgroundColor:"var(--cuadra-primary)",color:"white"},children:u.jsx(Yr,{className:"cuadra-h-6 cuadra-w-6"})}),u.jsx("p",{className:"cuadra-text-sm cuadra-font-medium cuadra-text-foreground font-brand",children:"Drop files here"})]})}),u.jsx(T.ThreadPrimitive.Viewport,{className:`cuadra-w-full cuadra-bg-inherit cuadra-relative scrollbar-thin ${L?"cuadra-flex-none":"cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto"}`,style:{paddingTop:L?"0":t||(g?"0.5rem":"2rem")},children:w?u.jsx("div",{className:"cuadra-absolute cuadra-inset-0 cuadra-flex cuadra-items-center cuadra-justify-center",children:u.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-3",children:[u.jsx(At,{className:"cuadra-h-5 cuadra-w-5 cuadra-animate-spin cuadra-text-muted-foreground"}),u.jsx("p",{className:"cuadra-text-sm cuadra-text-muted-foreground font-brand",children:"Loading messages..."})]})}):u.jsxs("div",{className:"cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full cuadra-px-4",children:[u.jsx(T.ThreadPrimitive.Empty,{children:u.jsx(ds,{title:r})}),u.jsx(T.ThreadPrimitive.Messages,{components:{UserMessage:hs,AssistantMessage:ps}})]})}),u.jsx("div",{className:`cuadra-w-full cuadra-px-4 cuadra-pt-2 ${L?"cuadra-pb-2":"cuadra-pb-4"}`,style:o?{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:[$&&u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-mb-2 cuadra-px-3 cuadra-py-2 cuadra-rounded-lg cuadra-text-xs font-brand cuadra-animate-in cuadra-fade-in cuadra-slide-in-from-bottom-2",style:{backgroundColor:"var(--cuadra-muted)",color:"var(--cuadra-foreground)",opacity:.85},children:[u.jsx(Er,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-flex-shrink-0 cuadra-text-muted-foreground"}),u.jsx("span",{className:"cuadra-flex-1 cuadra-text-muted-foreground",children:$.message}),u.jsx("button",{type:"button",onClick:()=>de.clear(),className:"cuadra-flex-shrink-0 cuadra-p-0.5 cuadra-rounded hover:cuadra-bg-black/5 cuadra-transition-colors","aria-label":"Dismiss",children:u.jsx(ut,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})]}),s&&u.jsx(T.ComposerPrimitive.Attachments,{components:{Attachment:()=>{const I=T.useAssistantState(({attachment:D})=>D);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(T.AttachmentPrimitive.Remove,{asChild:!0,children:u.jsx("button",{type:"button",className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-4 cuadra-rounded-full hover:cuadra-bg-background/60 cuadra-transition-colors cuadra-ml-1","aria-label":"Remove attachment",children:u.jsx(ut,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})})]}):null}}}),u.jsxs(T.ComposerPrimitive.Root,{className:"cuadra-relative cuadra-w-full cuadra-rounded-2xl cuadra-transition-shadow cuadra-duration-300 cuadra-flex cuadra-flex-col",style:{backgroundColor:"var(--cuadra-composer)",boxShadow:"var(--cuadra-composer-shadow)",border:l?"1px solid hsl(var(--cuadra-border))":"none"},children:[u.jsx(T.ComposerPrimitive.Input,{asChild:!0,children:u.jsx("textarea",{rows:1,placeholder:i,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:s&&u.jsx(T.ComposerPrimitive.AddAttachment,{multiple:!0,asChild:!0,children:u.jsxs("button",{type:"button",className:"cuadra-group cuadra-relative cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-8 cuadra-rounded-lg hover:cuadra-bg-muted/60 cuadra-transition-colors","aria-label":"Attach files",children:[u.jsx(_t,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground",strokeWidth:1.5}),u.jsx("span",{className:"cuadra-pointer-events-none cuadra-absolute cuadra-bottom-full cuadra-left-1/2 cuadra--translate-x-1/2 cuadra-mb-1.5 cuadra-whitespace-nowrap cuadra-rounded-md cuadra-px-2.5 cuadra-py-1 cuadra-text-xs cuadra-text-foreground cuadra-opacity-0 group-hover:cuadra-opacity-100 cuadra-transition-opacity cuadra-duration-150 cuadra-delay-300 font-brand",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"},children:"Attach files"})]})})}),u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[f&&f.length>0&&u.jsx(gs,{models:f,selectedModelId:d,onModelChange:m,threadIsEmpty:A,onNewChat:H}),u.jsx(T.ComposerPrimitive.Send,{asChild:!0,children:u.jsx("button",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-8 cuadra-rounded-full cuadra-transition-all cuadra-duration-200 hover:cuadra-opacity-90 disabled:cuadra-opacity-30 disabled:cuadra-cursor-not-allowed",style:{backgroundColor:"var(--cuadra-primary)",color:"white"},"aria-label":"Send message",type:"button",children:u.jsx(Mr,{className:"cuadra-h-4 cuadra-w-4",strokeWidth:2})})})]})]})]})]})}),L&&a&&a.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:a.map((I,D)=>u.jsx("button",{type:"button",onClick:()=>G(I),disabled:S,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-${D}`))})]})]})});function ds({title:e}){return u.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-text-center cuadra-py-6",children:u.jsx("h2",{className:"cuadra-text-4xl cuadra-font-normal cuadra-text-muted-foreground cuadra-tracking-tight",style:{fontFamily:"var(--cuadra-font-logo), Outfit, -apple-system, sans-serif"},children:e})})}function hs(){return u.jsx(T.MessagePrimitive.Root,{className:"cuadra-flex cuadra-w-full cuadra-justify-end cuadra-py-2.5",children:u.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-end cuadra-gap-2 cuadra-max-w-[80%]",children:[u.jsx(T.MessagePrimitive.Attachments,{components:{Attachment:()=>{const e=T.useAssistantState(({attachment:s})=>s);if(!e)return null;const r=e.type==="image",t=e.file,a=e.content?.find(s=>s.type==="image"),i=t?URL.createObjectURL(t):a?.image;return u.jsx("div",{className:"cuadra-mb-1",children:r&&i?u.jsx("img",{src:i,alt:e.name||"Attachment",className:"cuadra-rounded-2xl cuadra-max-h-64 cuadra-max-w-full cuadra-object-contain",style:{border:"1px solid rgba(0,0,0,0.06)"}}):u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-rounded-xl cuadra-px-3 cuadra-py-2",style:{backgroundColor:"var(--cuadra-muted)",border:"1px solid rgba(0,0,0,0.06)"},children:[u.jsx(Nt,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground"}),u.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground font-brand",children:e.name||"Attachment"})]})})}}}),u.jsx("div",{className:"cuadra-break-words cuadra-text-foreground font-brand",style:{borderRadius:"1.25rem",backgroundColor:"var(--cuadra-muted)",paddingLeft:"1rem",paddingRight:"1rem",paddingTop:"0.625rem",paddingBottom:"0.625rem",wordBreak:"break-word",fontSize:"0.9375rem",lineHeight:"1.625"},children:u.jsx(T.MessagePrimitive.Parts,{components:{Text:({text:e})=>u.jsx(Ze,{content:e||""})}})})]})})}function fs({text:e}){const[r,t]=y.useState(!1),a=T.useAssistantState(({message:i})=>i?.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:()=>t(!r),className:"cuadra-flex cuadra-items-center cuadra-gap-1.5 cuadra-py-1 cuadra-text-sm cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-colors font-brand",children:[u.jsx(Ke,{className:`cuadra-h-3.5 cuadra-w-3.5 cuadra-shrink-0 cuadra-transition-transform cuadra-duration-200 ${r?"":"cuadra--rotate-90"}`}),u.jsx("span",{children:"Reasoning"})]}),u.jsx("div",{className:`cuadra-overflow-hidden cuadra-transition-all cuadra-duration-200 cuadra-ease-out ${r?"cuadra-max-h-[2000px] cuadra-opacity-100":"cuadra-max-h-0 cuadra-opacity-0"}`,children:u.jsx("div",{className:"cuadra-pl-5 cuadra-pt-2 cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand",children:u.jsx(Ze,{content:e})})})]}):null}function ms(){return u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2.5 cuadra-text-muted-foreground cuadra-text-sm font-brand cuadra-py-3",children:[u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1",children:[u.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"0ms",backgroundColor:"var(--cuadra-primary)",opacity:.7}}),u.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"150ms",backgroundColor:"var(--cuadra-primary)",opacity:.5}}),u.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"300ms",backgroundColor:"var(--cuadra-primary)",opacity:.3}})]}),u.jsx("span",{children:"Thinking..."})]})}function ps(){const e=T.useAssistantState(({message:n})=>n?.status?.type==="running"),r=T.useAssistantState(({message:n})=>{const c=n?.content;return!c||!Array.isArray(c)?!1:c.some(o=>!!(o.type==="text"&&o.text&&o.text.length>0||o.type==="reasoning"&&o.text&&o.text.length>0))}),t=y.useRef(!1),[a,i]=y.useState(null);y.useEffect(()=>{if(e&&r&&!t.current){const n=ee.getCurrentMessageId();n&&(t.current=!0,i(n))}},[e,r]);const s=y.useSyncExternalStore(n=>ee.subscribe(n),()=>{if(a){const n=ee.getForMessage(a);return n.sources?.length?n.sources:null}if(e&&r){const n=ee.getCurrentMessageId();if(n){const c=ee.getForMessage(n);return c.sources?.length?c.sources:null}}return null},()=>null);return u.jsx(T.MessagePrimitive.Root,{className:"cuadra-flex cuadra-w-full cuadra-justify-start cuadra-py-2.5",children:u.jsxs("div",{className:"cuadra-text-foreground cuadra-max-w-full cuadra-break-words font-brand",style:{fontSize:"0.9375rem",lineHeight:"1.75"},children:[u.jsx(T.MessagePrimitive.Parts,{components:{Text:({text:n})=>u.jsx(Ze,{content:n||""}),Reasoning:({text:n})=>u.jsx(fs,{text:n||""})}}),e&&!r&&u.jsx(ms,{}),s&&s.length>0&&u.jsx(hr,{sources:s})]})})}function Te({label:e,children:r}){return u.jsxs("span",{className:"cuadra-relative cuadra-inline-flex cuadra-group/tip",children:[r,u.jsx("span",{className:"cuadra-absolute cuadra-bottom-full cuadra-left-1/2 cuadra-mb-1.5 cuadra-hidden group-hover/tip:cuadra-flex cuadra-items-center cuadra-whitespace-nowrap cuadra-rounded-md cuadra-px-2 cuadra-py-1 cuadra-text-[10px] cuadra-pointer-events-none cuadra-z-50 font-brand",style:{backgroundColor:"var(--cuadra-popover)",color:"var(--cuadra-foreground)",boxShadow:"0 2px 8px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)",transform:"translateX(-50%)"},children:e})]})}function gs({models:e,selectedModelId:r,onModelChange:t,threadIsEmpty:a,onNewChat:i}){const[s,n]=y.useState(!1),c=e.find(l=>l.id===r)||e[0];if(!c)return null;const o=async l=>{n(!1),!a&&l!==r&&await i?.(),t?.(l)};return u.jsxs("div",{className:"cuadra-relative",children:[u.jsxs("button",{type:"button",onClick:()=>n(!s),className:"cuadra-flex cuadra-items-center cuadra-gap-1 cuadra-px-2.5 cuadra-py-1.5 cuadra-rounded-lg cuadra-text-xs cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-colors font-brand",children:[u.jsx("span",{children:c.name}),c.supportsReasoning&&u.jsx(Te,{label:"Reasoning",children:u.jsx(ct,{className:"cuadra-h-3 cuadra-w-3"})}),c.supportsVision&&u.jsx(Te,{label:"Vision",children:u.jsx(lt,{className:"cuadra-h-3 cuadra-w-3"})}),u.jsx(Ke,{className:"cuadra-h-3 cuadra-w-3"})]}),s&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:()=>n(!1)}),u.jsx("div",{className:"cuadra-absolute cuadra-bottom-full cuadra-right-0 cuadra-mb-2 cuadra-z-50 cuadra-rounded-xl cuadra-min-w-[200px] cuadra-py-1",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 4px 24px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)"},children:e.map(l=>u.jsxs("button",{type:"button",className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-justify-between cuadra-gap-3 cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted/60 cuadra-transition-colors font-brand",onClick:()=>o(l.id),children:[u.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-min-w-0",children:[u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1.5",children:[u.jsx("span",{className:"cuadra-text-foreground cuadra-truncate",children:l.name}),l.supportsReasoning&&u.jsx(Te,{label:"Reasoning",children:u.jsx(ct,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})}),l.supportsVision&&u.jsx(Te,{label:"Vision",children:u.jsx(lt,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})})]}),l.description&&u.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground",children:l.description})]}),l.id===r&&u.jsx(It,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-primary cuadra-flex-shrink-0"})]},l.id))})]})]})}function xs(){const e=T.useAssistantState(({threadListItem:i})=>i?.title??null),[r,t]=y.useState(!1),a=e||"Untitled chat";return u.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-px-3 cuadra-py-2 cuadra-min-h-[48px]",children:u.jsxs("div",{className:"cuadra-relative",children:[u.jsxs("button",{type:"button",onClick:()=>t(!r),className:"cuadra-flex cuadra-items-center cuadra-gap-1 cuadra-text-sm cuadra-text-foreground hover:cuadra-bg-muted/60 cuadra-rounded-lg cuadra-px-2 cuadra-py-1.5 cuadra-transition-colors font-brand",children:[u.jsx("span",{className:"cuadra-font-medium cuadra-truncate cuadra-max-w-[200px]",children:a}),u.jsx(Ke,{className:`cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground cuadra-flex-shrink-0 cuadra-transition-transform cuadra-duration-200 ${r?"cuadra-rotate-180":""}`})]}),r&&u.jsx(ys,{onClose:()=>t(!1)})]})})}function ys({onClose:e}){return u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:e}),u.jsx("div",{className:"cuadra-absolute cuadra-left-0 cuadra-top-full cuadra-mt-1 cuadra-z-50 cuadra-w-[300px] cuadra-rounded-xl cuadra-overflow-hidden cuadra-flex cuadra-flex-col",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 4px 24px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)"},children:u.jsxs(T.ThreadListPrimitive.Root,{className:"cuadra-flex cuadra-flex-col",children:[u.jsx("div",{className:"cuadra-px-2 cuadra-py-1.5",children:u.jsxs(T.ThreadListPrimitive.New,{className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-gap-2.5 cuadra-px-3 cuadra-py-2 cuadra-rounded-lg cuadra-text-sm cuadra-text-foreground hover:cuadra-bg-muted cuadra-transition-colors cuadra-cursor-pointer font-brand",onClick:e,children:[u.jsx(_t,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"New Chat"]})}),u.jsx(bs,{onSelect:e})]})})]})}function bs({onSelect:e}){const r=T.useAssistantState(({threads:i})=>i?.threadIds??[]),t=T.useAssistantState(({threads:i})=>i?.newThreadId);return r.some(i=>i!==t)?u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"cuadra-mx-3 cuadra-my-0.5",style:{borderTop:"1px solid rgba(0,0,0,0.06)"}}),u.jsx("div",{className:"cuadra-overflow-y-auto cuadra-px-2 cuadra-pb-1.5 scrollbar-thin",style:{maxHeight:"340px"},children:u.jsx(T.ThreadListPrimitive.Items,{components:{ThreadListItem:i=>u.jsx(ws,{...i,onSelect:e})}})})]}):null}function ws({onSelect:e}){const r=T.useThreadListItem(),t=T.useThreadListItemRuntime(),a=T.useAssistantRuntime(),i=T.useThread(x=>x.threadId),s=r?.id===i,[n,c]=y.useState(!1),[o,l]=y.useState(!1),[f,d]=y.useState(r?.title||""),[m,g]=y.useState(!1),h=async()=>{if(!r?.remoteId||!f||f===r.title){l(!1);return}try{g(!0),await t.rename(f)}catch{}finally{g(!1),l(!1)}},b=async x=>{x.stopPropagation();try{await t.delete(),s&&await a.switchToNewThread()}catch(w){console.error("[CuadraChat] Failed to delete thread:",w)}};return y.useEffect(()=>{r?.title&&!o&&d(r.title)},[r?.title,o]),r?u.jsxs(T.ThreadListItemPrimitive.Root,{className:`cuadra-relative cuadra-flex cuadra-items-center cuadra-rounded-lg cuadra-transition-colors cuadra-cursor-pointer ${s?"cuadra-bg-muted":"hover:cuadra-bg-muted/60"}`,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:[o?u.jsx("div",{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0",onClick:x=>x.stopPropagation(),onMouseDown:x=>x.stopPropagation(),onKeyDown:x=>x.stopPropagation(),onKeyUp:x=>x.stopPropagation(),onKeyPress:x=>x.stopPropagation(),children:u.jsx("input",{className:"cuadra-w-full cuadra-bg-transparent cuadra-border-0 cuadra-border-b cuadra-text-sm cuadra-text-foreground cuadra-py-0.5 cuadra-px-0 cuadra-outline-none font-brand",style:{borderBottomColor:"var(--cuadra-primary)",borderBottomWidth:"1.5px"},value:f,onChange:x=>d(x.target.value),onKeyDown:x=>{x.stopPropagation(),x.key==="Enter"&&h(),x.key==="Escape"&&(l(!1),d(r.title||""))},onBlur:()=>void h(),disabled:m,autoFocus:!0})}):u.jsx(T.ThreadListItemPrimitive.Trigger,{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0 cuadra-cursor-pointer",onClick:()=>e?.(),children:u.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground cuadra-truncate cuadra-block cuadra-text-left font-brand",children:r.title||"Chat"})}),(n||s)&&!o&&u.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-0.5 cuadra-mr-1.5 cuadra-flex-shrink-0",children:[u.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-background/60 cuadra-transition-colors",onClick:x=>{x.stopPropagation(),l(!0),d(r.title||"Chat")},title:"Rename",children:u.jsx(Wr,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})}),u.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-destructive/10 cuadra-transition-colors",onClick:b,title:"Delete",children:u.jsx(Qr,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-destructive"})})]})]}):null}const Oe=({children:e,className:r="",paddingX:t="px-0",paddingY:a="py-0",borderSizePx:i=2,style:s,contentStyle:n})=>u.jsx("div",{className:`cuadra-relative cuadra-bg-background md:cuadra-rounded-lg cuadra-overflow-hidden cuadra-flex cuadra-flex-col ${t} ${a} ${r}`,style:{border:i>0?`${i}px solid var(--cuadra-primary)`:"none",...s,...n},children:e}),ks=y.createContext(void 0),Be=({children:e,value:r})=>u.jsx(ks.Provider,{value:r,children:e});function Cs(){y.useEffect(()=>{if(document.querySelector("style[data-cuadra-uikit]"))return;const r=document.createElement("div");r.className="cuadra-flex",document.body.appendChild(r);const t=window.getComputedStyle(r).display==="flex";if(document.body.removeChild(r),t)return;const a=document.createElement("link");a.setAttribute("data-cuadra-uikit","true"),a.rel="stylesheet",a.type="text/css";const i=["/node_modules/@cuadra-ai/uikit/dist/uikit.css",new URL("../dist/uikit.css",typeof document>"u"?require("url").pathToFileURL(__filename).href:fe&&fe.tagName.toUpperCase()==="SCRIPT"&&fe.src||new URL("index.cjs",document.baseURI).href).href];let s=!1;for(const n of i)if(a.href=n,a.onload=()=>{s=!0},a.onerror=()=>{},document.head.appendChild(a),s)break},[])}const vs=y.forwardRef(function({config:r},t){Cs();const a=y.useRef(null),i=y.useRef(!1),{baseUrl:s,proxyUrl:n,sessionToken:c,mode:o="multiChat",modelMode:l="fixed",modelId:f,onModelChange:d,ephemeral:m=!1,systemPrompt:g,enableReasoning:h=!1,initialThreadId:b,welcomeTitle:x,welcomeSubtitle:w,extraTopPadding:C,suggestions:v,inputPlaceholder:_,preMadeResponseDelay:S=1e3,streamingSpeed:P=50,initialMessage:$,initialPreMadeQA:A,theme:L="system",onError:p,onChatCreated:R,onUserMessage:G,onThreadIdUpdate:H,enableAttachments:I=!1,supportsVision:D,onBeforeRequest:B,mockResponseOnBlocked:k}=r;y.useImperativeHandle(t,()=>({sendMessage:N=>{a.current?.sendMessage(N)},sendPreMadeQA:(N,Z,ie)=>{a.current?.sendPreMadeQA(N,Z,ie)},clearChat:()=>{a.current?.clearChat()}}),[]),y.useEffect(()=>{if(i.current)return;const N=setTimeout(()=>{A?(i.current=!0,a.current?.sendPreMadeQA(A.question,A.answer,{delay:S,streamingSpeed:P})):$&&(i.current=!0,a.current?.sendMessage($))},500);return()=>clearTimeout(N)},[$,A,S,P]);const j=n||s||"",E=!!n,U=y.useMemo(()=>new Et(j,c||void 0,E),[j,c,E]),[F,M]=y.useState(null),[V,Y]=y.useState(!1),[J,ge]=y.useState(null),[Ee,X]=y.useState(!1);y.useEffect(()=>{o==="multiChat"&&X(!0)},[o]);const ne=y.useCallback(async()=>{if(l==="selector"){Y(!0),ge(null);try{const N=await U.listModels();M(N)}catch(N){ge(N instanceof Error?N:new Error("Failed to load models"))}finally{Y(!1)}}},[U,l]);y.useEffect(()=>{l==="selector"&&ne()},[l,ne]),y.useEffect(()=>(typeof window<"u"&&(window.__cuadraUIKitRefetchModels=ne),()=>{typeof window<"u"&&delete window.__cuadraUIKitRefetchModels}),[ne]);const[K,rt]=y.useState(l==="fixed"&&f||null),at=y.useRef(K),ke=y.useCallback(N=>{const Z=at.current;rt(N),at.current=N,d?.(N),Z!==null&&Z!==N&&o==="multiChat"&&setTimeout(()=>{const ie=window.__cuadraThreadListRuntime;if(ie?.threads?.switchToNewThread)try{ie.threads.switchToNewThread()}catch{}else if(ie?.threads?.createThread)try{ie.threads.createThread()}catch{}else if(ie?.switchToNewThread)try{ie.switchToNewThread()}catch{}},100)},[d,o]);y.useEffect(()=>{if(l==="selector"&&F?.items&&F.items.length>0&&!K){const N=F.items[0];if(N?.id){const Z=N.id;rt(Z),d?.(Z)}}},[l,F?.items,K,d]);const xr=l==="fixed"?!!f:!!K,yr=y.useMemo(()=>D!==void 0?D:l==="selector"&&K&&F?.items?F.items.find(Z=>Z.id===K)?.supportsVision??!0:!0,[D,l,K,F?.items]),Re=y.useMemo(()=>(F?.items||[]).filter(N=>N?.id&&N?.displayName).map(N=>({id:N.id,name:N.displayName,supportsVision:N.supportsVision??!1,supportsReasoning:N.supportsReasoning??!1})),[F]),Le=y.useMemo(()=>({currentModelId:K||"",models:Re,modelsLoading:V,modelsError:J,onModelChange:ke,refetchModels:ne}),[K,Re,V,J,ke,ne]);return l==="selector"&&V||o==="multiChat"&&Ee?u.jsx(Be,{value:Le,children:u.jsx(Oe,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",borderSizePx:r.borderless?0:2,children:u.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:u.jsx(At,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"})})})}):l==="selector"&&!xr&&J?u.jsx(Be,{value:Le,children:u.jsx(Oe,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",children:u.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:u.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2",children:u.jsx("p",{className:"cuadra-text-sm cuadra-text-destructive font-brand",children:"Failed to load models"})})})})}):u.jsx("div",{className:"cuadra-uikit cuadra-h-full cuadra-w-full",style:{height:"100%",width:"100%"},children:u.jsx(Be,{value:Le,children:u.jsx(Sa,{baseUrl:E?j:s||j,sessionToken:c,isProxyMode:E,mode:o,modelMode:l,modelId:K||f||void 0,onModelChange:ke,ephemeral:m,systemPrompt:g,enableReasoning:h,initialThreadId:b,enableAttachments:I,supportsVision:yr,onError:p,onChatCreated:R,onUserMessage:G,onThreadIdUpdate:H,onBeforeRequest:B,mockResponseOnBlocked:k,onChatsLoaded:()=>{o==="multiChat"&&X(!1)},children:u.jsx(Oe,{paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",className:`cuadra-h-full ${r.containerClass||""}`,borderSizePx:r.borderless?0:2,style:{height:"100%"},children:u.jsx("div",{className:"cuadra-h-full cuadra-flex cuadra-relative",style:{height:"100%"},children:u.jsx("div",{className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:u.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0",children:u.jsx(us,{ref:a,welcomeTitle:x,welcomeSubtitle:w,extraTopPadding:C,suggestions:v,inputPlaceholder:_,enableAttachments:I,preMadeResponseDelay:S,streamingSpeed:P,safeArea:r.safeArea,showChatHeader:o==="multiChat",models:l==="selector"?Re:void 0,selectedModelId:K||void 0,onModelChange:l==="selector"?ke:void 0,theme:L})})})})})})})})});function fr(e,r=":root"){if(typeof document>"u")return;const t=document.documentElement,a=[];if(e.light){js(e.light,t);const i=jt(e.light);i&&a.push(`.cuadra-uikit { ${i} }`)}if(e.dark){const i=jt(e.dark);i&&(a.push(`.dark { ${i} }`),a.push(`.dark .cuadra-uikit { ${i} }`))}if(a.length>0){let i=document.getElementById("cuadra-theme-custom");i||(i=document.createElement("style"),i.id="cuadra-theme-custom",document.head.appendChild(i)),i.textContent=a.join(`
|
|
21
|
+
`)}}const Ts={background:"background",foreground:"foreground",card:"card",cardForeground:"card-foreground",popover:"popover",popoverForeground:"popover-foreground",primary:"primary",primaryForeground:"primary-foreground",primaryLight:"primary-light",primaryLighter:"primary-lighter",secondary:"secondary",secondaryForeground:"secondary-foreground",muted:"muted",mutedForeground:"muted-foreground",accent:"accent",accentForeground:"accent-foreground",border:"border",input:"input",ring:"ring",destructive:"destructive",destructiveForeground:"destructive-foreground",success:"success",successForeground:"success-foreground",info:"info",infoForeground:"info-foreground",warning:"warning",warningForeground:"warning-foreground"};function mr(e){const r=Ts[e];return r?`--cuadra-${r}`:`--cuadra-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function js(e,r){Object.entries(e).forEach(([t,a])=>{if(a){const i=mr(t);r.style.setProperty(i,a)}})}function jt(e){return Object.entries(e).map(([r,t])=>t?`${mr(r)}: ${t};`:"").filter(Boolean).join(" ")}function Ss(){if(typeof document>"u")return;const e=document.documentElement;Array.from(e.style).filter(i=>i.startsWith("--cuadra-")).forEach(i=>e.style.removeProperty(i));const t=document.getElementById("cuadra-theme-custom");t&&t.remove();const a=document.getElementById("cuadra-theme-dark");a&&a.remove()}function Is({onReset:e,error:r}){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:r?.message||"An unexpected error occurred. Please try again."}),u.jsx("button",{onClick:e,className:"cuadra-px-4 cuadra-py-2 cuadra-text-sm cuadra-font-medium cuadra-rounded-md cuadra-transition-colors",style:{backgroundColor:"var(--cuadra-primary)",color:"hsl(var(--cuadra-primary-foreground))"},children:"Try Again"})]})}class tt extends y.Component{constructor(t){super(t);z(this,"reset",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,a){this.props.onError?.(t,a)}render(){if(this.state.hasError){const{fallback:t}=this.props,{error:a}=this.state;return typeof t=="function"?t(a,this.reset):t||u.jsx(Is,{error:a,onReset:this.reset})}return this.props.children}}function Ms(e,r){const t=a=>u.jsx(tt,{...r,children:u.jsx(e,{...a})});return t.displayName=`withErrorBoundary(${e.displayName||e.name||"Component"})`,t}const pe=y.createContext(null);pe.displayName="CuadraChatContext";function As(){const e=y.useContext(pe);if(e===null)throw new Error("useCuadraChat must be used within a CuadraChatProvider. Wrap your component tree with <CuadraChatProvider>...</CuadraChatProvider>");return{controls:e.controls,isReady:e.controls!==null}}function Ns(){const e=y.useContext(pe);return e===null?null:{controls:e.controls,isReady:e.controls!==null}}function _s({children:e}){const[r,t]=y.useState(null),a=y.useCallback(n=>{t(n)},[]),i=y.useCallback(()=>{t(null)},[]),s=y.useMemo(()=>({controls:r,registerControls:a,unregisterControls:i}),[r,a,i]);return u.jsx(pe.Provider,{value:s,children:e})}function pr(e){return"connection"in e&&typeof e.connection=="object"}function gr(e){return pr(e)?Ps(e):Es(e)}function Ps(e){return{connection:{baseUrl:e.connection.baseUrl||"",proxyUrl:e.connection.proxyUrl||"",sessionToken:e.connection.sessionToken??null},chat:{mode:e.chat?.mode??"multiChat",modelMode:e.chat?.modelMode??"fixed",modelId:e.chat?.modelId??"",systemPrompt:e.chat?.systemPrompt??"",ephemeral:e.chat?.ephemeral??!1,enableReasoning:e.chat?.enableReasoning??!1,enableAttachments:e.chat?.enableAttachments??!1,supportsVision:e.chat?.supportsVision,initialThreadId:e.chat?.initialThreadId},ui:{theme:e.ui?.theme??"system",customTheme:e.ui?.customTheme,showThemeToggle:e.ui?.showThemeToggle??!0,language:e.ui?.language,welcomeTitle:e.ui?.welcomeTitle??"Hi, how can I help you today?",welcomeSubtitle:e.ui?.welcomeSubtitle??"Start exploring our platform and discover what you can build.",suggestions:e.ui?.suggestions,inputPlaceholder:e.ui?.inputPlaceholder??"Type your message...",extraTopPadding:e.ui?.extraTopPadding,borderless:e.ui?.borderless,safeArea:e.ui?.safeArea,orgName:e.ui?.orgName,primaryColor:e.ui?.primaryColor},preMade:{responseDelay:e.preMade?.responseDelay??1e3,streamingSpeed:e.preMade?.streamingSpeed??50},initial:{message:e.initial?.message,preMadeQA:e.initial?.preMadeQA},interceptors:{onBeforeRequest:e.interceptors?.onBeforeRequest,mockResponseOnBlocked:e.interceptors?.mockResponseOnBlocked},callbacks:{onChatCreated:e.callbacks?.onChatCreated,onError:e.callbacks?.onError,onUserMessage:e.callbacks?.onUserMessage,onModelChange:e.callbacks?.onModelChange,onThreadIdUpdate:e.callbacks?.onThreadIdUpdate,onLogout:e.callbacks?.onLogout},className:e.className,errorFallback:e.errorFallback}}function Es(e){return typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[CuadraUIKit] Using legacy flat props format. Consider migrating to grouped props for better organization.
|
|
22
|
+
See: https://docs.cuadra.ai/guides/uikit-migration`),{connection:{baseUrl:e.baseUrl||"",proxyUrl:e.proxyUrl||"",sessionToken:e.sessionToken??null},chat:{mode:e.mode??"multiChat",modelMode:e.modelMode??"fixed",modelId:e.modelId??"",systemPrompt:e.systemPrompt??"",ephemeral:e.ephemeral??!1,enableReasoning:e.enableReasoning??!1,enableAttachments:e.enableAttachments??!1,supportsVision:e.supportsVision,initialThreadId:e.initialThreadId},ui:{theme:e.theme??"system",customTheme:e.customTheme,showThemeToggle:e.showThemeToggle??!0,language:e.language,welcomeTitle:e.welcomeTitle??"Hi, how can I help you today?",welcomeSubtitle:e.welcomeSubtitle??"Start exploring our platform and discover what you can build.",suggestions:e.suggestions,inputPlaceholder:e.inputPlaceholder??"Type your message...",extraTopPadding:e.extraTopPadding,borderless:!1,safeArea:!1,orgName:void 0,primaryColor:void 0},preMade:{responseDelay:e.preMadeResponseDelay??1e3,streamingSpeed:e.streamingSpeed??50},initial:{message:e.initialMessage,preMadeQA:e.initialPreMadeQA},interceptors:{onBeforeRequest:e.onBeforeRequest,mockResponseOnBlocked:e.mockResponseOnBlocked},callbacks:{onChatCreated:e.onChatCreated,onError:e.onError,onUserMessage:e.onUserMessage,onModelChange:e.onModelChange,onThreadIdUpdate:e.onThreadIdUpdate,onLogout:e.onLogout},className:e.className,errorFallback:e.errorFallback}}const Rs=y.forwardRef(function({config:r},t){const a=y.useRef(null),i=y.useContext(pe);y.useEffect(()=>{r.ui.customTheme&&fr(r.ui.customTheme)},[r.ui.customTheme]),y.useEffect(()=>{if(r.ui.primaryColor&&typeof document<"u"){const c=document.documentElement,o=l=>{const f=l.replace("#",""),d=parseInt(f.slice(0,2),16)/255,m=parseInt(f.slice(2,4),16)/255,g=parseInt(f.slice(4,6),16)/255,h=Math.max(d,m,g),b=Math.min(d,m,g);let x=0,w=0;const C=(h+b)/2;if(h!==b){const v=h-b;switch(w=C>.5?v/(2-h-b):v/(h+b),h){case d:x=((m-g)/v+(m<g?6:0))/6;break;case m:x=((g-d)/v+2)/6;break;case g:x=((d-m)/v+4)/6;break}}return`${Math.round(x*360)} ${Math.round(w*100)}% ${Math.round(C*100)}%`};try{const l=o(r.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")}}},[r.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(t,()=>s,[]),y.useEffect(()=>{if(i)return i.registerControls(s),()=>i.unregisterControls()},[i,s]),y.useEffect(()=>(typeof window<"u"&&(process.env.NODE_ENV==="development"&&console.warn("[CuadraUIKit] window.__cuadraChatControls is deprecated. Use CuadraChatProvider and useCuadraChat() hook instead. See: https://docs.cuadra.ai/guides/uikit-migration"),window.__cuadraChatControls=s),()=>{typeof window<"u"&&delete window.__cuadraChatControls}),[s]);const n={baseUrl:r.connection.baseUrl||void 0,proxyUrl:r.connection.proxyUrl||void 0,sessionToken:r.connection.sessionToken,mode:r.chat.mode,modelMode:r.chat.modelMode,modelId:r.chat.modelId||void 0,systemPrompt:r.chat.systemPrompt||void 0,ephemeral:r.chat.ephemeral,enableReasoning:r.chat.enableReasoning,enableAttachments:r.chat.enableAttachments,supportsVision:r.chat.supportsVision,initialThreadId:r.chat.initialThreadId,theme:r.ui.theme,showThemeToggle:r.ui.showThemeToggle,language:r.ui.language,welcomeTitle:r.ui.welcomeTitle,welcomeSubtitle:r.ui.welcomeSubtitle,suggestions:r.ui.suggestions,inputPlaceholder:r.ui.inputPlaceholder,extraTopPadding:r.ui.extraTopPadding,containerClass:r.className,borderless:r.ui.borderless,safeArea:r.ui.safeArea,orgName:r.ui.orgName,primaryColor:r.ui.primaryColor,preMadeResponseDelay:r.preMade.responseDelay,streamingSpeed:r.preMade.streamingSpeed,initialMessage:r.initial.message,initialPreMadeQA:r.initial.preMadeQA,onBeforeRequest:r.interceptors.onBeforeRequest,mockResponseOnBlocked:r.interceptors.mockResponseOnBlocked,onChatCreated:r.callbacks.onChatCreated,onError:r.callbacks.onError,onUserMessage:r.callbacks.onUserMessage,onModelChange:r.callbacks.onModelChange,onThreadIdUpdate:r.callbacks.onThreadIdUpdate,onLogout:r.callbacks.onLogout};return u.jsx(vs,{ref:a,config:n})}),Ls=y.forwardRef(function(r,t){const a=gr(r),i=a.errorFallback;return u.jsx(tt,{fallback:i,onError:(s,n)=>{a.callbacks.onError?.(s),process.env.NODE_ENV==="development"&&console.error("[CuadraChat] Error caught by boundary:",s,n)},children:u.jsx(Rs,{ref:t,config:a})})});exports.AttachmentValidationError=le;exports.Badge=et;exports.CuadraChat=Ls;exports.CuadraChatContext=pe;exports.CuadraChatProvider=_s;exports.CuadraErrorBoundary=tt;exports.SourceCitations=hr;exports.applyTheme=fr;exports.createAttachmentAdapter=Qe;exports.escapeHtml=aa;exports.generateSecureUUID=Pt;exports.isV2Props=pr;exports.isValidUrl=ea;exports.normalizeCuadraChatProps=gr;exports.removeTheme=Ss;exports.sanitizeSystemPrompt=Zr;exports.streamingMetadataStore=ee;exports.useCuadraChat=As;exports.useCuadraChatOptional=Ns;exports.validateBaseUrl=ta;exports.withErrorBoundary=Ms;
|
|
22
23
|
//# sourceMappingURL=index.cjs.map
|