@cuadra-ai/uikit 0.4.6 → 0.4.7
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/adapters/threadListAdapter.d.ts +4 -2
- package/dist/adapters/threadListAdapter.d.ts.map +1 -1
- package/dist/components/SimpleThread.d.ts.map +1 -1
- package/dist/index.cjs +16 -16
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +2022 -1614
- package/dist/index.mjs.map +1 -1
- package/dist/lib/cuadraChatClient.d.ts +6 -1
- package/dist/lib/cuadraChatClient.d.ts.map +1 -1
- package/dist/types/cuadra.d.ts +16 -0
- package/dist/types/cuadra.d.ts.map +1 -1
- package/dist/uikit.css +1 -1
- package/dist/widget/cuadra-uikit.css +1 -1
- package/dist/widget/cuadra-uikit.umd.js +22 -22
- package/dist/widget/cuadra-uikit.umd.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var dr=Object.defineProperty;var fr=(e,r,t)=>r in e?dr(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var $=(e,r,t)=>fr(e,typeof r!="symbol"?r+"":r,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react/jsx-runtime"),y=require("react"),T=require("@assistant-ui/react");require("@assistant-ui/react-markdown/styles/dot.css");const $e=require("@assistant-ui/react-markdown");var ue=typeof document<"u"?document.currentScript:null;let me=!1,rt=!1;function nt(){if(rt||(rt=!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){me=!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 n=window.getComputedStyle(t).display==="flex";if(document.body.removeChild(t),n){me=!0;return}}catch{}hr()}function hr(){if(me)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:ue&&ue.tagName.toUpperCase()==="SCRIPT"&&ue.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=()=>{me=!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 n=()=>{t<r.length&&(e.href=r[t++],e.onerror=n,e.onload=()=>{me=!0})};n()},document.head.appendChild(e)}typeof document<"u"&&typeof window<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",nt):nt());const mr=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),pr=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(r,t,n)=>n?n.toUpperCase():t.toLowerCase()),at=e=>{const r=pr(e);return r.charAt(0).toUpperCase()+r.slice(1)},bt=(...e)=>e.filter((r,t,n)=>!!r&&r.trim()!==""&&n.indexOf(r)===t).join(" ").trim(),gr=e=>{for(const r in e)if(r.startsWith("aria-")||r==="role"||r==="title")return!0};var xr={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 yr=y.forwardRef(({color:e="currentColor",size:r=24,strokeWidth:t=2,absoluteStrokeWidth:n,className:i="",children:o,iconNode:a,...c},s)=>y.createElement("svg",{ref:s,...xr,width:r,height:r,stroke:e,strokeWidth:n?Number(t)*24/Number(r):t,className:bt("lucide",i),...!o&&!gr(c)&&{"aria-hidden":"true"},...c},[...a.map(([l,f])=>y.createElement(l,f)),...Array.isArray(o)?o:[o]]));const W=(e,r)=>{const t=y.forwardRef(({className:n,...i},o)=>y.createElement(yr,{ref:o,iconNode:r,className:bt(`lucide-${mr(at(e))}`,`lucide-${e}`,n),...i}));return t.displayName=at(e),t};const br=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],wr=W("arrow-up",br);const kr=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],wt=W("check",kr);const Cr=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],We=W("chevron-down",Cr);const vr=[["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"}]],Tr=W("copy",vr);const jr=[["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"}]],Ir=W("file-spreadsheet",jr);const Ar=[["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"}]],kt=W("file-text",Ar);const Sr=[["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"}]],Mr=W("file-type",Sr);const Pr=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Ct=W("loader-circle",Pr);const _r=[["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"}]],vt=W("paperclip",_r);const Nr=[["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"}]],Er=W("pencil",Nr);const Rr=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Tt=W("plus",Rr);const Lr=[["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"}]],Dr=W("trash-2",Lr);const Fr=[["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"}]],Ur=W("upload",Fr);const zr=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],$r=W("x",zr),Or=[/\[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 Br(e){if(!e||typeof e!="string")return"";let r=e;for(const t of Or)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 qr(e){if(!e||typeof e!="string")return!1;try{const r=new URL(e);return["http:","https:"].includes(r.protocol)}catch{return!1}}function Wr(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:"&&!Hr(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 Hr(e){try{const r=new URL(e);return["localhost","127.0.0.1","[::1]"].includes(r.hostname)}catch{return!1}}function Vr(e){if(!e||typeof e!="string")return"";const r={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};return e.replace(/[&<>"'/]/g,t=>r[t]||t)}function jt(){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 It{constructor(r,t,n=!1){$(this,"baseUrl");$(this,"sessionToken",null);$(this,"isProxyMode",!1);this.baseUrl=r.replace(/\/$/,""),this.isProxyMode=n,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 n=this.getUrl("/v1/chats"),o={"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&&(o.Authorization=`Bearer ${this.sessionToken}`);const a={...r,stream:!0},c=await fetch(n,{method:"POST",headers:o,body:JSON.stringify(a),signal:t,cache:"no-store"});if(!c.ok){const s=await c.json().catch(()=>({}));throw new Error(s.detail||s.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}`),n={"Content-Type":"application/json"};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const i=await fetch(t,{method:"GET",headers:n});if(!i.ok){const o=await i.json().catch(()=>({}));throw new Error(o.detail||o.message||`API error: ${i.status} ${i.statusText}`)}return i.json()}async listChats(r){const t=this.getUrl("/v1/chats"),n=t.startsWith("/")||t.startsWith("./")?new URL(t,window.location.origin):new URL(t);r?.limit&&n.searchParams.set("limit",r.limit.toString()),r?.cursor&&n.searchParams.set("cursor",r.cursor),r?.["expand[]"]&&r["expand[]"].forEach(a=>{n.searchParams.append("expand[]",a)});const i={"Content-Type":"application/json"};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const o=await fetch(n.toString(),{method:"GET",headers:i});if(!o.ok){const a=await o.json().catch(()=>({}));throw new Error(a.detail||a.message||`API error: ${o.status} ${o.statusText}`)}return o.json()}generateIdempotencyKey(){return jt()}async updateChat(r,t){const n=`/v1/chats/${r}`,i=this.getUrl(n),o=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 s=await fetch(o.toString(),{method:"PATCH",headers:c,body:JSON.stringify(t)});if(!s.ok){const f=await s.text();let u={};try{u=JSON.parse(f)}catch{u={detail:f}}throw new Error(u.detail||u.message||`API error: ${s.status} ${s.statusText}`)}if(s.status===204)return{};const l=await s.text();if(!l)return{};try{return JSON.parse(l)}catch{return{}}}async deleteChat(r){const t=`/v1/chats/${r}`,n=this.getUrl(t),i=n.startsWith("/")||n.startsWith("./")?new URL(n,window.location.origin):new URL(n),a={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const c=await fetch(i.toString(),{method:"DELETE",headers:a});if(!c.ok){const s=await c.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${c.status} ${c.statusText}`)}}async generateChatTitle(r,t){const n=`/v1/chats/${r}/title`,i=this.getUrl(n),o=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 s=await fetch(o.toString(),{method:"POST",headers:c,body:t?JSON.stringify(t):void 0});if(!s.ok){const l=await s.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${s.status} ${s.statusText}`)}return s.json()}async listModels(r){const t=this.getUrl("/v1/models"),n=t.startsWith("/")||t.startsWith("./")?new URL(t,window.location.origin):new URL(t);r?.limit&&n.searchParams.set("limit",r.limit.toString()),r?.cursor&&n.searchParams.set("cursor",r.cursor),r?.["expand[]"]&&r["expand[]"].forEach(a=>{n.searchParams.append("expand[]",a)});const i={"Content-Type":"application/json"};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const o=await fetch(n.toString(),{method:"GET",headers:i});if(!o.ok){const a=await o.json().catch(()=>({}));throw new Error(a.detail||a.message||`API error: ${o.status} ${o.statusText}`)}return o.json()}async getModel(r){const t=this.getUrl(`/v1/models/${r}`),n={"Content-Type":"application/json"};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const i=await fetch(t,{method:"GET",headers:n});if(!i.ok){const o=await i.json().catch(()=>({}));throw new Error(o.detail||o.message||`API error: ${i.status} ${i.statusText}`)}return i.json()}async uploadFile(r,t,n){const i=this.getUrl("/v1/files"),o=this.generateIdempotencyKey(),a=new FormData;a.append("file",r),t&&a.append("resource_type",t),n&&a.append("resource_id",n);const c={"Idempotency-Key":o};this.sessionToken&&(c.Authorization=`Bearer ${this.sessionToken}`);const s=await fetch(i,{method:"POST",headers:c,body:a});if(!s.ok){const l=await s.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${s.status} ${s.statusText}`)}return s.json()}}async function*Kr(e,r){const t=e.getReader(),n=new TextDecoder;let i="";try{for(;;){if(r?.aborted){t.cancel();break}const{done:o,value:a}=await t.read();if(o)break;i+=n.decode(a,{stream:!0});const c=i.split(`
|
|
4
4
|
|
|
5
|
-
`);i=c.pop()||"";for(const s of c)if(s.startsWith("data: ")){const l=s.slice(6);if(l.trim()==="[DONE]"){yield{done:!0};continue}try{yield JSON.parse(l)}catch{}}}}finally{t.releaseLock()}}function Ur(e){return e.map(r=>{let t="";if(typeof r.content=="string")t=r.content;else if(Array.isArray(r.content)){const n=r.content.find(i=>i.type==="text");n&&typeof n=="object"&&"text"in n&&(t=n.text)}return{role:r.role,content:t}})}function zr(e){return{id:e.id,role:e.role,content:[{type:"text",text:e.content}],createdAt:new Date(e.createdAt),metadata:{custom:{}},...e.role==="assistant"&&{status:{type:"complete",reason:"stop"},metadata:{unstable_state:null,unstable_annotations:[],unstable_data:[],steps:[],custom:{}}},...e.role==="user"&&{attachments:[]}}}const de=new Map,Ue=new Map;function $r(e,r){return{async list(){const t=[];let i,o=0;do{const c=await e.listChats({limit:50,cursor:i}),s=c.items||[];Array.isArray(s)&&s.length>0&&t.push(...s),i=c.nextCursor||void 0,o++}while(i&&o<50);return{threads:t.map(c=>{const s=c.id;return!s||c.deletedAt?null:{status:"regular",remoteId:s,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:de.get(t)||t,externalId:void 0}},async rename(t,n){const i=de.get(t)||t;await e.updateChat(i,{title:n})},async archive(t){},async unarchive(t){},async delete(t){const n=de.get(t)||t;await e.deleteChat(n)},async generateTitle(t,n){return new ReadableStream},async fetch(t){try{const n=await e.getChat(t);return{status:"regular",remoteId:n.id||t,title:n.title||"Chat",createdAt:n.createdAt?new Date(n.createdAt):new Date,updatedAt:n.updatedAt?new Date(n.updatedAt):new Date}}catch{return{status:"regular",remoteId:t,createdAt:new Date,updatedAt:new Date}}},updateRemoteId(t,n){de.set(t,n),r?.(t,n)},unstable_Provider:({children:t})=>{const i=T.useThreadListItem()?.remoteId,o=x.useMemo(()=>({async load(){if(!i)return{messages:[]};try{const c=await e.getChat(i);if(!c.messages||c.messages.length===0)return{messages:[]};const s=c.messages.map(h=>zr(h)),l=s.map((h,u)=>({message:h,parentId:u>0?s[u-1].id:null}));for(const h of s)Ue.set(h.id,i);return{messages:l}}catch{return{messages:[]}}},async append(c){}}),[i,e]),a=x.useMemo(()=>({history:o}),[o]);return d.jsx(T.RuntimeAdapterProvider,{adapters:a,children:t})}}}class Or{constructor(){ne(this,"messageMetadata",new Map);ne(this,"currentMessageId",null);ne(this,"listeners",new Set)}setCurrentMessage(r){this.currentMessageId=r}update(r){if(!this.currentMessageId)return;const t=this.messageMetadata.get(this.currentMessageId)||{},n=r.sources;n&&n.length>0&&(this.messageMetadata.set(this.currentMessageId,{...t,sources:n}),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 X=new Or,nt=new Map,ze=[];let ke=[];function Ct(e,r,t=50,n=800){ze.push({question:e,response:r,streamingSpeed:t,initialDelay:n})}function vt(e,r){const{modelId:t,systemPrompt:n,ephemeral:i,enableReasoning:o,onChatCreated:a,onUserMessage:c,onThreadIdUpdate:s,onBeforeRequest:l,mockResponseOnBlocked:h}=r;let u;return{async*run(g){const{messages:p,abortSignal:f}=g,y=ze.shift();if(y){c?.();const w=y.initialDelay??800;if(w>0&&await new Promise(j=>setTimeout(j,w)),f?.aborted)throw new Error("Request aborted");const A=y.response.split(" ");let R="";const D=y.streamingSpeed||50,H=`premade-${Date.now()}`;i&&a?.(H);for(let j=0;j<A.length;j++){if(f?.aborted)throw new Error("Request aborted");R+=(j===0?"":" ")+A[j],yield{content:[{type:"text",text:R}]},await new Promise($=>setTimeout($,D+Math.random()*(D*.5)))}yield{content:[{type:"text",text:R}]},ke.push({role:"user",content:y.question},{role:"assistant",content:y.response});return}let k;for(const w of p){const A=Ue.get(w.id);if(A){k=A;break}}if(!k&&p.length>0){const w=p.find(A=>A.role==="user");if(w){const R=(typeof w.content=="string"?w.content:Array.isArray(w.content)&&w.content.find(D=>D.type==="text")?.text||"").substring(0,50);k=nt.get(R)}}!k&&u&&(k=u),c?.();let b=p,C=-1;for(let w=p.length-1;w>=0;w--)if(p[w].role==="assistant"){C=w;break}(k||C>=0)&&C>=0&&(b=p.slice(C+1));const v=Ur(b);if(ke.length>0&&!k){const w=ke.map(A=>({role:A.role,content:A.content}));v.unshift(...w),ke=[]}const P=[];let S;for(let w=b.length-1;w>=0;w--)if(b[w].role==="user"){S=b[w];break}if(S&&"attachments"in S){const w=S.attachments;if(w&&w.length>0){for(const A of w)if(A.file)try{const R=await e.uploadFile(A.file);P.push(R.id)}catch{}}}const N={messages:v,chatId:k||null,systemPrompt:n,ephemeral:i,enableReasoning:o,stream:!0};if(t&&t.trim()!==""&&(N.modelId=t),P.length>0&&(N.fileIds=P),l&&!await l()){if(h){const A=typeof h=="function"?h():h,R=p.filter($=>$.role==="user"),D=R.length>0?R[R.length-1]:void 0;let H="Message";D&&(typeof D.content=="string"?H=D.content:Array.isArray(D.content)&&(H=D.content.find(Q=>Q.type==="text")?.text||"Message")),Ct(H,A,40,400);const j=ze.shift();if(j){c?.();const $=j.initialDelay??400;if($>0&&await new Promise(W=>setTimeout(W,$)),f?.aborted)throw new Error("Request aborted");const Q=j.response.split(" ");let te="";const xe=j.streamingSpeed||40,ye=`mock-${Date.now()}`;i&&a?.(ye);for(let W=0;W<Q.length;W++){if(f?.aborted)throw new Error("Request aborted");te+=(W===0?"":" ")+Q[W],yield{content:[{type:"text",text:te}]},await new Promise(G=>setTimeout(G,xe+Math.random()*(xe*.3)))}yield{content:[{type:"text",text:te}]};return}}throw new Error("Request blocked")}const O=await e.createOrContinueChat(N,f);let M="",E="",m;const F=[];let V=0,I=!1;const L=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;X.clear(),X.setCurrentMessage(L);const K=()=>{F.length!==V&&(V=F.length,X.update({sources:F.length>0?[...F]:void 0}))},U=()=>{K();const w=[];return E&&w.push({type:"reasoning",text:E}),M&&w.push({type:"text",text:M}),w.length===0&&w.push({type:"text",text:""}),{content:w}};for await(const w of Fr(O,f)){if(f?.aborted)throw new Error("Request aborted");const A=w.id||w.chatId||w.messageId;if(A&&!m){m=A,u=A,a?.(A);for(const j of p)Ue.set(j.id,A);if(p.length>0){const j=p.find($=>$.role==="user");if(j){const Q=(typeof j.content=="string"?j.content:Array.isArray(j.content)&&j.content.find(te=>te.type==="text")?.text||"").substring(0,50);nt.set(Q,A)}}if(s){for(const[j,$]of de.entries())if($===A){s(j,A);break}}}const R=w.sources;if(R&&Array.isArray(R)&&R.length>0)for(const j of R)F.some($=>$.sourceId===j.sourceId)||F.push({sourceId:j.sourceId,filename:j.filename||"Unknown",score:j.score??1,chunkId:j.chunkId,datasetId:j.datasetId});const D=w.reasoning;if(D&&D.length>0&&(E+=D,yield U()),w.type)switch(w.type){case"source-document":w.sourceId&&F.push({sourceId:w.sourceId,filename:w.title||"Unknown",score:1});continue;case"reasoning-start":continue;case"reasoning-delta":w.delta&&(E+=w.delta),(M||E)&&(yield U());continue;case"reasoning-end":(M||E)&&(yield U());continue;case"text-delta":w.delta&&(E&&!I&&!M&&(I=!0,await new Promise(j=>setTimeout(j,400))),M+=w.delta),M&&(yield U());continue;case"error":throw new Error(w.errorText||"Stream error");case"text-start":case"text-end":case"start":case"start-step":case"finish-step":case"finish":continue}const H=w.delta;if(H!=null&&(E&&!I&&!M&&(I=!0,await new Promise(j=>setTimeout(j,400))),M+=H),w.content&&(M+=w.content),w.message&&(M+=w.message.content||""),w.finished){(M||E||F.length>0)&&(yield U());break}(M||E||F.length>0)&&(yield U())}(M||E||F.length>0)&&(yield U())}}}class fe extends Error{constructor(r,t,n){super(r),this.code=t,this.file=n,this.name="AttachmentValidationError"}}const Br=["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"],Wr=[".pdf",".doc",".docx",".xls",".xlsx",".txt",".md",".csv",".json",".jpg",".jpeg",".png",".gif",".webp",".svg"],qr=10*1024*1024;function at(e){if(e===0)return"0 Bytes";const r=1024,t=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(r));return parseFloat((e/Math.pow(r,n)).toFixed(2))+" "+t[n]}function Hr(e){return e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")).toLowerCase():""}function Vr(e,r){const n={"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 n?n.includes(r.toLowerCase()):!0}function Kr(){return typeof crypto<"u"&&crypto.randomUUID?"attachment-"+crypto.randomUUID():"attachment-"+Date.now()+"-"+Math.random().toString(36).slice(2,11)}function We(e={}){const{validation:r={},onValidationError:t,onAttachmentAdded:n,onAttachmentRemoved:i}=e,{maxFileSizeBytes:o=qr,allowedMimeTypes:a=Br,allowedExtensions:c=Wr,validateContentType:s=!0}=r,l=c.join(",");function h(u){if(u.size>o){const p=new fe('File "'+u.name+'" is too large ('+at(u.size)+"). Maximum size is "+at(o)+".","FILE_TOO_LARGE",u);throw t?.(p),p}const g=Hr(u.name);if(g&&!c.some(p=>p.toLowerCase()===g)){const p=new fe('File type "'+g+'" is not allowed. Allowed types: '+c.join(", "),"INVALID_TYPE",u);throw t?.(p),p}if(u.type&&!a.some(p=>{if(p.endsWith("/*")){const f=p.slice(0,-1);return u.type.startsWith(f)}return u.type===p})){const p=new fe('File type "'+u.type+'" is not allowed.',"INVALID_TYPE",u);throw t?.(p),p}if(s&&u.type&&g&&!Vr(u.type,g)){const p=new fe('File extension "'+g+'" does not match content type "'+u.type+'".',"VALIDATION_FAILED",u);throw t?.(p),p}}return{accept:l,async add({file:u}){h(u);let g="file";u.type.startsWith("image/")?g="image":(u.type.includes("pdf")||u.type.includes("document")||u.type.includes("text")||u.name.endsWith(".pdf")||u.name.endsWith(".docx")||u.name.endsWith(".txt")||u.name.endsWith(".md")||u.name.endsWith(".csv")||u.name.endsWith(".json"))&&(g="document");const p={id:Kr(),type:g,name:u.name,contentType:u.type,file:u,status:{type:"requires-action",reason:"composer-send"}};return n?.(p),p},async remove(u){i?.(u.id)},async send(u){if(u.type==="image"&&u.file){const g=await new Promise((p,f)=>{const y=new FileReader;y.onload=()=>p(y.result),y.onerror=()=>f(new Error("Failed to read file")),y.readAsDataURL(u.file)});return{...u,status:{type:"complete"},content:[{type:"image",image:g}]}}return{...u,status:{type:"complete"},content:[]}}}}function Qr({children:e,baseUrl:r,sessionToken:t,isProxyMode:n=!1,mode:i="multiChat",modelId:o,onModelChange:a,ephemeral:c=!1,systemPrompt:s,enableReasoning:l=!1,initialThreadId:h,onError:u,onChatCreated:g,onUserMessage:p,onThreadIdUpdate:f,onChatsLoaded:y,enableAttachments:k=!1,onBeforeRequest:b,mockResponseOnBlocked:C}){const v=x.useMemo(()=>new wt(r,t||void 0,n),[r,t,n]),[P,S]=x.useState(o||null);x.useEffect(()=>{o&&S(o)},[o]);const N=x.useCallback(E=>{g?.(E)},[g]),O=x.useCallback((E,m)=>{f?.(E,m)},[f]),M=x.useMemo(()=>vt(v,{modelId:P||void 0,systemPrompt:s,ephemeral:c,enableReasoning:l,onChatCreated:N,onUserMessage:p,onBeforeRequest:b,mockResponseOnBlocked:C}),[v,P,s,c,l,N,p,b,C]);return i==="singleChat"?d.jsx(Gr,{modelAdapter:M,enableAttachments:k,children:e}):d.jsx(Yr,{client:v,modelAdapterOptions:{modelId:P||void 0,systemPrompt:s,ephemeral:c,enableReasoning:l,onChatCreated:N,onUserMessage:p,onBeforeRequest:b,mockResponseOnBlocked:C},initialThreadId:h,onChatsLoaded:y,onThreadIdUpdate:O,onError:u,enableAttachments:k,children:e})}function Gr({modelAdapter:e,enableAttachments:r,children:t}){const n=x.useMemo(()=>r?We():void 0,[r]),i=T.useLocalRuntime(e,{adapters:{...n&&{attachments:n}}});return d.jsx(T.AssistantRuntimeProvider,{runtime:i,children:t})}function Yr({client:e,modelAdapterOptions:r,initialThreadId:t,onChatsLoaded:n,onThreadIdUpdate:i,onError:o,enableAttachments:a,children:c}){const s=x.useMemo(()=>$r(e,(y,k)=>{i?.(y,k)}),[e,i]),l=x.useCallback((y,k)=>{s.updateRemoteId&&s.updateRemoteId(y,k),i?.(y,k)},[s,i]),h=x.useMemo(()=>({...s,async list(){const y=await s.list();return n?.(),y}}),[s,n]);x.useEffect(()=>{window.__cuadraThreadListAdapter=h,window.__cuadraThreadListRuntime=null},[h]);const u=x.useMemo(()=>vt(e,{...r,onThreadIdUpdate:l}),[e,r,l]),g=x.useMemo(()=>a?We():void 0,[a]),p=x.useCallback(()=>T.useLocalRuntime(u,{adapters:{...g&&{attachments:g}}}),[u,g]),f=T.unstable_useRemoteThreadListRuntime({adapter:h,runtimeHook:p});return x.useEffect(()=>{window.__cuadraThreadListRuntime=f},[f]),d.jsx(T.AssistantRuntimeProvider,{runtime:f,children:c})}function it(e,r){const t=String(e);if(typeof r!="string")throw new TypeError("Expected character");let n=0,i=t.indexOf(r);for(;i!==-1;)n++,i=t.indexOf(r,i+r.length);return n}const me=Ae(/[A-Za-z]/),qe=Ae(/[\dA-Za-z]/);function Xr(e){return e!==null&&(e<32||e===127)}function ce(e){return e!==null&&e<-2}function B(e){return e!==null&&(e<0||e===32)}function Z(e){return e===-2||e===-1||e===32}const je=Ae(/\p{P}|\p{S}/u),oe=Ae(/\s/);function Ae(e){return r;function r(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function Zr(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}const Ie=(function(e){if(e==null)return rn;if(typeof e=="function")return Me(e);if(typeof e=="object")return Array.isArray(e)?Jr(e):en(e);if(typeof e=="string")return tn(e);throw new Error("Expected function, string, or object as test")});function Jr(e){const r=[];let t=-1;for(;++t<e.length;)r[t]=Ie(e[t]);return Me(n);function n(...i){let o=-1;for(;++o<r.length;)if(r[o].apply(this,i))return!0;return!1}}function en(e){const r=e;return Me(t);function t(n){const i=n;let o;for(o in e)if(i[o]!==r[o])return!1;return!0}}function tn(e){return Me(r);function r(t){return t&&t.type===e}}function Me(e){return r;function r(t,n,i){return!!(nn(t)&&e.call(this,t,typeof n=="number"?n:void 0,i||void 0))}}function rn(){return!0}function nn(e){return e!==null&&typeof e=="object"&&"type"in e}const Tt=[],an=!0,$e=!1,on="skip";function jt(e,r,t,n){let i;typeof r=="function"&&typeof t!="function"?(n=t,t=r):i=r;const o=Ie(i),a=n?-1:1;c(e,void 0,[])();function c(s,l,h){const u=s&&typeof s=="object"?s:{};if(typeof u.type=="string"){const p=typeof u.tagName=="string"?u.tagName:typeof u.name=="string"?u.name:void 0;Object.defineProperty(g,"name",{value:"node ("+(s.type+(p?"<"+p+">":""))+")"})}return g;function g(){let p=Tt,f,y,k;if((!r||o(s,l,h[h.length-1]||void 0))&&(p=sn(t(s,h)),p[0]===$e))return p;if("children"in s&&s.children){const b=s;if(b.children&&p[0]!==on)for(y=(n?b.children.length:-1)+a,k=h.concat(b);y>-1&&y<b.children.length;){const C=b.children[y];if(f=c(C,y,k)(),f[0]===$e)return f;y=typeof f[1]=="number"?f[1]:y+a}}return p}}}function sn(e){return Array.isArray(e)?e:typeof e=="number"?[an,e]:e==null?Tt:[e]}function cn(e,r,t){const i=Ie((t||{}).ignore||[]),o=un(r);let a=-1;for(;++a<o.length;)jt(e,"text",c);function c(l,h){let u=-1,g;for(;++u<h.length;){const p=h[u],f=g?g.children:void 0;if(i(p,f?f.indexOf(p):void 0,g))return;g=p}if(g)return s(l,h)}function s(l,h){const u=h[h.length-1],g=o[a][0],p=o[a][1];let f=0;const k=u.children.indexOf(l);let b=!1,C=[];g.lastIndex=0;let v=g.exec(l.value);for(;v;){const P=v.index,S={index:v.index,input:v.input,stack:[...h,l]};let N=p(...v,S);if(typeof N=="string"&&(N=N.length>0?{type:"text",value:N}:void 0),N===!1?g.lastIndex=P+1:(f!==P&&C.push({type:"text",value:l.value.slice(f,P)}),Array.isArray(N)?C.push(...N):N&&C.push(N),f=P+v[0].length,b=!0),!g.global)break;v=g.exec(l.value)}return b?(f<l.value.length&&C.push({type:"text",value:l.value.slice(f)}),u.children.splice(k,1,...C)):C=[l],k+C.length}}function un(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 n=-1;for(;++n<t.length;){const i=t[n];r.push([ln(i[0]),dn(i[1])])}return r}function ln(e){return typeof e=="string"?new RegExp(Zr(e),"g"):e}function dn(e){return typeof e=="function"?e:function(){return e}}const Pe="phrasing",Ee=["autolink","link","image","label"];function fn(){return{transforms:[bn],enter:{literalAutolink:mn,literalAutolinkEmail:Le,literalAutolinkHttp:Le,literalAutolinkWww:Le},exit:{literalAutolink:yn,literalAutolinkEmail:xn,literalAutolinkHttp:pn,literalAutolinkWww:gn}}}function hn(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Pe,notInConstruct:Ee},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Pe,notInConstruct:Ee},{character:":",before:"[ps]",after:"\\/",inConstruct:Pe,notInConstruct:Ee}]}}function mn(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Le(e){this.config.enter.autolinkProtocol.call(this,e)}function pn(e){this.config.exit.autolinkProtocol.call(this,e)}function gn(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 xn(e){this.config.exit.autolinkEmail.call(this,e)}function yn(e){this.exit(e)}function bn(e){cn(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,kn],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,wn]],{ignore:["link","linkReference"]})}function kn(e,r,t,n,i){let o="";if(!At(i)||(/^w/i.test(r)&&(t=r+t,r="",o="http://"),!Cn(t)))return!1;const a=vn(t+n);if(!a[0])return!1;const c={type:"link",title:null,url:o+r+a[0],children:[{type:"text",value:r+a[0]}]};return a[1]?[c,{type:"text",value:a[1]}]:c}function wn(e,r,t,n){return!At(n,!0)||/[-\d_]$/.test(t)?!1:{type:"link",title:null,url:"mailto:"+r+"@"+t,children:[{type:"text",value:r+"@"+t}]}}function Cn(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 vn(e){const r=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!r)return[e,void 0];e=e.slice(0,r.index);let t=r[0],n=t.indexOf(")");const i=it(e,"(");let o=it(e,")");for(;n!==-1&&i>o;)e+=t.slice(0,n+1),t=t.slice(n+1),n=t.indexOf(")"),o++;return[e,t]}function At(e,r){const t=e.input.charCodeAt(e.index-1);return(e.index===0||oe(t)||je(t))&&(!r||t!==47)}function ge(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}It.peek=En;function Tn(){this.buffer()}function jn(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function An(){this.buffer()}function In(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function Mn(e){const r=this.resume(),t=this.stack[this.stack.length-1];t.type,t.identifier=ge(this.sliceSerialize(e)).toLowerCase(),t.label=r}function Sn(e){this.exit(e)}function Nn(e){const r=this.resume(),t=this.stack[this.stack.length-1];t.type,t.identifier=ge(this.sliceSerialize(e)).toLowerCase(),t.label=r}function Pn(e){this.exit(e)}function En(){return"["}function It(e,r,t,n){const i=t.createTracker(n);let o=i.move("[^");const a=t.enter("footnoteReference"),c=t.enter("reference");return o+=i.move(t.safe(t.associationId(e),{after:"]",before:o})),c(),a(),o+=i.move("]"),o}function Ln(){return{enter:{gfmFootnoteCallString:Tn,gfmFootnoteCall:jn,gfmFootnoteDefinitionLabelString:An,gfmFootnoteDefinition:In},exit:{gfmFootnoteCallString:Mn,gfmFootnoteCall:Sn,gfmFootnoteDefinitionLabelString:Nn,gfmFootnoteDefinition:Pn}}}function Rn(e){let r=!1;return e&&e.firstLineBlank&&(r=!0),{handlers:{footnoteDefinition:t,footnoteReference:It},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function t(n,i,o,a){const c=o.createTracker(a);let s=c.move("[^");const l=o.enter("footnoteDefinition"),h=o.enter("label");return s+=c.move(o.safe(o.associationId(n),{before:s,after:"]"})),h(),s+=c.move("]:"),n.children&&n.children.length>0&&(c.shift(4),s+=c.move((r?`
|
|
6
|
-
`:" ")+o.indentLines(o.containerFlow(n,c.current()),r?
|
|
7
|
-
`)}function
|
|
8
|
-
`&&
|
|
9
|
-
`}function
|
|
10
|
-
`,encode:["`"],...c.current()})),u()}return
|
|
11
|
-
`),o&&(
|
|
12
|
-
`)),
|
|
13
|
-
`,...s.current()}))),c(),e.title&&(c=t.enter(`title${o}`),l+=s.move(" "+i),l+=s.move(t.safe(e.title,{before:l,after:i,...s.current()})),l+=s.move(i),c()),a(),l}function
|
|
5
|
+
`);i=c.pop()||"";for(const s of c)if(s.startsWith("data: ")){const l=s.slice(6);if(l.trim()==="[DONE]"){yield{done:!0};continue}try{yield JSON.parse(l)}catch{}}}}finally{t.releaseLock()}}function Qr(e){return e.map(r=>{let t="";if(typeof r.content=="string")t=r.content;else if(Array.isArray(r.content)){const n=r.content.find(i=>i.type==="text");n&&typeof n=="object"&&"text"in n&&(t=n.text)}return{role:r.role,content:t}})}function Gr(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 Yr=function(){let e,r;const t=new Promise((n,i)=>{e=n,r=i});if(!e||!r)throw new Error("Failed to create promise");return{promise:t,resolve:e,reject:r}},Jr=()=>{const e=[];let r=!1,t,n;const i=a=>{a.promise||(a.promise=a.reader.read().then(({done:c,value:s})=>{a.promise=void 0,c?(e.splice(e.indexOf(a),1),r&&e.length===0&&t.close()):t.enqueue(s),n?.resolve(),n=void 0}).catch(c=>{console.error(c),e.forEach(s=>{s.reader.cancel()}),e.length=0,t.error(c),n?.reject(c),n=void 0}))};return{readable:new ReadableStream({start(a){t=a},pull(){return n=Yr(),e.forEach(a=>{i(a)}),n.promise},cancel(){e.forEach(a=>{a.reader.cancel()}),e.length=0}}),isSealed(){return r},seal(){r=!0,e.length===0&&t.close()},addStream(a){if(r)throw new Error("Cannot add streams after the run callback has settled.");const c={reader:a.getReader()};e.push(c),i(c)},enqueue(a){this.addStream(new ReadableStream({start(c){c.enqueue(a),c.close()}}))}}},it=class{constructor(e){$(this,"_controller");$(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())}},At=e=>new ReadableStream({start(r){return e.start?.(new it(r))},pull(r){return e.pull?.(new it(r))},cancel(r){return e.cancel?.(r)}}),ot=()=>{let e;return[At({start(t){e=t}}),e]},st=class{constructor(e){$(this,"_isClosed",!1);$(this,"_mergeTask");$(this,"_argsTextController");this._controller=e;const r=At({start:n=>{this._argsTextController=n}});let t=!1;this._mergeTask=r.pipeTo(new WritableStream({write:n=>{switch(n.type){case"text-delta":t=!0,this._controller.enqueue(n);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: ${n.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())}},Xr=e=>new ReadableStream({start(r){return e.start?.(new st(r))},pull(r){return e.pull?.(new st(r))},cancel(r){return e.cancel?.(r)}}),Zr=()=>{let e;return[Xr({start(t){e=t}}),e]},St=class{constructor(){$(this,"value",-1)}up(){return++this.value}},en=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:[n,...i]}=r;if(e!==n)throw new Error(`Path mismatch: expected ${e}, got ${n}`);t.enqueue({...r,path:i})}})}});var tn=class extends TransformStream{constructor(e){const r=new St,t=new Map;super({transform(n,i){n.type==="part-start"&&n.path.length===0&&t.set(r.up(),e.up());const[o,...a]=n.path;if(o===void 0){i.enqueue(n);return}const c=t.get(o);if(c===void 0)throw new Error("Path not found");i.enqueue({...n,path:[c,...a]})}})}};let rn=(e,r=21)=>(t=r)=>{let n="",i=t|0;for(;i--;)n+=e[Math.random()*e.length|0];return n};var nn=rn("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),an=class Mt{constructor(r){$(this,"_state");$(this,"_parentId");this._state=r||{merger:Jr(),contentCounter:new St}}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 en(this._state.contentCounter.value)))}merge(r){this._state.merger.addStream(r.pipeThrough(new tn(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]=ot();return this._addPart({type:"text"},r),t}addReasoningPart(){const[r,t]=ot();return this._addPart({type:"reasoning"},r),t}addToolCallPart(r){const t=typeof r=="string"?{toolName:r}:r,n=t.toolName,i=t.toolCallId??nn(),[o,a]=Zr();return this._addPart({type:"tool-call",toolName:n,toolCallId:i,...this._parentId&&{parentId:this._parentId}},o),t.argsText!==void 0&&(a.argsText.append(t.argsText),a.argsText.close()),t.args!==void 0&&(a.argsText.append(JSON.stringify(t.args)),a.argsText.close()),t.response!==void 0&&a.setResponse(t.response),a}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 Mt(this._state);return t._parentId=r,t}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}};function on(e){const r=new an;return(async()=>{try{await e(r)}catch(n){throw r.__internal_isClosed||r.enqueue({type:"error",path:[],error:String(n)}),n}finally{r.__internal_isClosed||r.close()}})(),r.__internal_getReadable()}const de=new Map,Te=new Map;let se;function Ee(e,r){const t=de.get(e);if(t)return t;if(r)for(const n of r){const i=Te.get(n.id);if(i)return de.set(e,i),i}return e}function sn(e,r){return{async list(){const t=[];let i,o=0;do{const c=await e.listChats({limit:50,cursor:i}),s=c.items||[];Array.isArray(s)&&s.length>0&&t.push(...s),i=c.nextCursor||void 0,o++}while(i&&o<50);return{threads:t.map(c=>{const s=c.id;return!s||c.deletedAt?null:{status:"regular",remoteId:s,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:de.get(t)||t,externalId:void 0}},async rename(t,n){const i=Ee(t);await e.updateChat(i,{title:n})},async archive(t){},async unarchive(t){},async delete(t){const n=Ee(t);await e.deleteChat(n)},async generateTitle(t,n){const i=Ee(t,n);let o;try{o=(await e.generateChatTitle(i)).title}catch(a){console.error("[generateTitle] API call failed, falling back to first message",a);const s=n.find(l=>l.role==="user")?.content?.filter(l=>l.type==="text").map(l=>l.text).join(" ").trim();o=s?s.length>60?s.slice(0,57)+"...":s:void 0}return on(a=>{const c=a.addTextPart();o&&c.append(o),c.close(),a.close()})},async fetch(t){try{const n=await e.getChat(t);return{status:"regular",remoteId:n.id||t,title:n.title||"Chat",createdAt:n.createdAt?new Date(n.createdAt):new Date,updatedAt:n.updatedAt?new Date(n.updatedAt):new Date}}catch{return{status:"regular",remoteId:t,createdAt:new Date,updatedAt:new Date}}},updateRemoteId(t,n){de.set(t,n),r?.(t,n)},unstable_Provider:({children:t})=>{const i=T.useThreadListItem()?.remoteId;y.useEffect(()=>{i&&(se=i)},[i]);const o=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 s=c.messages.map(f=>Gr(f)),l=s.map((f,u)=>({message:f,parentId:u>0?s[u-1].id:null}));for(const f of s)Te.set(f.id,i);return{messages:l}}catch{return{messages:[]}}},async append(c){}}),[i,e]),a=y.useMemo(()=>({history:o}),[o]);return d.jsx(T.RuntimeAdapterProvider,{adapters:a,children:t})}}}class cn{constructor(){$(this,"messageMetadata",new Map);$(this,"currentMessageId",null);$(this,"listeners",new Set)}setCurrentMessage(r){this.currentMessageId=r}update(r){if(!this.currentMessageId)return;const t=this.messageMetadata.get(this.currentMessageId)||{},n=r.sources;n&&n.length>0&&(this.messageMetadata.set(this.currentMessageId,{...t,sources:n}),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 X=new cn,ct=new Map,Oe=[];let ke=[];function Pt(e,r,t=50,n=800){Oe.push({question:e,response:r,streamingSpeed:t,initialDelay:n})}function _t(e,r){const{modelId:t,systemPrompt:n,ephemeral:i,enableReasoning:o,onChatCreated:a,onUserMessage:c,onThreadIdUpdate:s,onBeforeRequest:l,mockResponseOnBlocked:f}=r;let u;return{async*run(g){const{messages:m,abortSignal:h}=g,b=Oe.shift();if(b){c?.();const k=b.initialDelay??800;if(k>0&&await new Promise(I=>setTimeout(I,k)),h?.aborted)throw new Error("Request aborted");const j=b.response.split(" ");let R="";const L=b.streamingSpeed||50,V=`premade-${Date.now()}`;i&&a?.(V);for(let I=0;I<j.length;I++){if(h?.aborted)throw new Error("Request aborted");R+=(I===0?"":" ")+j[I],yield{content:[{type:"text",text:R}]},await new Promise(B=>setTimeout(B,L+Math.random()*(L*.5)))}yield{content:[{type:"text",text:R}]},ke.push({role:"user",content:b.question},{role:"assistant",content:b.response});return}let x;for(const k of m){const j=Te.get(k.id);if(j){x=j;break}}if(!x&&m.length>0){const k=m.find(j=>j.role==="user");if(k){const R=(typeof k.content=="string"?k.content:Array.isArray(k.content)&&k.content.find(L=>L.type==="text")?.text||"").substring(0,50);x=ct.get(R)}}!x&&u&&(x=u),c?.();let w=m,C=-1;for(let k=m.length-1;k>=0;k--)if(m[k].role==="assistant"){C=k;break}(x||C>=0)&&C>=0&&(w=m.slice(C+1));const v=Qr(w);if(ke.length>0&&!x){const k=ke.map(j=>({role:j.role,content:j.content}));v.unshift(...k),ke=[]}const _=[];let M;for(let k=w.length-1;k>=0;k--)if(w[k].role==="user"){M=w[k];break}if(M&&"attachments"in M){const k=M.attachments;if(k&&k.length>0){for(const j of k)if(j.file)try{const R=await e.uploadFile(j.file);_.push(R.id)}catch{}}}const P={messages:v,chatId:x||null,systemPrompt:n,ephemeral:i,enableReasoning:o,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,R=m.filter(B=>B.role==="user"),L=R.length>0?R[R.length-1]:void 0;let V="Message";L&&(typeof L.content=="string"?V=L.content:Array.isArray(L.content)&&(V=L.content.find(G=>G.type==="text")?.text||"Message")),Pt(V,j,40,400);const I=Oe.shift();if(I){c?.();const B=I.initialDelay??400;if(B>0&&await new Promise(H=>setTimeout(H,B)),h?.aborted)throw new Error("Request aborted");const G=I.response.split(" ");let re="";const ye=I.streamingSpeed||40,be=`mock-${Date.now()}`;i&&a?.(be);for(let H=0;H<G.length;H++){if(h?.aborted)throw new Error("Request aborted");re+=(H===0?"":" ")+G[H],yield{content:[{type:"text",text:re}]},await new Promise(Y=>setTimeout(Y,ye+Math.random()*(ye*.3)))}yield{content:[{type:"text",text:re}]};return}}throw new Error("Request blocked")}const O=await e.createOrContinueChat(P,h);let S="",N="",p;const F=[];let K=0,A=!1;const E=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;X.clear(),X.setCurrentMessage(E);const Q=()=>{F.length!==K&&(K=F.length,X.update({sources:F.length>0?[...F]:void 0}))},U=()=>{Q();const k=[];return N&&k.push({type:"reasoning",text:N}),S&&k.push({type:"text",text:S}),k.length===0&&k.push({type:"text",text:""}),{content:k}};for await(const k of Kr(O,h)){if(h?.aborted)throw new Error("Request aborted");const j=k.id||k.chatId||k.messageId;if(j&&!p){p=j,u=j,a?.(j);for(const I of m)Te.set(I.id,j);if(m.length>0){const I=m.find(B=>B.role==="user");if(I){const G=(typeof I.content=="string"?I.content:Array.isArray(I.content)&&I.content.find(re=>re.type==="text")?.text||"").substring(0,50);ct.set(G,j)}}se&&!de.has(se)&&de.set(se,j),s&&se&&s(se,j)}const R=k.sources;if(R&&Array.isArray(R)&&R.length>0)for(const I of R)F.some(B=>B.sourceId===I.sourceId)||F.push({sourceId:I.sourceId,filename:I.filename||"Unknown",score:I.score??1,chunkId:I.chunkId,datasetId:I.datasetId});const L=k.reasoning;if(L&&L.length>0&&(N+=L,yield U()),k.type)switch(k.type){case"source-document":k.sourceId&&F.push({sourceId:k.sourceId,filename:k.title||"Unknown",score:1});continue;case"reasoning-start":continue;case"reasoning-delta":k.delta&&(N+=k.delta),(S||N)&&(yield U());continue;case"reasoning-end":(S||N)&&(yield U());continue;case"text-delta":k.delta&&(N&&!A&&!S&&(A=!0,await new Promise(I=>setTimeout(I,400))),S+=k.delta),S&&(yield U());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 V=k.delta;if(V!=null&&(N&&!A&&!S&&(A=!0,await new Promise(I=>setTimeout(I,400))),S+=V),k.content&&(S+=k.content),k.message&&(S+=k.message.content||""),k.finished){(S||N||F.length>0)&&(yield U());break}(S||N||F.length>0)&&(yield U())}(S||N||F.length>0)&&(yield U())}}}class he extends Error{constructor(r,t,n){super(r),this.code=t,this.file=n,this.name="AttachmentValidationError"}}const ln=["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"],un=[".pdf",".doc",".docx",".xls",".xlsx",".txt",".md",".csv",".json",".jpg",".jpeg",".png",".gif",".webp",".svg"],dn=10*1024*1024;function lt(e){if(e===0)return"0 Bytes";const r=1024,t=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(r));return parseFloat((e/Math.pow(r,n)).toFixed(2))+" "+t[n]}function fn(e){return e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")).toLowerCase():""}function hn(e,r){const n={"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 n?n.includes(r.toLowerCase()):!0}function mn(){return typeof crypto<"u"&&crypto.randomUUID?"attachment-"+crypto.randomUUID():"attachment-"+Date.now()+"-"+Math.random().toString(36).slice(2,11)}function He(e={}){const{validation:r={},onValidationError:t,onAttachmentAdded:n,onAttachmentRemoved:i}=e,{maxFileSizeBytes:o=dn,allowedMimeTypes:a=ln,allowedExtensions:c=un,validateContentType:s=!0}=r,l=c.join(",");function f(u){if(u.size>o){const m=new he('File "'+u.name+'" is too large ('+lt(u.size)+"). Maximum size is "+lt(o)+".","FILE_TOO_LARGE",u);throw t?.(m),m}const g=fn(u.name);if(g&&!c.some(m=>m.toLowerCase()===g)){const m=new he('File type "'+g+'" is not allowed. Allowed types: '+c.join(", "),"INVALID_TYPE",u);throw t?.(m),m}if(u.type&&!a.some(m=>{if(m.endsWith("/*")){const h=m.slice(0,-1);return u.type.startsWith(h)}return u.type===m})){const m=new he('File type "'+u.type+'" is not allowed.',"INVALID_TYPE",u);throw t?.(m),m}if(s&&u.type&&g&&!hn(u.type,g)){const m=new he('File extension "'+g+'" does not match content type "'+u.type+'".',"VALIDATION_FAILED",u);throw t?.(m),m}}return{accept:l,async add({file:u}){f(u);let g="file";u.type.startsWith("image/")?g="image":(u.type.includes("pdf")||u.type.includes("document")||u.type.includes("text")||u.name.endsWith(".pdf")||u.name.endsWith(".docx")||u.name.endsWith(".txt")||u.name.endsWith(".md")||u.name.endsWith(".csv")||u.name.endsWith(".json"))&&(g="document");const m={id:mn(),type:g,name:u.name,contentType:u.type,file:u,status:{type:"requires-action",reason:"composer-send"}};return n?.(m),m},async remove(u){i?.(u.id)},async send(u){if(u.type==="image"&&u.file){const g=await new Promise((m,h)=>{const b=new FileReader;b.onload=()=>m(b.result),b.onerror=()=>h(new Error("Failed to read file")),b.readAsDataURL(u.file)});return{...u,status:{type:"complete"},content:[{type:"image",image:g}]}}return{...u,status:{type:"complete"},content:[]}}}}function pn({children:e,baseUrl:r,sessionToken:t,isProxyMode:n=!1,mode:i="multiChat",modelId:o,onModelChange:a,ephemeral:c=!1,systemPrompt:s,enableReasoning:l=!1,initialThreadId:f,onError:u,onChatCreated:g,onUserMessage:m,onThreadIdUpdate:h,onChatsLoaded:b,enableAttachments:x=!1,onBeforeRequest:w,mockResponseOnBlocked:C}){const v=y.useMemo(()=>new It(r,t||void 0,n),[r,t,n]),[_,M]=y.useState(o||null);y.useEffect(()=>{o&&M(o)},[o]);const P=y.useCallback(N=>{g?.(N)},[g]),O=y.useCallback((N,p)=>{h?.(N,p)},[h]),S=y.useMemo(()=>_t(v,{modelId:_||void 0,systemPrompt:s,ephemeral:c,enableReasoning:l,onChatCreated:P,onUserMessage:m,onBeforeRequest:w,mockResponseOnBlocked:C}),[v,_,s,c,l,P,m,w,C]);return i==="singleChat"?d.jsx(gn,{modelAdapter:S,enableAttachments:x,children:e}):d.jsx(xn,{client:v,modelAdapterOptions:{modelId:_||void 0,systemPrompt:s,ephemeral:c,enableReasoning:l,onChatCreated:P,onUserMessage:m,onBeforeRequest:w,mockResponseOnBlocked:C},initialThreadId:f,onChatsLoaded:b,onThreadIdUpdate:O,onError:u,enableAttachments:x,children:e})}function gn({modelAdapter:e,enableAttachments:r,children:t}){const n=y.useMemo(()=>r?He():void 0,[r]),i=T.useLocalRuntime(e,{adapters:{...n&&{attachments:n}}});return d.jsx(T.AssistantRuntimeProvider,{runtime:i,children:t})}function xn({client:e,modelAdapterOptions:r,initialThreadId:t,onChatsLoaded:n,onThreadIdUpdate:i,onError:o,enableAttachments:a,children:c}){const s=y.useMemo(()=>sn(e,(b,x)=>{i?.(b,x)}),[e,i]),l=y.useCallback((b,x)=>{s.updateRemoteId&&s.updateRemoteId(b,x),i?.(b,x)},[s,i]),f=y.useMemo(()=>({...s,async list(){const b=await s.list();return n?.(),b}}),[s,n]);y.useEffect(()=>{window.__cuadraThreadListAdapter=f,window.__cuadraThreadListRuntime=null},[f]);const u=y.useMemo(()=>_t(e,{...r,onThreadIdUpdate:l}),[e,r,l]),g=y.useMemo(()=>a?He():void 0,[a]),m=y.useCallback(()=>T.useLocalRuntime(u,{adapters:{...g&&{attachments:g}}}),[u,g]),h=T.unstable_useRemoteThreadListRuntime({adapter:f,runtimeHook:m});return y.useEffect(()=>{window.__cuadraThreadListRuntime=h},[h]),d.jsx(T.AssistantRuntimeProvider,{runtime:h,children:c})}function ut(e,r){const t=String(e);if(typeof r!="string")throw new TypeError("Expected character");let n=0,i=t.indexOf(r);for(;i!==-1;)n++,i=t.indexOf(r,i+r.length);return n}const pe=Se(/[A-Za-z]/),Ve=Se(/[\dA-Za-z]/);function yn(e){return e!==null&&(e<32||e===127)}function le(e){return e!==null&&e<-2}function q(e){return e!==null&&(e<0||e===32)}function Z(e){return e===-2||e===-1||e===32}const Ae=Se(/\p{P}|\p{S}/u),oe=Se(/\s/);function Se(e){return r;function r(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function bn(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}const Me=(function(e){if(e==null)return vn;if(typeof e=="function")return Pe(e);if(typeof e=="object")return Array.isArray(e)?wn(e):kn(e);if(typeof e=="string")return Cn(e);throw new Error("Expected function, string, or object as test")});function wn(e){const r=[];let t=-1;for(;++t<e.length;)r[t]=Me(e[t]);return Pe(n);function n(...i){let o=-1;for(;++o<r.length;)if(r[o].apply(this,i))return!0;return!1}}function kn(e){const r=e;return Pe(t);function t(n){const i=n;let o;for(o in e)if(i[o]!==r[o])return!1;return!0}}function Cn(e){return Pe(r);function r(t){return t&&t.type===e}}function Pe(e){return r;function r(t,n,i){return!!(Tn(t)&&e.call(this,t,typeof n=="number"?n:void 0,i||void 0))}}function vn(){return!0}function Tn(e){return e!==null&&typeof e=="object"&&"type"in e}const Nt=[],jn=!0,Be=!1,In="skip";function Et(e,r,t,n){let i;typeof r=="function"&&typeof t!="function"?(n=t,t=r):i=r;const o=Me(i),a=n?-1:1;c(e,void 0,[])();function c(s,l,f){const u=s&&typeof s=="object"?s:{};if(typeof u.type=="string"){const m=typeof u.tagName=="string"?u.tagName:typeof u.name=="string"?u.name:void 0;Object.defineProperty(g,"name",{value:"node ("+(s.type+(m?"<"+m+">":""))+")"})}return g;function g(){let m=Nt,h,b,x;if((!r||o(s,l,f[f.length-1]||void 0))&&(m=An(t(s,f)),m[0]===Be))return m;if("children"in s&&s.children){const w=s;if(w.children&&m[0]!==In)for(b=(n?w.children.length:-1)+a,x=f.concat(w);b>-1&&b<w.children.length;){const C=w.children[b];if(h=c(C,b,x)(),h[0]===Be)return h;b=typeof h[1]=="number"?h[1]:b+a}}return m}}}function An(e){return Array.isArray(e)?e:typeof e=="number"?[jn,e]:e==null?Nt:[e]}function Sn(e,r,t){const i=Me((t||{}).ignore||[]),o=Mn(r);let a=-1;for(;++a<o.length;)Et(e,"text",c);function c(l,f){let u=-1,g;for(;++u<f.length;){const m=f[u],h=g?g.children:void 0;if(i(m,h?h.indexOf(m):void 0,g))return;g=m}if(g)return s(l,f)}function s(l,f){const u=f[f.length-1],g=o[a][0],m=o[a][1];let h=0;const x=u.children.indexOf(l);let w=!1,C=[];g.lastIndex=0;let v=g.exec(l.value);for(;v;){const _=v.index,M={index:v.index,input:v.input,stack:[...f,l]};let P=m(...v,M);if(typeof P=="string"&&(P=P.length>0?{type:"text",value:P}:void 0),P===!1?g.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),!g.global)break;v=g.exec(l.value)}return w?(h<l.value.length&&C.push({type:"text",value:l.value.slice(h)}),u.children.splice(x,1,...C)):C=[l],x+C.length}}function Mn(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 n=-1;for(;++n<t.length;){const i=t[n];r.push([Pn(i[0]),_n(i[1])])}return r}function Pn(e){return typeof e=="string"?new RegExp(bn(e),"g"):e}function _n(e){return typeof e=="function"?e:function(){return e}}const Re="phrasing",Le=["autolink","link","image","label"];function Nn(){return{transforms:[zn],enter:{literalAutolink:Rn,literalAutolinkEmail:De,literalAutolinkHttp:De,literalAutolinkWww:De},exit:{literalAutolink:Un,literalAutolinkEmail:Fn,literalAutolinkHttp:Ln,literalAutolinkWww:Dn}}}function En(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Re,notInConstruct:Le},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Re,notInConstruct:Le},{character:":",before:"[ps]",after:"\\/",inConstruct:Re,notInConstruct:Le}]}}function Rn(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function De(e){this.config.enter.autolinkProtocol.call(this,e)}function Ln(e){this.config.exit.autolinkProtocol.call(this,e)}function Dn(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 Fn(e){this.config.exit.autolinkEmail.call(this,e)}function Un(e){this.exit(e)}function zn(e){Sn(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,$n],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,On]],{ignore:["link","linkReference"]})}function $n(e,r,t,n,i){let o="";if(!Rt(i)||(/^w/i.test(r)&&(t=r+t,r="",o="http://"),!Bn(t)))return!1;const a=qn(t+n);if(!a[0])return!1;const c={type:"link",title:null,url:o+r+a[0],children:[{type:"text",value:r+a[0]}]};return a[1]?[c,{type:"text",value:a[1]}]:c}function On(e,r,t,n){return!Rt(n,!0)||/[-\d_]$/.test(t)?!1:{type:"link",title:null,url:"mailto:"+r+"@"+t,children:[{type:"text",value:r+"@"+t}]}}function Bn(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 qn(e){const r=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!r)return[e,void 0];e=e.slice(0,r.index);let t=r[0],n=t.indexOf(")");const i=ut(e,"(");let o=ut(e,")");for(;n!==-1&&i>o;)e+=t.slice(0,n+1),t=t.slice(n+1),n=t.indexOf(")"),o++;return[e,t]}function Rt(e,r){const t=e.input.charCodeAt(e.index-1);return(e.index===0||oe(t)||Ae(t))&&(!r||t!==47)}function xe(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}Lt.peek=Xn;function Wn(){this.buffer()}function Hn(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function Vn(){this.buffer()}function Kn(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function Qn(e){const r=this.resume(),t=this.stack[this.stack.length-1];t.type,t.identifier=xe(this.sliceSerialize(e)).toLowerCase(),t.label=r}function Gn(e){this.exit(e)}function Yn(e){const r=this.resume(),t=this.stack[this.stack.length-1];t.type,t.identifier=xe(this.sliceSerialize(e)).toLowerCase(),t.label=r}function Jn(e){this.exit(e)}function Xn(){return"["}function Lt(e,r,t,n){const i=t.createTracker(n);let o=i.move("[^");const a=t.enter("footnoteReference"),c=t.enter("reference");return o+=i.move(t.safe(t.associationId(e),{after:"]",before:o})),c(),a(),o+=i.move("]"),o}function Zn(){return{enter:{gfmFootnoteCallString:Wn,gfmFootnoteCall:Hn,gfmFootnoteDefinitionLabelString:Vn,gfmFootnoteDefinition:Kn},exit:{gfmFootnoteCallString:Qn,gfmFootnoteCall:Gn,gfmFootnoteDefinitionLabelString:Yn,gfmFootnoteDefinition:Jn}}}function ea(e){let r=!1;return e&&e.firstLineBlank&&(r=!0),{handlers:{footnoteDefinition:t,footnoteReference:Lt},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function t(n,i,o,a){const c=o.createTracker(a);let s=c.move("[^");const l=o.enter("footnoteDefinition"),f=o.enter("label");return s+=c.move(o.safe(o.associationId(n),{before:s,after:"]"})),f(),s+=c.move("]:"),n.children&&n.children.length>0&&(c.shift(4),s+=c.move((r?`
|
|
6
|
+
`:" ")+o.indentLines(o.containerFlow(n,c.current()),r?Dt:ta))),l(),s}}function ta(e,r,t){return r===0?e:Dt(e,r,t)}function Dt(e,r,t){return(t?"":" ")+e}const ra=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Ft.peek=sa;function na(){return{canContainEols:["delete"],enter:{strikethrough:ia},exit:{strikethrough:oa}}}function aa(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:ra}],handlers:{delete:Ft}}}function ia(e){this.enter({type:"delete",children:[]},e)}function oa(e){this.exit(e)}function Ft(e,r,t,n){const i=t.createTracker(n),o=t.enter("strikethrough");let a=i.move("~~");return a+=t.containerPhrasing(e,{...i.current(),before:a,after:"~"}),a+=i.move("~~"),o(),a}function sa(){return"~"}function ca(e){return e.length}function la(e,r){const t=r||{},n=(t.align||[]).concat(),i=t.stringLength||ca,o=[],a=[],c=[],s=[];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=ua(e[f][w]);if(t.alignDelimiters!==!1){const v=i(C);x[w]=v,(s[w]===void 0||v>s[w])&&(s[w]=v)}b.push(C)}a[f]=b,c[f]=x}let u=-1;if(typeof n=="object"&&"length"in n)for(;++u<l;)o[u]=dt(n[u]);else{const b=dt(n);for(;++u<l;)o[u]=b}u=-1;const g=[],m=[];for(;++u<l;){const b=o[u];let x="",w="";b===99?(x=":",w=":"):b===108?x=":":b===114&&(w=":");let C=t.alignDelimiters===!1?1:Math.max(1,s[u]-x.length-w.length);const v=x+"-".repeat(C)+w;t.alignDelimiters!==!1&&(C=x.length+C+w.length,C>s[u]&&(s[u]=C),m[u]=C),g[u]=v}a.splice(1,0,g),c.splice(1,0,m),f=-1;const h=[];for(;++f<a.length;){const b=a[f],x=c[f];u=-1;const w=[];for(;++u<l;){const C=b[u]||"";let v="",_="";if(t.alignDelimiters!==!1){const M=s[u]-(x[u]||0),P=o[u];P===114?v=" ".repeat(M):P===99?M%2?(v=" ".repeat(M/2+.5),_=" ".repeat(M/2-.5)):(v=" ".repeat(M/2),_=v):_=" ".repeat(M)}t.delimiterStart!==!1&&!u&&w.push("|"),t.padding!==!1&&!(t.alignDelimiters===!1&&C==="")&&(t.delimiterStart!==!1||u)&&w.push(" "),t.alignDelimiters!==!1&&w.push(v),w.push(C),t.alignDelimiters!==!1&&w.push(_),t.padding!==!1&&w.push(" "),(t.delimiterEnd!==!1||u!==l-1)&&w.push("|")}h.push(t.delimiterEnd===!1?w.join("").replace(/ +$/,""):w.join(""))}return h.join(`
|
|
7
|
+
`)}function ua(e){return e==null?"":String(e)}function dt(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 da(e,r,t,n){const i=t.enter("blockquote"),o=t.createTracker(n);o.move("> "),o.shift(2);const a=t.indentLines(t.containerFlow(e,o.current()),fa);return i(),a}function fa(e,r,t){return">"+(t?"":" ")+e}function ha(e,r){return ft(e,r.inConstruct,!0)&&!ft(e,r.notInConstruct,!1)}function ft(e,r,t){if(typeof r=="string"&&(r=[r]),!r||r.length===0)return t;let n=-1;for(;++n<r.length;)if(e.includes(r[n]))return!0;return!1}function ht(e,r,t,n){let i=-1;for(;++i<t.unsafe.length;)if(t.unsafe[i].character===`
|
|
8
|
+
`&&ha(t.stack,t.unsafe[i]))return/[ \t]/.test(n.before)?"":" ";return`\\
|
|
9
|
+
`}function ma(e,r){const t=String(e);let n=t.indexOf(r),i=n,o=0,a=0;if(typeof r!="string")throw new TypeError("Expected substring");for(;n!==-1;)n===i?++o>a&&(a=o):o=1,i=n+r.length,n=t.indexOf(r,i);return a}function pa(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 ga(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 xa(e,r,t,n){const i=ga(t),o=e.value||"",a=i==="`"?"GraveAccent":"Tilde";if(pa(e,t)){const u=t.enter("codeIndented"),g=t.indentLines(o,ya);return u(),g}const c=t.createTracker(n),s=i.repeat(Math.max(ma(o,i)+1,3)),l=t.enter("codeFenced");let f=c.move(s);if(e.lang){const u=t.enter(`codeFencedLang${a}`);f+=c.move(t.safe(e.lang,{before:f,after:" ",encode:["`"],...c.current()})),u()}if(e.lang&&e.meta){const u=t.enter(`codeFencedMeta${a}`);f+=c.move(" "),f+=c.move(t.safe(e.meta,{before:f,after:`
|
|
10
|
+
`,encode:["`"],...c.current()})),u()}return f+=c.move(`
|
|
11
|
+
`),o&&(f+=c.move(o+`
|
|
12
|
+
`)),f+=c.move(s),l(),f}function ya(e,r,t){return(t?"":" ")+e}function Ke(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 ba(e,r,t,n){const i=Ke(t),o=i==='"'?"Quote":"Apostrophe",a=t.enter("definition");let c=t.enter("label");const s=t.createTracker(n);let l=s.move("[");return l+=s.move(t.safe(t.associationId(e),{before:l,after:"]",...s.current()})),l+=s.move("]: "),c(),!e.url||/[\0- \u007F]/.test(e.url)?(c=t.enter("destinationLiteral"),l+=s.move("<"),l+=s.move(t.safe(e.url,{before:l,after:">",...s.current()})),l+=s.move(">")):(c=t.enter("destinationRaw"),l+=s.move(t.safe(e.url,{before:l,after:e.title?" ":`
|
|
13
|
+
`,...s.current()}))),c(),e.title&&(c=t.enter(`title${o}`),l+=s.move(" "+i),l+=s.move(t.safe(e.title,{before:l,after:i,...s.current()})),l+=s.move(i),c()),a(),l}function wa(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 ge(e){return"&#x"+e.toString(16).toUpperCase()+";"}function je(e){if(e===null||q(e)||oe(e))return 1;if(Ae(e))return 2}function Ie(e,r,t){const n=je(e),i=je(r);return n===void 0?i===void 0?t==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:n===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}}Ut.peek=ka;function Ut(e,r,t,n){const i=wa(t),o=t.enter("emphasis"),a=t.createTracker(n),c=a.move(i);let s=a.move(t.containerPhrasing(e,{after:i,before:c,...a.current()}));const l=s.charCodeAt(0),f=Ie(n.before.charCodeAt(n.before.length-1),l,i);f.inside&&(s=ge(l)+s.slice(1));const u=s.charCodeAt(s.length-1),g=Ie(n.after.charCodeAt(0),u,i);g.inside&&(s=s.slice(0,-1)+ge(u));const m=a.move(i);return o(),t.attentionEncodeSurroundingInfo={after:g.outside,before:f.outside},c+s+m}function ka(e,r,t){return t.options.emphasis||"*"}function Ca(e,r,t,n){let i,o,a;typeof r=="function"&&typeof t!="function"?(o=void 0,a=r,i=t):(o=r,a=t,i=n),Et(e,o,c,i);function c(s,l){const f=l[l.length-1],u=f?f.children.indexOf(s):void 0;return a(s,u,f)}}const va={};function zt(e,r){const t=va,n=typeof t.includeImageAlt=="boolean"?t.includeImageAlt:!0,i=typeof t.includeHtml=="boolean"?t.includeHtml:!0;return $t(e,n,i)}function $t(e,r,t){if(Ta(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 mt(e.children,r,t)}return Array.isArray(e)?mt(e,r,t):""}function mt(e,r,t){const n=[];let i=-1;for(;++i<e.length;)n[i]=$t(e[i],r,t);return n.join("")}function Ta(e){return!!(e&&typeof e=="object")}function ja(e,r){let t=!1;return Ca(e,function(n){if("value"in n&&/\r?\n|\r/.test(n.value)||n.type==="break")return t=!0,Be}),!!((!e.depth||e.depth<3)&&zt(e)&&(r.options.setext||t))}function Ia(e,r,t,n){const i=Math.max(Math.min(6,e.depth||1),1),o=t.createTracker(n);if(ja(e,t)){const f=t.enter("headingSetext"),u=t.enter("phrasing"),g=t.containerPhrasing(e,{...o.current(),before:`
|
|
14
14
|
`,after:`
|
|
15
|
-
`});return u(),
|
|
15
|
+
`});return u(),f(),g+`
|
|
16
16
|
`+(i===1?"=":"-").repeat(g.length-(Math.max(g.lastIndexOf("\r"),g.lastIndexOf(`
|
|
17
17
|
`))+1))}const a="#".repeat(i),c=t.enter("headingAtx"),s=t.enter("phrasing");o.move(a+" ");let l=t.containerPhrasing(e,{before:"# ",after:`
|
|
18
|
-
`,...o.current()});return/^[\t ]/.test(l)&&(l=
|
|
19
|
-
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:g,table:a,tableCell:s,tableRow:c}};function a(
|
|
20
|
-
`))}function s(p,f,y,k){const b=y.enter("tableCell"),C=y.enter("phrasing"),v=y.containerPhrasing(p,{...k,before:o,after:o});return C(),b(),v}function l(p,f){return Wn(p,{align:f,alignDelimiters:n,padding:t,stringLength:i})}function h(p,f,y){const k=p.children;let b=-1;const C=[],v=f.enter("table");for(;++b<k.length;)C[b]=u(k[b],f,y);return v(),C}function u(p,f,y){const k=p.children;let b=-1;const C=[],v=f.enter("tableRow");for(;++b<k.length;)C[b]=s(k[b],p,f,y);return v(),C}function g(p,f,y){let k=Bt.inlineCode(p,f,y);return y.stack.includes("tableCell")&&(k=k.replace(/\|/g,"\\$&")),k}}function La(){return{exit:{taskListCheckValueChecked:dt,taskListCheckValueUnchecked:dt,paragraph:Da}}}function Ra(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:_a}}}function dt(e){const r=this.stack[this.stack.length-2];r.type,r.checked=e.type==="taskListCheckValueChecked"}function Da(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 n=t.children[0];if(n&&n.type==="text"){const i=r.children;let o=-1,a;for(;++o<i.length;){const c=i[o];if(c.type==="paragraph"){a=c;break}}a===t&&(n.value=n.value.slice(1),n.value.length===0?t.children.shift():t.position&&n.position&&typeof n.position.start.offset=="number"&&(n.position.start.column++,n.position.start.offset++,t.position.start=Object.assign({},n.position.start)))}}this.exit(e)}function _a(e,r,t,n){const i=e.children[0],o=typeof e.checked=="boolean"&&i&&i.type==="paragraph",a="["+(e.checked?"x":" ")+"] ",c=t.createTracker(n);o&&c.move(a);let s=Bt.listItem(e,r,t,{...n,...c.current()});return o&&(s=s.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,l)),s;function l(h){return h+a}}function Fa(){return[fn(),Ln(),Fn(),Aa(),La()]}function Ua(e){return{extensions:[hn(),Rn(e),Un(),Ea(e),Ra()]}}function Ce(e,r,t,n){const i=e.length;let o=0,a;if(r<0?r=-r>i?0:i+r:r=r>i?i:r,t=t>0?t:0,n.length<1e4)a=Array.from(n),a.unshift(r,t),e.splice(...a);else for(t&&e.splice(r,t);o<n.length;)a=n.slice(o,o+1e4),a.unshift(r,0),e.splice(...a),o+=1e4,r+=1e4}const ft={}.hasOwnProperty;function za(e){const r={};let t=-1;for(;++t<e.length;)$a(r,e[t]);return r}function $a(e,r){let t;for(t in r){const i=(ft.call(e,t)?e[t]:void 0)||(e[t]={}),o=r[t];let a;if(o)for(a in o){ft.call(i,a)||(i[a]=[]);const c=o[a];Oa(i[a],Array.isArray(c)?c:c?[c]:[])}}}function Oa(e,r){let t=-1;const n=[];for(;++t<r.length;)(r[t].add==="after"?e:n).push(r[t]);Ce(e,0,0,n)}const Ba={tokenize:Qa,partial:!0},Wt={tokenize:Ga,partial:!0},qt={tokenize:Ya,partial:!0},Ht={tokenize:Xa,partial:!0},Wa={tokenize:Za,partial:!0},Vt={name:"wwwAutolink",tokenize:Va,previous:Qt},Kt={name:"protocolAutolink",tokenize:Ka,previous:Gt},ee={name:"emailAutolink",tokenize:Ha,previous:Yt},Y={};function qa(){return{text:Y}}let ie=48;for(;ie<123;)Y[ie]=ee,ie++,ie===58?ie=65:ie===91&&(ie=97);Y[43]=ee;Y[45]=ee;Y[46]=ee;Y[95]=ee;Y[72]=[ee,Kt];Y[104]=[ee,Kt];Y[87]=[ee,Vt];Y[119]=[ee,Vt];function Ha(e,r,t){const n=this;let i,o;return a;function a(u){return!Oe(u)||!Yt.call(n,n.previous)||Ke(n.events)?t(u):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(u))}function c(u){return Oe(u)?(e.consume(u),c):u===64?(e.consume(u),s):t(u)}function s(u){return u===46?e.check(Wa,h,l)(u):u===45||u===95||qe(u)?(o=!0,e.consume(u),s):h(u)}function l(u){return e.consume(u),i=!0,s}function h(u){return o&&i&&me(n.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),r(u)):t(u)}}function Va(e,r,t){const n=this;return i;function i(a){return a!==87&&a!==119||!Qt.call(n,n.previous)||Ke(n.events)?t(a):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(Ba,e.attempt(Wt,e.attempt(qt,o),t),t)(a))}function o(a){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),r(a)}}function Ka(e,r,t){const n=this;let i="",o=!1;return a;function a(u){return(u===72||u===104)&&Gt.call(n,n.previous)&&!Ke(n.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),i+=String.fromCodePoint(u),e.consume(u),c):t(u)}function c(u){if(me(u)&&i.length<5)return i+=String.fromCodePoint(u),e.consume(u),c;if(u===58){const g=i.toLowerCase();if(g==="http"||g==="https")return e.consume(u),s}return t(u)}function s(u){return u===47?(e.consume(u),o?l:(o=!0,s)):t(u)}function l(u){return u===null||Xr(u)||B(u)||oe(u)||je(u)?t(u):e.attempt(Wt,e.attempt(qt,h),t)(u)}function h(u){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),r(u)}}function Qa(e,r,t){let n=0;return i;function i(a){return(a===87||a===119)&&n<3?(n++,e.consume(a),i):a===46&&n===3?(e.consume(a),o):t(a)}function o(a){return a===null?t(a):r(a)}}function Ga(e,r,t){let n,i,o;return a;function a(l){return l===46||l===95?e.check(Ht,s,c)(l):l===null||B(l)||oe(l)||l!==45&&je(l)?s(l):(o=!0,e.consume(l),a)}function c(l){return l===95?n=!0:(i=n,n=void 0),e.consume(l),a}function s(l){return i||n||!o?t(l):r(l)}}function Ya(e,r){let t=0,n=0;return i;function i(a){return a===40?(t++,e.consume(a),i):a===41&&n<t?o(a):a===33||a===34||a===38||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===60||a===63||a===93||a===95||a===126?e.check(Ht,r,o)(a):a===null||B(a)||oe(a)?r(a):(e.consume(a),i)}function o(a){return a===41&&n++,e.consume(a),i}}function Xa(e,r,t){return n;function n(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),n):c===38?(e.consume(c),o):c===93?(e.consume(c),i):c===60||c===null||B(c)||oe(c)?r(c):t(c)}function i(c){return c===null||c===40||c===91||B(c)||oe(c)?r(c):n(c)}function o(c){return me(c)?a(c):t(c)}function a(c){return c===59?(e.consume(c),n):me(c)?(e.consume(c),a):t(c)}}function Za(e,r,t){return n;function n(o){return e.consume(o),i}function i(o){return qe(o)?t(o):r(o)}}function Qt(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||B(e)}function Gt(e){return!me(e)}function Yt(e){return!(e===47||Oe(e))}function Oe(e){return e===43||e===45||e===46||e===95||qe(e)}function Ke(e){let r=e.length,t=!1;for(;r--;){const n=e[r][1];if((n.type==="labelLink"||n.type==="labelImage")&&!n._balanced){t=!0;break}if(n._gfmAutolinkLiteralWalkedInto){t=!1;break}}return e.length>0&&!t&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),t}function Ja(e,r,t){const n=[];let i=-1;for(;++i<e.length;){const o=e[i].resolveAll;o&&!n.includes(o)&&(r=o(r,t),n.push(o))}return r}function J(e,r,t,n){const i=n?n-1:Number.POSITIVE_INFINITY;let o=0;return a;function a(s){return Z(s)?(e.enter(t),c(s)):r(s)}function c(s){return Z(s)&&o++<i?(e.consume(s),c):(e.exit(t),r(s))}}const ei={partial:!0,tokenize:ti};function ti(e,r,t){return n;function n(o){return Z(o)?J(e,i,"linePrefix")(o):i(o)}function i(o){return o===null||ce(o)?r(o):t(o)}}const ri={tokenize:li,partial:!0};function ni(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:si,continuation:{tokenize:ci},exit:ui}},text:{91:{name:"gfmFootnoteCall",tokenize:oi},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:ai,resolveTo:ii}}}}function ai(e,r,t){const n=this;let i=n.events.length;const o=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let a;for(;i--;){const s=n.events[i][1];if(s.type==="labelImage"){a=s;break}if(s.type==="gfmFootnoteCall"||s.type==="labelLink"||s.type==="label"||s.type==="image"||s.type==="link")break}return c;function c(s){if(!a||!a._balanced)return t(s);const l=ge(n.sliceSerialize({start:a.end,end:n.now()}));return l.codePointAt(0)!==94||!o.includes(l.slice(1))?t(s):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(s),e.exit("gfmFootnoteCallLabelMarker"),r(s))}}function ii(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 n={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 o={type:"gfmFootnoteCallString",start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},a={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},c=[e[t+1],e[t+2],["enter",n,r],e[t+3],e[t+4],["enter",i,r],["exit",i,r],["enter",o,r],["enter",a,r],["exit",a,r],["exit",o,r],e[e.length-2],e[e.length-1],["exit",n,r]];return e.splice(t,e.length-t+1,...c),e}function oi(e,r,t){const n=this,i=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let o=0,a;return c;function c(u){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(u),e.exit("gfmFootnoteCallLabelMarker"),s}function s(u){return u!==94?t(u):(e.enter("gfmFootnoteCallMarker"),e.consume(u),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",l)}function l(u){if(o>999||u===93&&!a||u===null||u===91||B(u))return t(u);if(u===93){e.exit("chunkString");const g=e.exit("gfmFootnoteCallString");return i.includes(ge(n.sliceSerialize(g)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(u),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),r):t(u)}return B(u)||(a=!0),o++,e.consume(u),u===92?h:l}function h(u){return u===91||u===92||u===93?(e.consume(u),o++,l):l(u)}}function si(e,r,t){const n=this,i=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let o,a=0,c;return s;function s(f){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),l}function l(f){return f===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",h):t(f)}function h(f){if(a>999||f===93&&!c||f===null||f===91||B(f))return t(f);if(f===93){e.exit("chunkString");const y=e.exit("gfmFootnoteDefinitionLabelString");return o=ge(n.sliceSerialize(y)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),g}return B(f)||(c=!0),a++,e.consume(f),f===92?u:h}function u(f){return f===91||f===92||f===93?(e.consume(f),a++,h):h(f)}function g(f){return f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),i.includes(o)||i.push(o),J(e,p,"gfmFootnoteDefinitionWhitespace")):t(f)}function p(f){return r(f)}}function ci(e,r,t){return e.check(ei,r,e.attempt(ri,r,t))}function ui(e){e.exit("gfmFootnoteDefinition")}function li(e,r,t){const n=this;return J(e,i,"gfmFootnoteDefinitionIndent",5);function i(o){const a=n.events[n.events.length-1];return a&&a[1].type==="gfmFootnoteDefinitionIndent"&&a[2].sliceSerialize(a[1],!0).length===4?r(o):t(o)}}function di(e){let t=(e||{}).singleTilde;const n={name:"strikethrough",tokenize:o,resolveAll:i};return t==null&&(t=!0),{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function i(a,c){let s=-1;for(;++s<a.length;)if(a[s][0]==="enter"&&a[s][1].type==="strikethroughSequenceTemporary"&&a[s][1]._close){let l=s;for(;l--;)if(a[l][0]==="exit"&&a[l][1].type==="strikethroughSequenceTemporary"&&a[l][1]._open&&a[s][1].end.offset-a[s][1].start.offset===a[l][1].end.offset-a[l][1].start.offset){a[s][1].type="strikethroughSequence",a[l][1].type="strikethroughSequence";const h={type:"strikethrough",start:Object.assign({},a[l][1].start),end:Object.assign({},a[s][1].end)},u={type:"strikethroughText",start:Object.assign({},a[l][1].end),end:Object.assign({},a[s][1].start)},g=[["enter",h,c],["enter",a[l][1],c],["exit",a[l][1],c],["enter",u,c]],p=c.parser.constructs.insideSpan.null;p&&Ce(g,g.length,0,Ja(p,a.slice(l+1,s),c)),Ce(g,g.length,0,[["exit",u,c],["enter",a[s][1],c],["exit",a[s][1],c],["exit",h,c]]),Ce(a,l-1,s-l+3,g),s=l+g.length-2;break}}for(s=-1;++s<a.length;)a[s][1].type==="strikethroughSequenceTemporary"&&(a[s][1].type="data");return a}function o(a,c,s){const l=this.previous,h=this.events;let u=0;return g;function g(f){return l===126&&h[h.length-1][1].type!=="characterEscape"?s(f):(a.enter("strikethroughSequenceTemporary"),p(f))}function p(f){const y=ve(l);if(f===126)return u>1?s(f):(a.consume(f),u++,p);if(u<2&&!t)return s(f);const k=a.exit("strikethroughSequenceTemporary"),b=ve(f);return k._open=!b||b===2&&!!y,k._close=!y||y===2&&!!b,c(f)}}}class fi{constructor(){this.map=[]}add(r,t,n){hi(this,r,t,n)}consume(r){if(this.map.sort(function(o,a){return o[0]-a[0]}),this.map.length===0)return;let t=this.map.length;const n=[];for(;t>0;)t-=1,n.push(r.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),r.length=this.map[t][0];n.push(r.slice()),r.length=0;let i=n.pop();for(;i;){for(const o of i)r.push(o);i=n.pop()}this.map.length=0}}function hi(e,r,t,n){let i=0;if(!(t===0&&n.length===0)){for(;i<e.map.length;){if(e.map[i][0]===r){e.map[i][1]+=t,e.map[i][2].push(...n);return}i+=1}e.map.push([r,t,n])}}function mi(e,r){let t=!1;const n=[];for(;r<e.length;){const i=e[r];if(t){if(i[0]==="enter")i[1].type==="tableContent"&&n.push(e[r+1][1].type==="tableDelimiterMarker"?"left":"none");else if(i[1].type==="tableContent"){if(e[r-1][1].type==="tableDelimiterMarker"){const o=n.length-1;n[o]=n[o]==="left"?"center":"right"}}else if(i[1].type==="tableDelimiterRow")break}else i[0]==="enter"&&i[1].type==="tableDelimiterRow"&&(t=!0);r+=1}return n}function pi(){return{flow:{null:{name:"table",tokenize:gi,resolveAll:xi}}}}function gi(e,r,t){const n=this;let i=0,o=0,a;return c;function c(m){let F=n.events.length-1;for(;F>-1;){const L=n.events[F][1].type;if(L==="lineEnding"||L==="linePrefix")F--;else break}const V=F>-1?n.events[F][1].type:null,I=V==="tableHead"||V==="tableRow"?N:s;return I===N&&n.parser.lazy[n.now().line]?t(m):I(m)}function s(m){return e.enter("tableHead"),e.enter("tableRow"),l(m)}function l(m){return m===124||(a=!0,o+=1),h(m)}function h(m){return m===null?t(m):ce(m)?o>1?(o=0,n.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),p):t(m):Z(m)?J(e,h,"whitespace")(m):(o+=1,a&&(a=!1,i+=1),m===124?(e.enter("tableCellDivider"),e.consume(m),e.exit("tableCellDivider"),a=!0,h):(e.enter("data"),u(m)))}function u(m){return m===null||m===124||B(m)?(e.exit("data"),h(m)):(e.consume(m),m===92?g:u)}function g(m){return m===92||m===124?(e.consume(m),u):u(m)}function p(m){return n.interrupt=!1,n.parser.lazy[n.now().line]?t(m):(e.enter("tableDelimiterRow"),a=!1,Z(m)?J(e,f,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(m):f(m))}function f(m){return m===45||m===58?k(m):m===124?(a=!0,e.enter("tableCellDivider"),e.consume(m),e.exit("tableCellDivider"),y):S(m)}function y(m){return Z(m)?J(e,k,"whitespace")(m):k(m)}function k(m){return m===58?(o+=1,a=!0,e.enter("tableDelimiterMarker"),e.consume(m),e.exit("tableDelimiterMarker"),b):m===45?(o+=1,b(m)):m===null||ce(m)?P(m):S(m)}function b(m){return m===45?(e.enter("tableDelimiterFiller"),C(m)):S(m)}function C(m){return m===45?(e.consume(m),C):m===58?(a=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(m),e.exit("tableDelimiterMarker"),v):(e.exit("tableDelimiterFiller"),v(m))}function v(m){return Z(m)?J(e,P,"whitespace")(m):P(m)}function P(m){return m===124?f(m):m===null||ce(m)?!a||i!==o?S(m):(e.exit("tableDelimiterRow"),e.exit("tableHead"),r(m)):S(m)}function S(m){return t(m)}function N(m){return e.enter("tableRow"),O(m)}function O(m){return m===124?(e.enter("tableCellDivider"),e.consume(m),e.exit("tableCellDivider"),O):m===null||ce(m)?(e.exit("tableRow"),r(m)):Z(m)?J(e,O,"whitespace")(m):(e.enter("data"),M(m))}function M(m){return m===null||m===124||B(m)?(e.exit("data"),O(m)):(e.consume(m),m===92?E:M)}function E(m){return m===92||m===124?(e.consume(m),M):M(m)}}function xi(e,r){let t=-1,n=!0,i=0,o=[0,0,0,0],a=[0,0,0,0],c=!1,s=0,l,h,u;const g=new fi;for(;++t<e.length;){const p=e[t],f=p[1];p[0]==="enter"?f.type==="tableHead"?(c=!1,s!==0&&(ht(g,r,s,l,h),h=void 0,s=0),l={type:"table",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(t,0,[["enter",l,r]])):f.type==="tableRow"||f.type==="tableDelimiterRow"?(n=!0,u=void 0,o=[0,0,0,0],a=[0,t+1,0,0],c&&(c=!1,h={type:"tableBody",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(t,0,[["enter",h,r]])),i=f.type==="tableDelimiterRow"?2:h?3:1):i&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")?(n=!1,a[2]===0&&(o[1]!==0&&(a[0]=a[1],u=we(g,r,o,i,void 0,u),o=[0,0,0,0]),a[2]=t)):f.type==="tableCellDivider"&&(n?n=!1:(o[1]!==0&&(a[0]=a[1],u=we(g,r,o,i,void 0,u)),o=a,a=[o[1],t,0,0])):f.type==="tableHead"?(c=!0,s=t):f.type==="tableRow"||f.type==="tableDelimiterRow"?(s=t,o[1]!==0?(a[0]=a[1],u=we(g,r,o,i,t,u)):a[1]!==0&&(u=we(g,r,a,i,t,u)),i=0):i&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")&&(a[3]=t)}for(s!==0&&ht(g,r,s,l,h),g.consume(r.events),t=-1;++t<r.events.length;){const p=r.events[t];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=mi(r.events,t))}return e}function we(e,r,t,n,i,o){const a=n===1?"tableHeader":n===2?"tableDelimiter":"tableData",c="tableContent";t[0]!==0&&(o.end=Object.assign({},se(r.events,t[0])),e.add(t[0],0,[["exit",o,r]]));const s=se(r.events,t[1]);if(o={type:a,start:Object.assign({},s),end:Object.assign({},s)},e.add(t[1],0,[["enter",o,r]]),t[2]!==0){const l=se(r.events,t[2]),h=se(r.events,t[3]),u={type:c,start:Object.assign({},l),end:Object.assign({},h)};if(e.add(t[2],0,[["enter",u,r]]),n!==2){const g=r.events[t[2]],p=r.events[t[3]];if(g[1].end=Object.assign({},p[1].end),g[1].type="chunkText",g[1].contentType="text",t[3]>t[2]+1){const f=t[2]+1,y=t[3]-t[2]-1;e.add(f,y,[])}}e.add(t[3]+1,0,[["exit",u,r]])}return i!==void 0&&(o.end=Object.assign({},se(r.events,i)),e.add(i,0,[["exit",o,r]]),o=void 0),o}function ht(e,r,t,n,i){const o=[],a=se(r.events,t);i&&(i.end=Object.assign({},a),o.push(["exit",i,r])),n.end=Object.assign({},a),o.push(["exit",n,r]),e.add(t+1,0,o)}function se(e,r){const t=e[r],n=t[0]==="enter"?"start":"end";return t[1][n]}const yi={name:"tasklistCheck",tokenize:ki};function bi(){return{text:{91:yi}}}function ki(e,r,t){const n=this;return i;function i(s){return n.previous!==null||!n._gfmTasklistFirstContentOfListItem?t(s):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(s),e.exit("taskListCheckMarker"),o)}function o(s){return B(s)?(e.enter("taskListCheckValueUnchecked"),e.consume(s),e.exit("taskListCheckValueUnchecked"),a):s===88||s===120?(e.enter("taskListCheckValueChecked"),e.consume(s),e.exit("taskListCheckValueChecked"),a):t(s)}function a(s){return s===93?(e.enter("taskListCheckMarker"),e.consume(s),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):t(s)}function c(s){return ce(s)?r(s):Z(s)?e.check({tokenize:wi},r,t)(s):t(s)}}function wi(e,r,t){return J(e,n,"whitespace");function n(i){return i===null?t(i):r(i)}}function Ci(e){return za([qa(),ni(),di(e),pi(),bi()])}const vi={};function Ti(e){const r=this,t=e||vi,n=r.data(),i=n.micromarkExtensions||(n.micromarkExtensions=[]),o=n.fromMarkdownExtensions||(n.fromMarkdownExtensions=[]),a=n.toMarkdownExtensions||(n.toMarkdownExtensions=[]);i.push(Ci(t)),o.push(Fa()),a.push(Ua(t))}function z(...e){return e.filter(Boolean).join(" ")}const ji=({content:e})=>d.jsx(Fe.MarkdownTextPrimitive,{remarkPlugins:[Ti],className:"cuadra-aui-md",components:Mi,children:e}),Qe=x.memo(ji),Ai=({language:e,code:r})=>{const{isCopied:t,copyToClipboard:n}=Ii(),i=()=>{!r||t||n(r)};return d.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:[d.jsx("span",{className:"cuadra-lowercase [&>span]:cuadra-text-xs cuadra-font-brand",children:e}),d.jsxs("button",{onClick:i,className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-muted cuadra-transition-colors","aria-label":"Copy code",children:[!t&&d.jsx(gr,{className:"cuadra-h-4 cuadra-w-4"}),t&&d.jsx(pt,{className:"cuadra-h-4 cuadra-w-4"})]})]})},Ii=({copiedDuration:e=3e3}={})=>{const[r,t]=x.useState(!1);return{isCopied:r,copyToClipboard:i=>{i&&navigator.clipboard.writeText(i).then(()=>{t(!0),setTimeout(()=>t(!1),e)})}}},Mi=Fe.unstable_memoizeMarkdownComponents({h1:({className:e,...r})=>d.jsx("h1",{className:z("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})=>d.jsx("h2",{className:z("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})=>d.jsx("h3",{className:z("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})=>d.jsx("h4",{className:z("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})=>d.jsx("h5",{className:z("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})=>d.jsx("h6",{className:z("cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand",e),...r}),p:({className:e,...r})=>d.jsx("p",{className:z("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})=>d.jsx("a",{className:z("cuadra-text-primary cuadra-font-medium cuadra-underline cuadra-underline-offset-4 font-brand",e),...r}),blockquote:({className:e,...r})=>d.jsx("blockquote",{className:z("cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand",e),...r}),ul:({className:e,...r})=>d.jsx("ul",{className:z("cuadra-my-5 cuadra-ml-6 cuadra-list-disc [&>li]:cuadra-mt-2 font-brand",e),...r}),ol:({className:e,...r})=>d.jsx("ol",{className:z("cuadra-my-5 cuadra-ml-6 cuadra-list-decimal [&>li]:cuadra-mt-2 font-brand",e),...r}),hr:({className:e,...r})=>d.jsx("hr",{className:z("cuadra-my-5 cuadra-border-b",e),...r}),table:({className:e,...r})=>d.jsx("table",{className:z("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})=>d.jsx("th",{className:z("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})=>d.jsx("td",{className:z("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})=>d.jsx("tr",{className:z("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})=>d.jsx("sup",{className:z("[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand",e),...r}),pre:({className:e,...r})=>d.jsx("pre",{className:z("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 n=Fe.useIsMarkdownCodeBlock();return d.jsx("code",{className:z(!n&&"cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand",r),...t})},CodeHeader:Ai});function Ge({className:e="",variant:r="default",...t}){const n="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 d.jsx("div",{className:`${n} ${i[r]||i.default} ${e}`,...t})}function Si(e){const r=new Map;for(const t of e){const n=r.get(t.filename);(!n||t.score>n.score)&&r.set(t.filename,t)}return Array.from(r.values()).sort((t,n)=>n.score-t.score)}function Xt({sources:e,maxVisible:r=3}){if(!e||e.length===0)return null;const t=Si(e),n=t.slice(0,r),i=t.length-r;return d.jsxs("div",{className:"cuadra-mt-4 cuadra-pt-3 cuadra-border-t cuadra-border-border",children:[d.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1.5 cuadra-mb-2.5",children:[d.jsx(gt,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground"}),d.jsx("span",{className:"cuadra-text-xs cuadra-font-medium cuadra-text-muted-foreground font-brand",children:"Sources"})]}),d.jsxs("div",{className:"cuadra-flex cuadra-flex-wrap cuadra-gap-2",children:[n.map((o,a)=>d.jsx(Pi,{source:o},o.sourceId||a)),i>0&&d.jsxs(Ge,{variant:"subtle",children:["+",i," more"]})]})]})}function Ni(e){switch(e.split(".").pop()?.toLowerCase()){case"csv":case"xlsx":case"xls":return yr;case"md":case"txt":return wr;default:return gt}}function Pi({source:e}){const{filename:r,score:t}=e,n=Ni(r);return d.jsxs(Ge,{className:"cuadra-gap-2 cuadra-cursor-default",title:t<1?`${Math.round(t*100)}% relevant`:void 0,children:[d.jsx(n,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-shrink-0 cuadra-opacity-60"}),d.jsx("span",{className:"cuadra-truncate cuadra-max-w-[180px]",children:r}),t<1&&t>0&&d.jsxs("span",{className:"cuadra-opacity-50 cuadra-text-[10px] cuadra-tabular-nums",children:[Math.round(t*100),"%"]})]})}const Ei=x.forwardRef(function({welcomeTitle:r="What shall we explore today?",extraTopPadding:t,suggestions:n,inputPlaceholder:i="Reply...",enableAttachments:o=!1,preMadeResponseDelay:a=1e3,streamingSpeed:c=50,safeArea:s=!1,composerBorder:l=!1,models:h,selectedModelId:u,onModelChange:g,showChatHeader:p=!1},f){const y=T.useThreadRuntime(),k=T.useAssistantApi(),[b,C]=x.useState(!1),[v,P]=x.useState(null),[S,N]=x.useState(!1),O=T.useThread(I=>{const L=I.messages;return!L||L.length===0}),M=O&&!b,E=x.useCallback((I,L,K)=>{if(!S)try{const U=K?.streamingSpeed??c,w=K?.delay??a;Ct(I,L,U,w),k.composer().setText(I),setTimeout(()=>{k.composer().send()},10)}catch{}},[S,c,a,k]),m=x.useCallback(I=>{try{k.composer().setText(I),setTimeout(()=>{k.composer().send()},10)}catch{}},[k]),F=x.useCallback(async I=>{if(!(S||!y))try{if(I.response){const L=I.responseDelay??a;await E(I.prompt,I.response,{delay:L,streamingSpeed:c})}else m(I.prompt)}catch{}},[y,S,a,c,E,m]),V=x.useCallback(async()=>{try{const L=window.__cuadraThreadListRuntime?.threadList;L?.switchToNewThread&&await L.switchToNewThread()}catch{}},[]);return x.useImperativeHandle(f,()=>({sendMessage:m,sendPreMadeQA:E,clearChat:V}),[m,E,V]),x.useEffect(()=>{if(!y){C(!1);return}try{const I=y?.store;if(!I){C(!1);return}const L=I.subscribe?.(U=>{const w=U?.threadId,A=U?.messages||[],R=U?.isLoadingHistory||!1,D=A.length;w&&w!==v&&P(w),C(R&&D===0)}),K=I.getState?.();if(K){const U=K?.threadId,w=K?.messages||[],A=K?.isLoadingHistory||!1,R=w.length;U&&U!==v&&P(U),C(A&&R===0)}return()=>{L&&L()}}catch{C(!1)}},[y,v]),d.jsxs(T.ThreadPrimitive.Root,{className:"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full cuadra-relative",children:[p&&d.jsx(zi,{}),d.jsxs("div",{className:`cuadra-flex-1 cuadra-flex cuadra-flex-col cuadra-min-h-0 ${M?"cuadra-justify-center":""}`,children:[d.jsx(T.ThreadPrimitive.Viewport,{className:`cuadra-w-full cuadra-bg-inherit cuadra-relative scrollbar-thin ${M?"cuadra-flex-none":"cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto"}`,style:{paddingTop:M?"0":t||(p?"0.5rem":"2rem")},children:b?d.jsx("div",{className:"cuadra-absolute cuadra-inset-0 cuadra-flex cuadra-items-center cuadra-justify-center",children:d.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-3",children:[d.jsx(xt,{className:"cuadra-h-5 cuadra-w-5 cuadra-animate-spin cuadra-text-muted-foreground"}),d.jsx("p",{className:"cuadra-text-sm cuadra-text-muted-foreground font-brand",children:"Loading messages..."})]})}):d.jsxs("div",{className:"cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full cuadra-px-4",children:[d.jsx(T.ThreadPrimitive.Empty,{children:d.jsx(Li,{title:r})}),d.jsx(T.ThreadPrimitive.Messages,{components:{UserMessage:Ri,AssistantMessage:Fi}})]})}),d.jsx("div",{className:`cuadra-w-full cuadra-px-4 cuadra-pt-2 ${M?"cuadra-pb-2":"cuadra-pb-4"}`,style:s?{paddingBottom:"calc(env(safe-area-inset-bottom) + 1rem)"}:void 0,children:d.jsxs("div",{className:"cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full",children:[o&&d.jsx(T.ComposerPrimitive.Attachments,{components:{Attachment:()=>{const I=T.useAssistantState(({attachment:L})=>L);return I?d.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:[d.jsx(yt,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground",strokeWidth:1.5}),d.jsx("span",{className:"cuadra-text-xs cuadra-text-foreground font-brand",children:I.name||"Attachment"}),d.jsx(T.AttachmentPrimitive.Remove,{asChild:!0,children:d.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:d.jsx(Nr,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})})]}):null}}}),d.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:[d.jsx(T.ComposerPrimitive.Input,{asChild:!0,children:d.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"}})}),d.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-px-3 cuadra-pb-2.5 cuadra-pt-1",children:[d.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1",children:o&&d.jsx(T.ComposerPrimitive.AddAttachment,{multiple:!0,asChild:!0,children:d.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:[d.jsx(bt,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground",strokeWidth:1.5}),d.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"})]})})}),d.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[h&&h.length>0&&d.jsx(Ui,{models:h,selectedModelId:u,onModelChange:g,threadIsEmpty:O,onNewChat:V}),d.jsx(T.ComposerPrimitive.Send,{asChild:!0,children:d.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:d.jsx(fr,{className:"cuadra-h-4 cuadra-w-4",strokeWidth:2})})})]})]})]})]})}),M&&n&&n.length>0&&d.jsx("div",{className:"cuadra-flex cuadra-flex-wrap cuadra-justify-center cuadra-gap-2 cuadra-px-4 cuadra-pb-6 cuadra-pt-1 cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full",children:n.map((I,L)=>d.jsx("button",{type:"button",onClick:()=>F(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-${L}`))})]})]})});function Li({title:e}){return d.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-text-center cuadra-py-6",children:d.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 Ri(){return d.jsx(T.MessagePrimitive.Root,{className:"cuadra-flex cuadra-w-full cuadra-justify-end cuadra-py-2.5",children:d.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-end cuadra-gap-2 cuadra-max-w-[80%]",children:[d.jsx(T.MessagePrimitive.Attachments,{components:{Attachment:()=>{const e=T.useAssistantState(({attachment:o})=>o);if(!e)return null;const r=e.type==="image",t=e.file,n=e.content?.find(o=>o.type==="image"),i=t?URL.createObjectURL(t):n?.image;return d.jsx("div",{className:"cuadra-mb-1",children:r&&i?d.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)"}}):d.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:[d.jsx(yt,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground"}),d.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground font-brand",children:e.name||"Attachment"})]})})}}}),d.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:d.jsx(T.MessagePrimitive.Parts,{components:{Text:({text:e})=>d.jsx(Qe,{content:e||""})}})})]})})}function Di({text:e}){const[r,t]=x.useState(!1),n=T.useAssistantState(({message:i})=>i?.status?.type==="running");return e?n?d.jsx("div",{className:"cuadra-mb-3 cuadra-py-1",children:d.jsx("div",{className:"cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand cuadra-animate-text-shimmer",children:e})}):d.jsxs("div",{className:"cuadra-mb-3",children:[d.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:[d.jsx(Be,{className:`cuadra-h-3.5 cuadra-w-3.5 cuadra-shrink-0 cuadra-transition-transform cuadra-duration-200 ${r?"":"cuadra--rotate-90"}`}),d.jsx("span",{children:"Reasoning"})]}),d.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:d.jsx("div",{className:"cuadra-pl-5 cuadra-pt-2 cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand",children:d.jsx(Qe,{content:e})})})]}):null}function _i(){return d.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:[d.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1",children:[d.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}}),d.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}}),d.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}})]}),d.jsx("span",{children:"Thinking..."})]})}function Fi(){const e=T.useAssistantState(({message:a})=>a?.status?.type==="running"),r=T.useAssistantState(({message:a})=>{const c=a?.content;return!c||!Array.isArray(c)?!1:c.some(s=>!!(s.type==="text"&&s.text&&s.text.length>0||s.type==="reasoning"&&s.text&&s.text.length>0))}),t=x.useRef(!1),[n,i]=x.useState(null);x.useEffect(()=>{if(e&&r&&!t.current){const a=X.getCurrentMessageId();a&&(t.current=!0,i(a))}},[e,r]);const o=x.useSyncExternalStore(a=>X.subscribe(a),()=>{if(n){const a=X.getForMessage(n);return a.sources?.length?a.sources:null}if(e&&r){const a=X.getCurrentMessageId();if(a){const c=X.getForMessage(a);return c.sources?.length?c.sources:null}}return null},()=>null);return d.jsx(T.MessagePrimitive.Root,{className:"cuadra-flex cuadra-w-full cuadra-justify-start cuadra-py-2.5",children:d.jsxs("div",{className:"cuadra-text-foreground cuadra-max-w-full cuadra-break-words font-brand",style:{fontSize:"0.9375rem",lineHeight:"1.75"},children:[d.jsx(T.MessagePrimitive.Parts,{components:{Text:({text:a})=>d.jsx(Qe,{content:a||""}),Reasoning:({text:a})=>d.jsx(Di,{text:a||""})}}),e&&!r&&d.jsx(_i,{}),o&&o.length>0&&d.jsx(Xt,{sources:o})]})})}function Ui({models:e,selectedModelId:r,onModelChange:t,threadIsEmpty:n,onNewChat:i}){const[o,a]=x.useState(!1),c=e.find(l=>l.id===r)||e[0];if(!c)return null;const s=async l=>{a(!1),!n&&l!==r&&await i?.(),t?.(l)};return d.jsxs("div",{className:"cuadra-relative",children:[d.jsxs("button",{type:"button",onClick:()=>a(!o),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:[d.jsx("span",{children:c.name}),d.jsx(Be,{className:"cuadra-h-3 cuadra-w-3"})]}),o&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:()=>a(!1)}),d.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-overflow-hidden 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=>d.jsxs("button",{type:"button",className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-justify-between cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted/60 cuadra-transition-colors font-brand",onClick:()=>s(l.id),children:[d.jsxs("div",{className:"cuadra-flex cuadra-flex-col",children:[d.jsx("span",{className:"cuadra-text-foreground",children:l.name}),l.description&&d.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground",children:l.description})]}),l.id===r&&d.jsx(pt,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-primary cuadra-flex-shrink-0"})]},l.id))})]})]})}function zi(){const e=T.useAssistantState(({threadListItem:i})=>i?.title??null),[r,t]=x.useState(!1),n=e||"Untitled chat";return d.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-px-3 cuadra-py-2 cuadra-min-h-[48px]",children:d.jsxs("div",{className:"cuadra-relative",children:[d.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:[d.jsx("span",{className:"cuadra-font-medium cuadra-truncate cuadra-max-w-[200px]",children:n}),d.jsx(Be,{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&&d.jsx($i,{onClose:()=>t(!1)})]})})}function $i({onClose:e}){return d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:e}),d.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:d.jsxs(T.ThreadListPrimitive.Root,{className:"cuadra-flex cuadra-flex-col",children:[d.jsx("div",{className:"cuadra-px-2 cuadra-py-1.5",children:d.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:[d.jsx(bt,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"New Chat"]})}),d.jsx(Oi,{onSelect:e})]})})]})}function Oi({onSelect:e}){const r=T.useAssistantState(({threads:i})=>i?.threadIds??[]),t=T.useAssistantState(({threads:i})=>i?.newThreadId);return r.some(i=>i!==t)?d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"cuadra-mx-3 cuadra-my-0.5",style:{borderTop:"1px solid rgba(0,0,0,0.06)"}}),d.jsx("div",{className:"cuadra-overflow-y-auto cuadra-px-2 cuadra-pb-1.5 scrollbar-thin",style:{maxHeight:"340px"},children:d.jsx(T.ThreadListPrimitive.Items,{components:{ThreadListItem:i=>d.jsx(Bi,{...i,onSelect:e})}})})]}):null}function Bi({onSelect:e}){const r=T.useThreadListItem(),t=T.useThread(f=>f.threadId),n=r?.id===t,[i,o]=x.useState(!1),[a,c]=x.useState(!1),[s,l]=x.useState(r?.title||""),[h,u]=x.useState(!1),g=async()=>{if(!r?.remoteId||!s||s===r.title){c(!1);return}try{u(!0);const f=window.__cuadraThreadListAdapter;f?.rename&&await f.rename(r.remoteId,s)}catch{}finally{u(!1),c(!1)}},p=async f=>{f.stopPropagation();const y=r?.id;if(y)try{const b=window.__cuadraThreadListRuntime?.threadList,C=b?.getItemById?.(y);b?.switchToNewThread&&await b.switchToNewThread(),C?.delete&&await C.delete()}catch{}};return x.useEffect(()=>{r?.title&&!a&&l(r.title)},[r?.title,a]),r?d.jsxs(T.ThreadListItemPrimitive.Root,{className:`cuadra-relative cuadra-flex cuadra-items-center cuadra-rounded-lg cuadra-transition-colors cuadra-cursor-pointer ${n?"cuadra-bg-muted":"hover:cuadra-bg-muted/60"}`,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),children:[a?d.jsx("div",{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0",onClick:f=>f.stopPropagation(),onMouseDown:f=>f.stopPropagation(),onKeyDown:f=>f.stopPropagation(),onKeyUp:f=>f.stopPropagation(),onKeyPress:f=>f.stopPropagation(),children:d.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:s,onChange:f=>l(f.target.value),onKeyDown:f=>{f.stopPropagation(),f.key==="Enter"&&g(),f.key==="Escape"&&(c(!1),l(r.title||""))},onBlur:()=>void g(),disabled:h,autoFocus:!0})}):d.jsx(T.ThreadListItemPrimitive.Trigger,{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0 cuadra-cursor-pointer",onClick:()=>e?.(),children:d.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground cuadra-truncate cuadra-block cuadra-text-left font-brand",children:r.title||"Chat"})}),(i||n)&&!a&&d.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-0.5 cuadra-mr-1.5 cuadra-flex-shrink-0",children:[d.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-background/60 cuadra-transition-colors",onClick:f=>{f.stopPropagation(),c(!0),l(r.title||"Chat")},title:"Rename",children:d.jsx(jr,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})}),d.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-destructive/10 cuadra-transition-colors",onClick:p,title:"Delete",children:d.jsx(Mr,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-destructive"})})]})]}):null}const De=({children:e,className:r="",paddingX:t="px-0",paddingY:n="py-0",borderSizePx:i=2,style:o,contentStyle:a})=>d.jsx("div",{className:`cuadra-relative cuadra-bg-background md:cuadra-rounded-lg cuadra-overflow-hidden cuadra-flex cuadra-flex-col ${t} ${n} ${r}`,style:{border:i>0?`${i}px solid var(--cuadra-primary)`:"none",...o,...a},children:e}),Wi=x.createContext(void 0),_e=({children:e,value:r})=>d.jsx(Wi.Provider,{value:r,children:e});function qi(){x.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 n=document.createElement("link");n.setAttribute("data-cuadra-uikit","true"),n.rel="stylesheet",n.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:ue&&ue.tagName.toUpperCase()==="SCRIPT"&&ue.src||new URL("index.cjs",document.baseURI).href).href];let o=!1;for(const a of i)if(n.href=a,n.onload=()=>{o=!0},n.onerror=()=>{},document.head.appendChild(n),o)break},[])}const Hi=x.forwardRef(function({config:r},t){qi();const n=x.useRef(null),i=x.useRef(!1),{baseUrl:o,proxyUrl:a,sessionToken:c,mode:s="multiChat",modelMode:l="fixed",modelId:h,onModelChange:u,ephemeral:g=!1,systemPrompt:p,enableReasoning:f=!1,initialThreadId:y,welcomeTitle:k,welcomeSubtitle:b,extraTopPadding:C,suggestions:v,inputPlaceholder:P,preMadeResponseDelay:S=1e3,streamingSpeed:N=50,initialMessage:O,initialPreMadeQA:M,theme:E="system",onError:m,onChatCreated:F,onUserMessage:V,onThreadIdUpdate:I,enableAttachments:L=!1,onBeforeRequest:K,mockResponseOnBlocked:U}=r;x.useImperativeHandle(t,()=>({sendMessage:_=>{n.current?.sendMessage(_)},sendPreMadeQA:(_,ae,re)=>{n.current?.sendPreMadeQA(_,ae,re)},clearChat:()=>{n.current?.clearChat()}}),[]),x.useEffect(()=>{if(i.current)return;const _=setTimeout(()=>{M?(i.current=!0,n.current?.sendPreMadeQA(M.question,M.answer,{delay:S,streamingSpeed:N})):O&&(i.current=!0,n.current?.sendMessage(O))},500);return()=>clearTimeout(_)},[O,M,S,N]);const w=a||o||"",A=!!a,R=x.useMemo(()=>new wt(w,c||void 0,A),[w,c,A]),[D,H]=x.useState(null),[j,$]=x.useState(!1),[Q,te]=x.useState(null),[xe,ye]=x.useState(!1);x.useEffect(()=>{s==="multiChat"&&ye(!0)},[s]);const W=x.useCallback(async()=>{if(l==="selector"){$(!0),te(null);try{const _=await R.listModels();H(_)}catch(_){te(_ instanceof Error?_:new Error("Failed to load models"))}finally{$(!1)}}},[R,l]);x.useEffect(()=>{l==="selector"&&W()},[l,W]),x.useEffect(()=>(typeof window<"u"&&(window.__cuadraUIKitRefetchModels=W),()=>{typeof window<"u"&&delete window.__cuadraUIKitRefetchModels}),[W]);const[G,Xe]=x.useState(l==="fixed"&&h||null),Ze=x.useRef(G),be=x.useCallback(_=>{const ae=Ze.current;Xe(_),Ze.current=_,u?.(_),ae!==null&&ae!==_&&s==="multiChat"&&setTimeout(()=>{const re=window.__cuadraThreadListRuntime;if(re?.threads?.switchToNewThread)try{re.threads.switchToNewThread()}catch{}else if(re?.threads?.createThread)try{re.threads.createThread()}catch{}else if(re?.switchToNewThread)try{re.switchToNewThread()}catch{}},100)},[u,s]);x.useEffect(()=>{if(l==="selector"&&D?.items&&D.items.length>0&&!G){const _=D.items[0];if(_?.id){const ae=_.id;Xe(ae),u?.(ae)}}},[l,D?.items,G,u]);const rr=l==="fixed"?!!h:!!G,Se=x.useMemo(()=>(D?.items||[]).filter(_=>_?.id&&_?.displayName).map(_=>({id:_.id,name:_.displayName})),[D]),Ne=x.useMemo(()=>({currentModelId:G||"",models:Se,modelsLoading:j,modelsError:Q,onModelChange:be,refetchModels:W}),[G,Se,j,Q,be,W]);return l==="selector"&&j||s==="multiChat"&&xe?d.jsx(_e,{value:Ne,children:d.jsx(De,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",borderSizePx:r.borderless?0:2,children:d.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:d.jsx(xt,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"})})})}):l==="selector"&&!rr&&Q?d.jsx(_e,{value:Ne,children:d.jsx(De,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",children:d.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:d.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2",children:d.jsx("p",{className:"cuadra-text-sm cuadra-text-destructive font-brand",children:"Failed to load models"})})})})}):d.jsx("div",{className:"cuadra-uikit cuadra-h-full cuadra-w-full",style:{height:"100%",width:"100%"},children:d.jsx(_e,{value:Ne,children:d.jsx(Qr,{baseUrl:A?w:o||w,sessionToken:c,isProxyMode:A,mode:s,modelMode:l,modelId:G||h||void 0,onModelChange:be,ephemeral:g,systemPrompt:p,enableReasoning:f,initialThreadId:y,enableAttachments:L,onError:m,onChatCreated:F,onUserMessage:V,onThreadIdUpdate:I,onBeforeRequest:K,mockResponseOnBlocked:U,onChatsLoaded:()=>{s==="multiChat"&&ye(!1)},children:d.jsx(De,{paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",className:`cuadra-h-full ${r.containerClass||""}`,borderSizePx:r.borderless?0:2,style:{height:"100%"},children:d.jsx("div",{className:"cuadra-h-full cuadra-flex cuadra-relative",style:{height:"100%"},children:d.jsx("div",{className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:d.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0",children:d.jsx(Ei,{ref:n,welcomeTitle:k,welcomeSubtitle:b,extraTopPadding:C,suggestions:v,inputPlaceholder:P,enableAttachments:L,preMadeResponseDelay:S,streamingSpeed:N,safeArea:r.safeArea,showChatHeader:s==="multiChat",models:l==="selector"?Se:void 0,selectedModelId:G||void 0,onModelChange:l==="selector"?be:void 0,theme:E})})})})})})})})});function Zt(e,r=":root"){if(typeof document>"u")return;const t=document.documentElement;if(e.light&&Ki(e.light,t),e.dark){let n=document.getElementById("cuadra-theme-dark");n||(n=document.createElement("style"),n.id="cuadra-theme-dark",document.head.appendChild(n));const i=Qi(e.dark);n.textContent=`.dark { ${i} }`}}const Vi={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 Jt(e){const r=Vi[e];return r?`--cuadra-${r}`:`--cuadra-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function Ki(e,r){Object.entries(e).forEach(([t,n])=>{if(n){const i=Jt(t);r.style.setProperty(i,n)}})}function Qi(e){return Object.entries(e).map(([r,t])=>t?`${Jt(r)}: ${t};`:"").filter(Boolean).join(" ")}function Gi(){if(typeof document>"u")return;const e=document.documentElement;Array.from(e.style).filter(n=>n.startsWith("--cuadra-")).forEach(n=>e.style.removeProperty(n));const t=document.getElementById("cuadra-theme-dark");t&&t.remove()}function Yi({onReset:e,error:r}){return d.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-h-full cuadra-p-6 cuadra-text-center",children:[d.jsx("div",{className:"cuadra-mb-4",children:d.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:d.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"})})}),d.jsx("h3",{className:"cuadra-text-lg cuadra-font-medium cuadra-text-foreground cuadra-mb-2",children:"Something went wrong"}),d.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."}),d.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 Ye extends x.Component{constructor(t){super(t);ne(this,"reset",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){this.props.onError?.(t,n)}render(){if(this.state.hasError){const{fallback:t}=this.props,{error:n}=this.state;return typeof t=="function"?t(n,this.reset):t||d.jsx(Yi,{error:n,onReset:this.reset})}return this.props.children}}function Xi(e,r){const t=n=>d.jsx(Ye,{...r,children:d.jsx(e,{...n})});return t.displayName=`withErrorBoundary(${e.displayName||e.name||"Component"})`,t}const le=x.createContext(null);le.displayName="CuadraChatContext";function Zi(){const e=x.useContext(le);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 Ji(){const e=x.useContext(le);return e===null?null:{controls:e.controls,isReady:e.controls!==null}}function eo({children:e}){const[r,t]=x.useState(null),n=x.useCallback(a=>{t(a)},[]),i=x.useCallback(()=>{t(null)},[]),o=x.useMemo(()=>({controls:r,registerControls:n,unregisterControls:i}),[r,n,i]);return d.jsx(le.Provider,{value:o,children:e})}function er(e){return"connection"in e&&typeof e.connection=="object"}function tr(e){return er(e)?to(e):ro(e)}function to(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,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 ro(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
|
-
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,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
|
|
18
|
+
`,...o.current()});return/^[\t ]/.test(l)&&(l=ge(l.charCodeAt(0))+l.slice(1)),l=l?a+" "+l:a,t.options.closeAtx&&(l+=" "+a),s(),c(),l}Ot.peek=Aa;function Ot(e){return e.value||""}function Aa(){return"<"}Bt.peek=Sa;function Bt(e,r,t,n){const i=Ke(t),o=i==='"'?"Quote":"Apostrophe",a=t.enter("image");let c=t.enter("label");const s=t.createTracker(n);let l=s.move("![");return l+=s.move(t.safe(e.alt,{before:l,after:"]",...s.current()})),l+=s.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=t.enter("destinationLiteral"),l+=s.move("<"),l+=s.move(t.safe(e.url,{before:l,after:">",...s.current()})),l+=s.move(">")):(c=t.enter("destinationRaw"),l+=s.move(t.safe(e.url,{before:l,after:e.title?" ":")",...s.current()}))),c(),e.title&&(c=t.enter(`title${o}`),l+=s.move(" "+i),l+=s.move(t.safe(e.title,{before:l,after:i,...s.current()})),l+=s.move(i),c()),l+=s.move(")"),a(),l}function Sa(){return"!"}qt.peek=Ma;function qt(e,r,t,n){const i=e.referenceType,o=t.enter("imageReference");let a=t.enter("label");const c=t.createTracker(n);let s=c.move("![");const l=t.safe(e.alt,{before:s,after:"]",...c.current()});s+=c.move(l+"]["),a();const f=t.stack;t.stack=[],a=t.enter("reference");const u=t.safe(t.associationId(e),{before:s,after:"]",...c.current()});return a(),t.stack=f,o(),i==="full"||!l||l!==u?s+=c.move(u+"]"):i==="shortcut"?s=s.slice(0,-1):s+=c.move("]"),s}function Ma(){return"!"}Wt.peek=Pa;function Wt(e,r,t){let n=e.value||"",i="`",o=-1;for(;new RegExp("(^|[^`])"+i+"([^`]|$)").test(n);)i+="`";for(/[^ \r\n]/.test(n)&&(/^[ \r\n]/.test(n)&&/[ \r\n]$/.test(n)||/^`|`$/.test(n))&&(n=" "+n+" ");++o<t.unsafe.length;){const a=t.unsafe[o],c=t.compilePattern(a);let s;if(a.atBreak)for(;s=c.exec(n);){let l=s.index;n.charCodeAt(l)===10&&n.charCodeAt(l-1)===13&&l--,n=n.slice(0,l)+" "+n.slice(s.index+1)}}return i+n+i}function Pa(){return"`"}function Ht(e,r){const t=zt(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))}Vt.peek=_a;function Vt(e,r,t,n){const i=Ke(t),o=i==='"'?"Quote":"Apostrophe",a=t.createTracker(n);let c,s;if(Ht(e,t)){const f=t.stack;t.stack=[],c=t.enter("autolink");let u=a.move("<");return u+=a.move(t.containerPhrasing(e,{before:u,after:">",...a.current()})),u+=a.move(">"),c(),t.stack=f,u}c=t.enter("link"),s=t.enter("label");let l=a.move("[");return l+=a.move(t.containerPhrasing(e,{before:l,after:"](",...a.current()})),l+=a.move("]("),s(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(s=t.enter("destinationLiteral"),l+=a.move("<"),l+=a.move(t.safe(e.url,{before:l,after:">",...a.current()})),l+=a.move(">")):(s=t.enter("destinationRaw"),l+=a.move(t.safe(e.url,{before:l,after:e.title?" ":")",...a.current()}))),s(),e.title&&(s=t.enter(`title${o}`),l+=a.move(" "+i),l+=a.move(t.safe(e.title,{before:l,after:i,...a.current()})),l+=a.move(i),s()),l+=a.move(")"),c(),l}function _a(e,r,t){return Ht(e,t)?"<":"["}Kt.peek=Na;function Kt(e,r,t,n){const i=e.referenceType,o=t.enter("linkReference");let a=t.enter("label");const c=t.createTracker(n);let s=c.move("[");const l=t.containerPhrasing(e,{before:s,after:"]",...c.current()});s+=c.move(l+"]["),a();const f=t.stack;t.stack=[],a=t.enter("reference");const u=t.safe(t.associationId(e),{before:s,after:"]",...c.current()});return a(),t.stack=f,o(),i==="full"||!l||l!==u?s+=c.move(u+"]"):i==="shortcut"?s=s.slice(0,-1):s+=c.move("]"),s}function Na(){return"["}function Qe(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 Ea(e){const r=Qe(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 Ra(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 Qt(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 La(e,r,t,n){const i=t.enter("list"),o=t.bulletCurrent;let a=e.ordered?Ra(t):Qe(t);const c=e.ordered?a==="."?")":".":Ea(t);let s=r&&t.bulletLastUsed?a===t.bulletLastUsed:!1;if(!e.ordered){const f=e.children?e.children[0]:void 0;if((a==="*"||a==="-")&&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&&(s=!0),Qt(t)===a&&f){let u=-1;for(;++u<e.children.length;){const g=e.children[u];if(g&&g.type==="listItem"&&g.children&&g.children[0]&&g.children[0].type==="thematicBreak"){s=!0;break}}}}s&&(a=c),t.bulletCurrent=a;const l=t.containerFlow(e,n);return t.bulletLastUsed=a,t.bulletCurrent=o,i(),l}function Da(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 Fa(e,r,t,n){const i=Da(t);let o=t.bulletCurrent||Qe(t);r&&r.type==="list"&&r.ordered&&(o=(typeof r.start=="number"&&r.start>-1?r.start:1)+(t.options.incrementListMarker===!1?0:r.children.indexOf(e))+o);let a=o.length+1;(i==="tab"||i==="mixed"&&(r&&r.type==="list"&&r.spread||e.spread))&&(a=Math.ceil(a/4)*4);const c=t.createTracker(n);c.move(o+" ".repeat(a-o.length)),c.shift(a);const s=t.enter("listItem"),l=t.indentLines(t.containerFlow(e,c.current()),f);return s(),l;function f(u,g,m){return g?(m?"":" ".repeat(a))+u:(m?o:o+" ".repeat(a-o.length))+u}}function Ua(e,r,t,n){const i=t.enter("paragraph"),o=t.enter("phrasing"),a=t.containerPhrasing(e,n);return o(),i(),a}const za=Me(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function $a(e,r,t,n){return(e.children.some(function(a){return za(a)})?t.containerPhrasing:t.containerFlow).call(t,e,n)}function Oa(e){const r=e.options.strong||"*";if(r!=="*"&&r!=="_")throw new Error("Cannot serialize strong with `"+r+"` for `options.strong`, expected `*`, or `_`");return r}Gt.peek=Ba;function Gt(e,r,t,n){const i=Oa(t),o=t.enter("strong"),a=t.createTracker(n),c=a.move(i+i);let s=a.move(t.containerPhrasing(e,{after:i,before:c,...a.current()}));const l=s.charCodeAt(0),f=Ie(n.before.charCodeAt(n.before.length-1),l,i);f.inside&&(s=ge(l)+s.slice(1));const u=s.charCodeAt(s.length-1),g=Ie(n.after.charCodeAt(0),u,i);g.inside&&(s=s.slice(0,-1)+ge(u));const m=a.move(i+i);return o(),t.attentionEncodeSurroundingInfo={after:g.outside,before:f.outside},c+s+m}function Ba(e,r,t){return t.options.strong||"*"}function qa(e,r,t,n){return t.safe(e.value,n)}function Wa(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 Ha(e,r,t){const n=(Qt(t)+(t.options.ruleSpaces?" ":"")).repeat(Wa(t));return t.options.ruleSpaces?n.slice(0,-1):n}const Yt={blockquote:da,break:ht,code:xa,definition:ba,emphasis:Ut,hardBreak:ht,heading:Ia,html:Ot,image:Bt,imageReference:qt,inlineCode:Wt,link:Vt,linkReference:Kt,list:La,listItem:Fa,paragraph:Ua,root:$a,strong:Gt,text:qa,thematicBreak:Ha};function Va(){return{enter:{table:Ka,tableData:pt,tableHeader:pt,tableRow:Ga},exit:{codeText:Ya,table:Qa,tableData:Fe,tableHeader:Fe,tableRow:Fe}}}function Ka(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 Qa(e){this.exit(e),this.data.inTable=void 0}function Ga(e){this.enter({type:"tableRow",children:[]},e)}function Fe(e){this.exit(e)}function pt(e){this.enter({type:"tableCell",children:[]},e)}function Ya(e){let r=this.resume();this.data.inTable&&(r=r.replace(/\\([\\|])/g,Ja));const t=this.stack[this.stack.length-1];t.type,t.value=r,this.exit(e)}function Ja(e,r){return r==="|"?r:e}function Xa(e){const r=e||{},t=r.tableCellPadding,n=r.tablePipeAlign,i=r.stringLength,o=t?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
19
|
+
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:g,table:a,tableCell:s,tableRow:c}};function a(m,h,b,x){return l(f(m,b,x),m.align)}function c(m,h,b,x){const w=u(m,b,x),C=l([w]);return C.slice(0,C.indexOf(`
|
|
20
|
+
`))}function s(m,h,b,x){const w=b.enter("tableCell"),C=b.enter("phrasing"),v=b.containerPhrasing(m,{...x,before:o,after:o});return C(),w(),v}function l(m,h){return la(m,{align:h,alignDelimiters:n,padding:t,stringLength:i})}function f(m,h,b){const x=m.children;let w=-1;const C=[],v=h.enter("table");for(;++w<x.length;)C[w]=u(x[w],h,b);return v(),C}function u(m,h,b){const x=m.children;let w=-1;const C=[],v=h.enter("tableRow");for(;++w<x.length;)C[w]=s(x[w],m,h,b);return v(),C}function g(m,h,b){let x=Yt.inlineCode(m,h,b);return b.stack.includes("tableCell")&&(x=x.replace(/\|/g,"\\$&")),x}}function Za(){return{exit:{taskListCheckValueChecked:gt,taskListCheckValueUnchecked:gt,paragraph:ti}}}function ei(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:ri}}}function gt(e){const r=this.stack[this.stack.length-2];r.type,r.checked=e.type==="taskListCheckValueChecked"}function ti(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 n=t.children[0];if(n&&n.type==="text"){const i=r.children;let o=-1,a;for(;++o<i.length;){const c=i[o];if(c.type==="paragraph"){a=c;break}}a===t&&(n.value=n.value.slice(1),n.value.length===0?t.children.shift():t.position&&n.position&&typeof n.position.start.offset=="number"&&(n.position.start.column++,n.position.start.offset++,t.position.start=Object.assign({},n.position.start)))}}this.exit(e)}function ri(e,r,t,n){const i=e.children[0],o=typeof e.checked=="boolean"&&i&&i.type==="paragraph",a="["+(e.checked?"x":" ")+"] ",c=t.createTracker(n);o&&c.move(a);let s=Yt.listItem(e,r,t,{...n,...c.current()});return o&&(s=s.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,l)),s;function l(f){return f+a}}function ni(){return[Nn(),Zn(),na(),Va(),Za()]}function ai(e){return{extensions:[En(),ea(e),aa(),Xa(e),ei()]}}function ve(e,r,t,n){const i=e.length;let o=0,a;if(r<0?r=-r>i?0:i+r:r=r>i?i:r,t=t>0?t:0,n.length<1e4)a=Array.from(n),a.unshift(r,t),e.splice(...a);else for(t&&e.splice(r,t);o<n.length;)a=n.slice(o,o+1e4),a.unshift(r,0),e.splice(...a),o+=1e4,r+=1e4}const xt={}.hasOwnProperty;function ii(e){const r={};let t=-1;for(;++t<e.length;)oi(r,e[t]);return r}function oi(e,r){let t;for(t in r){const i=(xt.call(e,t)?e[t]:void 0)||(e[t]={}),o=r[t];let a;if(o)for(a in o){xt.call(i,a)||(i[a]=[]);const c=o[a];si(i[a],Array.isArray(c)?c:c?[c]:[])}}}function si(e,r){let t=-1;const n=[];for(;++t<r.length;)(r[t].add==="after"?e:n).push(r[t]);ve(e,0,0,n)}const ci={tokenize:mi,partial:!0},Jt={tokenize:pi,partial:!0},Xt={tokenize:gi,partial:!0},Zt={tokenize:xi,partial:!0},li={tokenize:yi,partial:!0},er={name:"wwwAutolink",tokenize:fi,previous:rr},tr={name:"protocolAutolink",tokenize:hi,previous:nr},te={name:"emailAutolink",tokenize:di,previous:ar},J={};function ui(){return{text:J}}let ie=48;for(;ie<123;)J[ie]=te,ie++,ie===58?ie=65:ie===91&&(ie=97);J[43]=te;J[45]=te;J[46]=te;J[95]=te;J[72]=[te,tr];J[104]=[te,tr];J[87]=[te,er];J[119]=[te,er];function di(e,r,t){const n=this;let i,o;return a;function a(u){return!qe(u)||!ar.call(n,n.previous)||Ge(n.events)?t(u):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(u))}function c(u){return qe(u)?(e.consume(u),c):u===64?(e.consume(u),s):t(u)}function s(u){return u===46?e.check(li,f,l)(u):u===45||u===95||Ve(u)?(o=!0,e.consume(u),s):f(u)}function l(u){return e.consume(u),i=!0,s}function f(u){return o&&i&&pe(n.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),r(u)):t(u)}}function fi(e,r,t){const n=this;return i;function i(a){return a!==87&&a!==119||!rr.call(n,n.previous)||Ge(n.events)?t(a):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(ci,e.attempt(Jt,e.attempt(Xt,o),t),t)(a))}function o(a){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),r(a)}}function hi(e,r,t){const n=this;let i="",o=!1;return a;function a(u){return(u===72||u===104)&&nr.call(n,n.previous)&&!Ge(n.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),i+=String.fromCodePoint(u),e.consume(u),c):t(u)}function c(u){if(pe(u)&&i.length<5)return i+=String.fromCodePoint(u),e.consume(u),c;if(u===58){const g=i.toLowerCase();if(g==="http"||g==="https")return e.consume(u),s}return t(u)}function s(u){return u===47?(e.consume(u),o?l:(o=!0,s)):t(u)}function l(u){return u===null||yn(u)||q(u)||oe(u)||Ae(u)?t(u):e.attempt(Jt,e.attempt(Xt,f),t)(u)}function f(u){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),r(u)}}function mi(e,r,t){let n=0;return i;function i(a){return(a===87||a===119)&&n<3?(n++,e.consume(a),i):a===46&&n===3?(e.consume(a),o):t(a)}function o(a){return a===null?t(a):r(a)}}function pi(e,r,t){let n,i,o;return a;function a(l){return l===46||l===95?e.check(Zt,s,c)(l):l===null||q(l)||oe(l)||l!==45&&Ae(l)?s(l):(o=!0,e.consume(l),a)}function c(l){return l===95?n=!0:(i=n,n=void 0),e.consume(l),a}function s(l){return i||n||!o?t(l):r(l)}}function gi(e,r){let t=0,n=0;return i;function i(a){return a===40?(t++,e.consume(a),i):a===41&&n<t?o(a):a===33||a===34||a===38||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===60||a===63||a===93||a===95||a===126?e.check(Zt,r,o)(a):a===null||q(a)||oe(a)?r(a):(e.consume(a),i)}function o(a){return a===41&&n++,e.consume(a),i}}function xi(e,r,t){return n;function n(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),n):c===38?(e.consume(c),o):c===93?(e.consume(c),i):c===60||c===null||q(c)||oe(c)?r(c):t(c)}function i(c){return c===null||c===40||c===91||q(c)||oe(c)?r(c):n(c)}function o(c){return pe(c)?a(c):t(c)}function a(c){return c===59?(e.consume(c),n):pe(c)?(e.consume(c),a):t(c)}}function yi(e,r,t){return n;function n(o){return e.consume(o),i}function i(o){return Ve(o)?t(o):r(o)}}function rr(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||q(e)}function nr(e){return!pe(e)}function ar(e){return!(e===47||qe(e))}function qe(e){return e===43||e===45||e===46||e===95||Ve(e)}function Ge(e){let r=e.length,t=!1;for(;r--;){const n=e[r][1];if((n.type==="labelLink"||n.type==="labelImage")&&!n._balanced){t=!0;break}if(n._gfmAutolinkLiteralWalkedInto){t=!1;break}}return e.length>0&&!t&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),t}function bi(e,r,t){const n=[];let i=-1;for(;++i<e.length;){const o=e[i].resolveAll;o&&!n.includes(o)&&(r=o(r,t),n.push(o))}return r}function ee(e,r,t,n){const i=n?n-1:Number.POSITIVE_INFINITY;let o=0;return a;function a(s){return Z(s)?(e.enter(t),c(s)):r(s)}function c(s){return Z(s)&&o++<i?(e.consume(s),c):(e.exit(t),r(s))}}const wi={partial:!0,tokenize:ki};function ki(e,r,t){return n;function n(o){return Z(o)?ee(e,i,"linePrefix")(o):i(o)}function i(o){return o===null||le(o)?r(o):t(o)}}const Ci={tokenize:Pi,partial:!0};function vi(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Ai,continuation:{tokenize:Si},exit:Mi}},text:{91:{name:"gfmFootnoteCall",tokenize:Ii},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Ti,resolveTo:ji}}}}function Ti(e,r,t){const n=this;let i=n.events.length;const o=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let a;for(;i--;){const s=n.events[i][1];if(s.type==="labelImage"){a=s;break}if(s.type==="gfmFootnoteCall"||s.type==="labelLink"||s.type==="label"||s.type==="image"||s.type==="link")break}return c;function c(s){if(!a||!a._balanced)return t(s);const l=xe(n.sliceSerialize({start:a.end,end:n.now()}));return l.codePointAt(0)!==94||!o.includes(l.slice(1))?t(s):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(s),e.exit("gfmFootnoteCallLabelMarker"),r(s))}}function ji(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 n={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 o={type:"gfmFootnoteCallString",start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},a={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},c=[e[t+1],e[t+2],["enter",n,r],e[t+3],e[t+4],["enter",i,r],["exit",i,r],["enter",o,r],["enter",a,r],["exit",a,r],["exit",o,r],e[e.length-2],e[e.length-1],["exit",n,r]];return e.splice(t,e.length-t+1,...c),e}function Ii(e,r,t){const n=this,i=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let o=0,a;return c;function c(u){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(u),e.exit("gfmFootnoteCallLabelMarker"),s}function s(u){return u!==94?t(u):(e.enter("gfmFootnoteCallMarker"),e.consume(u),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",l)}function l(u){if(o>999||u===93&&!a||u===null||u===91||q(u))return t(u);if(u===93){e.exit("chunkString");const g=e.exit("gfmFootnoteCallString");return i.includes(xe(n.sliceSerialize(g)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(u),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),r):t(u)}return q(u)||(a=!0),o++,e.consume(u),u===92?f:l}function f(u){return u===91||u===92||u===93?(e.consume(u),o++,l):l(u)}}function Ai(e,r,t){const n=this,i=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let o,a=0,c;return s;function s(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(a>999||h===93&&!c||h===null||h===91||q(h))return t(h);if(h===93){e.exit("chunkString");const b=e.exit("gfmFootnoteDefinitionLabelString");return o=xe(n.sliceSerialize(b)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(h),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),g}return q(h)||(c=!0),a++,e.consume(h),h===92?u:f}function u(h){return h===91||h===92||h===93?(e.consume(h),a++,f):f(h)}function g(h){return h===58?(e.enter("definitionMarker"),e.consume(h),e.exit("definitionMarker"),i.includes(o)||i.push(o),ee(e,m,"gfmFootnoteDefinitionWhitespace")):t(h)}function m(h){return r(h)}}function Si(e,r,t){return e.check(wi,r,e.attempt(Ci,r,t))}function Mi(e){e.exit("gfmFootnoteDefinition")}function Pi(e,r,t){const n=this;return ee(e,i,"gfmFootnoteDefinitionIndent",5);function i(o){const a=n.events[n.events.length-1];return a&&a[1].type==="gfmFootnoteDefinitionIndent"&&a[2].sliceSerialize(a[1],!0).length===4?r(o):t(o)}}function _i(e){let t=(e||{}).singleTilde;const n={name:"strikethrough",tokenize:o,resolveAll:i};return t==null&&(t=!0),{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function i(a,c){let s=-1;for(;++s<a.length;)if(a[s][0]==="enter"&&a[s][1].type==="strikethroughSequenceTemporary"&&a[s][1]._close){let l=s;for(;l--;)if(a[l][0]==="exit"&&a[l][1].type==="strikethroughSequenceTemporary"&&a[l][1]._open&&a[s][1].end.offset-a[s][1].start.offset===a[l][1].end.offset-a[l][1].start.offset){a[s][1].type="strikethroughSequence",a[l][1].type="strikethroughSequence";const f={type:"strikethrough",start:Object.assign({},a[l][1].start),end:Object.assign({},a[s][1].end)},u={type:"strikethroughText",start:Object.assign({},a[l][1].end),end:Object.assign({},a[s][1].start)},g=[["enter",f,c],["enter",a[l][1],c],["exit",a[l][1],c],["enter",u,c]],m=c.parser.constructs.insideSpan.null;m&&ve(g,g.length,0,bi(m,a.slice(l+1,s),c)),ve(g,g.length,0,[["exit",u,c],["enter",a[s][1],c],["exit",a[s][1],c],["exit",f,c]]),ve(a,l-1,s-l+3,g),s=l+g.length-2;break}}for(s=-1;++s<a.length;)a[s][1].type==="strikethroughSequenceTemporary"&&(a[s][1].type="data");return a}function o(a,c,s){const l=this.previous,f=this.events;let u=0;return g;function g(h){return l===126&&f[f.length-1][1].type!=="characterEscape"?s(h):(a.enter("strikethroughSequenceTemporary"),m(h))}function m(h){const b=je(l);if(h===126)return u>1?s(h):(a.consume(h),u++,m);if(u<2&&!t)return s(h);const x=a.exit("strikethroughSequenceTemporary"),w=je(h);return x._open=!w||w===2&&!!b,x._close=!b||b===2&&!!w,c(h)}}}class Ni{constructor(){this.map=[]}add(r,t,n){Ei(this,r,t,n)}consume(r){if(this.map.sort(function(o,a){return o[0]-a[0]}),this.map.length===0)return;let t=this.map.length;const n=[];for(;t>0;)t-=1,n.push(r.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),r.length=this.map[t][0];n.push(r.slice()),r.length=0;let i=n.pop();for(;i;){for(const o of i)r.push(o);i=n.pop()}this.map.length=0}}function Ei(e,r,t,n){let i=0;if(!(t===0&&n.length===0)){for(;i<e.map.length;){if(e.map[i][0]===r){e.map[i][1]+=t,e.map[i][2].push(...n);return}i+=1}e.map.push([r,t,n])}}function Ri(e,r){let t=!1;const n=[];for(;r<e.length;){const i=e[r];if(t){if(i[0]==="enter")i[1].type==="tableContent"&&n.push(e[r+1][1].type==="tableDelimiterMarker"?"left":"none");else if(i[1].type==="tableContent"){if(e[r-1][1].type==="tableDelimiterMarker"){const o=n.length-1;n[o]=n[o]==="left"?"center":"right"}}else if(i[1].type==="tableDelimiterRow")break}else i[0]==="enter"&&i[1].type==="tableDelimiterRow"&&(t=!0);r+=1}return n}function Li(){return{flow:{null:{name:"table",tokenize:Di,resolveAll:Fi}}}}function Di(e,r,t){const n=this;let i=0,o=0,a;return c;function c(p){let F=n.events.length-1;for(;F>-1;){const E=n.events[F][1].type;if(E==="lineEnding"||E==="linePrefix")F--;else break}const K=F>-1?n.events[F][1].type:null,A=K==="tableHead"||K==="tableRow"?P:s;return A===P&&n.parser.lazy[n.now().line]?t(p):A(p)}function s(p){return e.enter("tableHead"),e.enter("tableRow"),l(p)}function l(p){return p===124||(a=!0,o+=1),f(p)}function f(p){return p===null?t(p):le(p)?o>1?(o=0,n.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),m):t(p):Z(p)?ee(e,f,"whitespace")(p):(o+=1,a&&(a=!1,i+=1),p===124?(e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),a=!0,f):(e.enter("data"),u(p)))}function u(p){return p===null||p===124||q(p)?(e.exit("data"),f(p)):(e.consume(p),p===92?g:u)}function g(p){return p===92||p===124?(e.consume(p),u):u(p)}function m(p){return n.interrupt=!1,n.parser.lazy[n.now().line]?t(p):(e.enter("tableDelimiterRow"),a=!1,Z(p)?ee(e,h,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(p):h(p))}function h(p){return p===45||p===58?x(p):p===124?(a=!0,e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),b):M(p)}function b(p){return Z(p)?ee(e,x,"whitespace")(p):x(p)}function x(p){return p===58?(o+=1,a=!0,e.enter("tableDelimiterMarker"),e.consume(p),e.exit("tableDelimiterMarker"),w):p===45?(o+=1,w(p)):p===null||le(p)?_(p):M(p)}function w(p){return p===45?(e.enter("tableDelimiterFiller"),C(p)):M(p)}function C(p){return p===45?(e.consume(p),C):p===58?(a=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(p),e.exit("tableDelimiterMarker"),v):(e.exit("tableDelimiterFiller"),v(p))}function v(p){return Z(p)?ee(e,_,"whitespace")(p):_(p)}function _(p){return p===124?h(p):p===null||le(p)?!a||i!==o?M(p):(e.exit("tableDelimiterRow"),e.exit("tableHead"),r(p)):M(p)}function M(p){return t(p)}function P(p){return e.enter("tableRow"),O(p)}function O(p){return p===124?(e.enter("tableCellDivider"),e.consume(p),e.exit("tableCellDivider"),O):p===null||le(p)?(e.exit("tableRow"),r(p)):Z(p)?ee(e,O,"whitespace")(p):(e.enter("data"),S(p))}function S(p){return p===null||p===124||q(p)?(e.exit("data"),O(p)):(e.consume(p),p===92?N:S)}function N(p){return p===92||p===124?(e.consume(p),S):S(p)}}function Fi(e,r){let t=-1,n=!0,i=0,o=[0,0,0,0],a=[0,0,0,0],c=!1,s=0,l,f,u;const g=new Ni;for(;++t<e.length;){const m=e[t],h=m[1];m[0]==="enter"?h.type==="tableHead"?(c=!1,s!==0&&(yt(g,r,s,l,f),f=void 0,s=0),l={type:"table",start:Object.assign({},h.start),end:Object.assign({},h.end)},g.add(t,0,[["enter",l,r]])):h.type==="tableRow"||h.type==="tableDelimiterRow"?(n=!0,u=void 0,o=[0,0,0,0],a=[0,t+1,0,0],c&&(c=!1,f={type:"tableBody",start:Object.assign({},h.start),end:Object.assign({},h.end)},g.add(t,0,[["enter",f,r]])),i=h.type==="tableDelimiterRow"?2:f?3:1):i&&(h.type==="data"||h.type==="tableDelimiterMarker"||h.type==="tableDelimiterFiller")?(n=!1,a[2]===0&&(o[1]!==0&&(a[0]=a[1],u=Ce(g,r,o,i,void 0,u),o=[0,0,0,0]),a[2]=t)):h.type==="tableCellDivider"&&(n?n=!1:(o[1]!==0&&(a[0]=a[1],u=Ce(g,r,o,i,void 0,u)),o=a,a=[o[1],t,0,0])):h.type==="tableHead"?(c=!0,s=t):h.type==="tableRow"||h.type==="tableDelimiterRow"?(s=t,o[1]!==0?(a[0]=a[1],u=Ce(g,r,o,i,t,u)):a[1]!==0&&(u=Ce(g,r,a,i,t,u)),i=0):i&&(h.type==="data"||h.type==="tableDelimiterMarker"||h.type==="tableDelimiterFiller")&&(a[3]=t)}for(s!==0&&yt(g,r,s,l,f),g.consume(r.events),t=-1;++t<r.events.length;){const m=r.events[t];m[0]==="enter"&&m[1].type==="table"&&(m[1]._align=Ri(r.events,t))}return e}function Ce(e,r,t,n,i,o){const a=n===1?"tableHeader":n===2?"tableDelimiter":"tableData",c="tableContent";t[0]!==0&&(o.end=Object.assign({},ce(r.events,t[0])),e.add(t[0],0,[["exit",o,r]]));const s=ce(r.events,t[1]);if(o={type:a,start:Object.assign({},s),end:Object.assign({},s)},e.add(t[1],0,[["enter",o,r]]),t[2]!==0){const l=ce(r.events,t[2]),f=ce(r.events,t[3]),u={type:c,start:Object.assign({},l),end:Object.assign({},f)};if(e.add(t[2],0,[["enter",u,r]]),n!==2){const g=r.events[t[2]],m=r.events[t[3]];if(g[1].end=Object.assign({},m[1].end),g[1].type="chunkText",g[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",u,r]])}return i!==void 0&&(o.end=Object.assign({},ce(r.events,i)),e.add(i,0,[["exit",o,r]]),o=void 0),o}function yt(e,r,t,n,i){const o=[],a=ce(r.events,t);i&&(i.end=Object.assign({},a),o.push(["exit",i,r])),n.end=Object.assign({},a),o.push(["exit",n,r]),e.add(t+1,0,o)}function ce(e,r){const t=e[r],n=t[0]==="enter"?"start":"end";return t[1][n]}const Ui={name:"tasklistCheck",tokenize:$i};function zi(){return{text:{91:Ui}}}function $i(e,r,t){const n=this;return i;function i(s){return n.previous!==null||!n._gfmTasklistFirstContentOfListItem?t(s):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(s),e.exit("taskListCheckMarker"),o)}function o(s){return q(s)?(e.enter("taskListCheckValueUnchecked"),e.consume(s),e.exit("taskListCheckValueUnchecked"),a):s===88||s===120?(e.enter("taskListCheckValueChecked"),e.consume(s),e.exit("taskListCheckValueChecked"),a):t(s)}function a(s){return s===93?(e.enter("taskListCheckMarker"),e.consume(s),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):t(s)}function c(s){return le(s)?r(s):Z(s)?e.check({tokenize:Oi},r,t)(s):t(s)}}function Oi(e,r,t){return ee(e,n,"whitespace");function n(i){return i===null?t(i):r(i)}}function Bi(e){return ii([ui(),vi(),_i(e),Li(),zi()])}const qi={};function Wi(e){const r=this,t=e||qi,n=r.data(),i=n.micromarkExtensions||(n.micromarkExtensions=[]),o=n.fromMarkdownExtensions||(n.fromMarkdownExtensions=[]),a=n.toMarkdownExtensions||(n.toMarkdownExtensions=[]);i.push(Bi(t)),o.push(ni()),a.push(ai(t))}function z(...e){return e.filter(Boolean).join(" ")}const Hi=({content:e})=>d.jsx($e.MarkdownTextPrimitive,{remarkPlugins:[Wi],className:"cuadra-aui-md",components:Qi,children:e}),Ye=y.memo(Hi),Vi=({language:e,code:r})=>{const{isCopied:t,copyToClipboard:n}=Ki(),i=()=>{!r||t||n(r)};return d.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:[d.jsx("span",{className:"cuadra-lowercase [&>span]:cuadra-text-xs cuadra-font-brand",children:e}),d.jsxs("button",{onClick:i,className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-muted cuadra-transition-colors","aria-label":"Copy code",children:[!t&&d.jsx(Tr,{className:"cuadra-h-4 cuadra-w-4"}),t&&d.jsx(wt,{className:"cuadra-h-4 cuadra-w-4"})]})]})},Ki=({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)})}}},Qi=$e.unstable_memoizeMarkdownComponents({h1:({className:e,...r})=>d.jsx("h1",{className:z("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})=>d.jsx("h2",{className:z("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})=>d.jsx("h3",{className:z("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})=>d.jsx("h4",{className:z("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})=>d.jsx("h5",{className:z("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})=>d.jsx("h6",{className:z("cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand",e),...r}),p:({className:e,...r})=>d.jsx("p",{className:z("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})=>d.jsx("a",{className:z("cuadra-text-primary cuadra-font-medium cuadra-underline cuadra-underline-offset-4 font-brand",e),...r}),blockquote:({className:e,...r})=>d.jsx("blockquote",{className:z("cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand",e),...r}),ul:({className:e,...r})=>d.jsx("ul",{className:z("cuadra-my-5 cuadra-ml-6 cuadra-list-disc [&>li]:cuadra-mt-2 font-brand",e),...r}),ol:({className:e,...r})=>d.jsx("ol",{className:z("cuadra-my-5 cuadra-ml-6 cuadra-list-decimal [&>li]:cuadra-mt-2 font-brand",e),...r}),hr:({className:e,...r})=>d.jsx("hr",{className:z("cuadra-my-5 cuadra-border-b",e),...r}),table:({className:e,...r})=>d.jsx("table",{className:z("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})=>d.jsx("th",{className:z("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})=>d.jsx("td",{className:z("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})=>d.jsx("tr",{className:z("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})=>d.jsx("sup",{className:z("[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand",e),...r}),pre:({className:e,...r})=>d.jsx("pre",{className:z("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 n=$e.useIsMarkdownCodeBlock();return d.jsx("code",{className:z(!n&&"cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand",r),...t})},CodeHeader:Vi});function Je({className:e="",variant:r="default",...t}){const n="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 d.jsx("div",{className:`${n} ${i[r]||i.default} ${e}`,...t})}function Gi(e){const r=new Map;for(const t of e){const n=r.get(t.filename);(!n||t.score>n.score)&&r.set(t.filename,t)}return Array.from(r.values()).sort((t,n)=>n.score-t.score)}function ir({sources:e,maxVisible:r=3}){if(!e||e.length===0)return null;const t=Gi(e),n=t.slice(0,r),i=t.length-r;return d.jsxs("div",{className:"cuadra-mt-4 cuadra-pt-3 cuadra-border-t cuadra-border-border",children:[d.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1.5 cuadra-mb-2.5",children:[d.jsx(kt,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground"}),d.jsx("span",{className:"cuadra-text-xs cuadra-font-medium cuadra-text-muted-foreground font-brand",children:"Sources"})]}),d.jsxs("div",{className:"cuadra-flex cuadra-flex-wrap cuadra-gap-2",children:[n.map((o,a)=>d.jsx(Ji,{source:o},o.sourceId||a)),i>0&&d.jsxs(Je,{variant:"subtle",children:["+",i," more"]})]})]})}function Yi(e){switch(e.split(".").pop()?.toLowerCase()){case"csv":case"xlsx":case"xls":return Ir;case"md":case"txt":return Mr;default:return kt}}function Ji({source:e}){const{filename:r,score:t}=e,n=Yi(r);return d.jsxs(Je,{className:"cuadra-gap-2 cuadra-cursor-default",title:t<1?`${Math.round(t*100)}% relevant`:void 0,children:[d.jsx(n,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-shrink-0 cuadra-opacity-60"}),d.jsx("span",{className:"cuadra-truncate cuadra-max-w-[180px]",children:r}),t<1&&t>0&&d.jsxs("span",{className:"cuadra-opacity-50 cuadra-text-[10px] cuadra-tabular-nums",children:[Math.round(t*100),"%"]})]})}const Xi=y.forwardRef(function({welcomeTitle:r="What shall we explore today?",extraTopPadding:t,suggestions:n,inputPlaceholder:i="Reply...",enableAttachments:o=!1,preMadeResponseDelay:a=1e3,streamingSpeed:c=50,safeArea:s=!1,composerBorder:l=!1,models:f,selectedModelId:u,onModelChange:g,showChatHeader:m=!1},h){const b=T.useThreadRuntime(),x=T.useAssistantApi(),[w,C]=y.useState(!1),[v,_]=y.useState(null),[M,P]=y.useState(!1),O=T.useThread(A=>{const E=A.messages;return!E||E.length===0}),S=O&&!w,N=y.useCallback((A,E,Q)=>{if(!M)try{const U=Q?.streamingSpeed??c,k=Q?.delay??a;Pt(A,E,U,k),x.composer().setText(A),setTimeout(()=>{x.composer().send()},10)}catch{}},[M,c,a,x]),p=y.useCallback(A=>{try{x.composer().setText(A),setTimeout(()=>{x.composer().send()},10)}catch{}},[x]),F=y.useCallback(async A=>{if(!(M||!b))try{if(A.response){const E=A.responseDelay??a;await N(A.prompt,A.response,{delay:E,streamingSpeed:c})}else p(A.prompt)}catch{}},[b,M,a,c,N,p]),K=y.useCallback(async()=>{try{const E=window.__cuadraThreadListRuntime?.threadList;E?.switchToNewThread&&await E.switchToNewThread()}catch{}},[]);return y.useImperativeHandle(h,()=>({sendMessage:p,sendPreMadeQA:N,clearChat:K}),[p,N,K]),y.useEffect(()=>{if(!b){C(!1);return}try{const A=b?.store;if(!A){C(!1);return}const E=A.subscribe?.(U=>{const k=U?.threadId,j=U?.messages||[],R=U?.isLoadingHistory||!1,L=j.length;k&&k!==v&&_(k),C(R&&L===0)}),Q=A.getState?.();if(Q){const U=Q?.threadId,k=Q?.messages||[],j=Q?.isLoadingHistory||!1,R=k.length;U&&U!==v&&_(U),C(j&&R===0)}return()=>{E&&E()}}catch{C(!1)}},[b,v]),d.jsxs(T.ThreadPrimitive.Root,{className:"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full cuadra-relative",children:[m&&d.jsx(io,{}),d.jsxs(T.ComposerPrimitive.AttachmentDropzone,{disabled:!o,className:`cuadra-flex-1 cuadra-flex cuadra-flex-col cuadra-min-h-0 cuadra-relative ${S?"cuadra-justify-center":""}`,children:[d.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:d.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-3",children:[d.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:d.jsx(Ur,{className:"cuadra-h-6 cuadra-w-6"})}),d.jsx("p",{className:"cuadra-text-sm cuadra-font-medium cuadra-text-foreground font-brand",children:"Drop files here"})]})}),d.jsx(T.ThreadPrimitive.Viewport,{className:`cuadra-w-full cuadra-bg-inherit cuadra-relative scrollbar-thin ${S?"cuadra-flex-none":"cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto"}`,style:{paddingTop:S?"0":t||(m?"0.5rem":"2rem")},children:w?d.jsx("div",{className:"cuadra-absolute cuadra-inset-0 cuadra-flex cuadra-items-center cuadra-justify-center",children:d.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-3",children:[d.jsx(Ct,{className:"cuadra-h-5 cuadra-w-5 cuadra-animate-spin cuadra-text-muted-foreground"}),d.jsx("p",{className:"cuadra-text-sm cuadra-text-muted-foreground font-brand",children:"Loading messages..."})]})}):d.jsxs("div",{className:"cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full cuadra-px-4",children:[d.jsx(T.ThreadPrimitive.Empty,{children:d.jsx(Zi,{title:r})}),d.jsx(T.ThreadPrimitive.Messages,{components:{UserMessage:eo,AssistantMessage:no}})]})}),d.jsx("div",{className:`cuadra-w-full cuadra-px-4 cuadra-pt-2 ${S?"cuadra-pb-2":"cuadra-pb-4"}`,style:s?{paddingBottom:"calc(env(safe-area-inset-bottom) + 1rem)"}:void 0,children:d.jsxs("div",{className:"cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full",children:[o&&d.jsx(T.ComposerPrimitive.Attachments,{components:{Attachment:()=>{const A=T.useAssistantState(({attachment:E})=>E);return A?d.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:[d.jsx(vt,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground",strokeWidth:1.5}),d.jsx("span",{className:"cuadra-text-xs cuadra-text-foreground font-brand",children:A.name||"Attachment"}),d.jsx(T.AttachmentPrimitive.Remove,{asChild:!0,children:d.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:d.jsx($r,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})})]}):null}}}),d.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:[d.jsx(T.ComposerPrimitive.Input,{asChild:!0,children:d.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"}})}),d.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-px-3 cuadra-pb-2.5 cuadra-pt-1",children:[d.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1",children:o&&d.jsx(T.ComposerPrimitive.AddAttachment,{multiple:!0,asChild:!0,children:d.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:[d.jsx(Tt,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground",strokeWidth:1.5}),d.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"})]})})}),d.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[f&&f.length>0&&d.jsx(ao,{models:f,selectedModelId:u,onModelChange:g,threadIsEmpty:O,onNewChat:K}),d.jsx(T.ComposerPrimitive.Send,{asChild:!0,children:d.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:d.jsx(wr,{className:"cuadra-h-4 cuadra-w-4",strokeWidth:2})})})]})]})]})]})}),S&&n&&n.length>0&&d.jsx("div",{className:"cuadra-flex cuadra-flex-wrap cuadra-justify-center cuadra-gap-2 cuadra-px-4 cuadra-pb-6 cuadra-pt-1 cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full",children:n.map((A,E)=>d.jsx("button",{type:"button",onClick:()=>F(A),disabled:M,className:"cuadra-px-3.5 cuadra-py-2 cuadra-rounded-full cuadra-text-sm cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-all cuadra-duration-200 font-brand cuadra-cursor-pointer disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed",style:{backgroundColor:"var(--cuadra-composer)",boxShadow:"0 0 0 1px rgba(0,0,0,0.06)"},children:A.prompt},`suggestion-${E}`))})]})]})});function Zi({title:e}){return d.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-text-center cuadra-py-6",children:d.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 eo(){return d.jsx(T.MessagePrimitive.Root,{className:"cuadra-flex cuadra-w-full cuadra-justify-end cuadra-py-2.5",children:d.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-end cuadra-gap-2 cuadra-max-w-[80%]",children:[d.jsx(T.MessagePrimitive.Attachments,{components:{Attachment:()=>{const e=T.useAssistantState(({attachment:o})=>o);if(!e)return null;const r=e.type==="image",t=e.file,n=e.content?.find(o=>o.type==="image"),i=t?URL.createObjectURL(t):n?.image;return d.jsx("div",{className:"cuadra-mb-1",children:r&&i?d.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)"}}):d.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:[d.jsx(vt,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground"}),d.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground font-brand",children:e.name||"Attachment"})]})})}}}),d.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:d.jsx(T.MessagePrimitive.Parts,{components:{Text:({text:e})=>d.jsx(Ye,{content:e||""})}})})]})})}function to({text:e}){const[r,t]=y.useState(!1),n=T.useAssistantState(({message:i})=>i?.status?.type==="running");return e?n?d.jsx("div",{className:"cuadra-mb-3 cuadra-py-1",children:d.jsx("div",{className:"cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand cuadra-animate-text-shimmer",children:e})}):d.jsxs("div",{className:"cuadra-mb-3",children:[d.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:[d.jsx(We,{className:`cuadra-h-3.5 cuadra-w-3.5 cuadra-shrink-0 cuadra-transition-transform cuadra-duration-200 ${r?"":"cuadra--rotate-90"}`}),d.jsx("span",{children:"Reasoning"})]}),d.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:d.jsx("div",{className:"cuadra-pl-5 cuadra-pt-2 cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand",children:d.jsx(Ye,{content:e})})})]}):null}function ro(){return d.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:[d.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1",children:[d.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}}),d.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}}),d.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}})]}),d.jsx("span",{children:"Thinking..."})]})}function no(){const e=T.useAssistantState(({message:a})=>a?.status?.type==="running"),r=T.useAssistantState(({message:a})=>{const c=a?.content;return!c||!Array.isArray(c)?!1:c.some(s=>!!(s.type==="text"&&s.text&&s.text.length>0||s.type==="reasoning"&&s.text&&s.text.length>0))}),t=y.useRef(!1),[n,i]=y.useState(null);y.useEffect(()=>{if(e&&r&&!t.current){const a=X.getCurrentMessageId();a&&(t.current=!0,i(a))}},[e,r]);const o=y.useSyncExternalStore(a=>X.subscribe(a),()=>{if(n){const a=X.getForMessage(n);return a.sources?.length?a.sources:null}if(e&&r){const a=X.getCurrentMessageId();if(a){const c=X.getForMessage(a);return c.sources?.length?c.sources:null}}return null},()=>null);return d.jsx(T.MessagePrimitive.Root,{className:"cuadra-flex cuadra-w-full cuadra-justify-start cuadra-py-2.5",children:d.jsxs("div",{className:"cuadra-text-foreground cuadra-max-w-full cuadra-break-words font-brand",style:{fontSize:"0.9375rem",lineHeight:"1.75"},children:[d.jsx(T.MessagePrimitive.Parts,{components:{Text:({text:a})=>d.jsx(Ye,{content:a||""}),Reasoning:({text:a})=>d.jsx(to,{text:a||""})}}),e&&!r&&d.jsx(ro,{}),o&&o.length>0&&d.jsx(ir,{sources:o})]})})}function ao({models:e,selectedModelId:r,onModelChange:t,threadIsEmpty:n,onNewChat:i}){const[o,a]=y.useState(!1),c=e.find(l=>l.id===r)||e[0];if(!c)return null;const s=async l=>{a(!1),!n&&l!==r&&await i?.(),t?.(l)};return d.jsxs("div",{className:"cuadra-relative",children:[d.jsxs("button",{type:"button",onClick:()=>a(!o),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:[d.jsx("span",{children:c.name}),d.jsx(We,{className:"cuadra-h-3 cuadra-w-3"})]}),o&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:()=>a(!1)}),d.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-overflow-hidden 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=>d.jsxs("button",{type:"button",className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-justify-between cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted/60 cuadra-transition-colors font-brand",onClick:()=>s(l.id),children:[d.jsxs("div",{className:"cuadra-flex cuadra-flex-col",children:[d.jsx("span",{className:"cuadra-text-foreground",children:l.name}),l.description&&d.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground",children:l.description})]}),l.id===r&&d.jsx(wt,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-primary cuadra-flex-shrink-0"})]},l.id))})]})]})}function io(){const e=T.useAssistantState(({threadListItem:i})=>i?.title??null),[r,t]=y.useState(!1),n=e||"Untitled chat";return d.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-px-3 cuadra-py-2 cuadra-min-h-[48px]",children:d.jsxs("div",{className:"cuadra-relative",children:[d.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:[d.jsx("span",{className:"cuadra-font-medium cuadra-truncate cuadra-max-w-[200px]",children:n}),d.jsx(We,{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&&d.jsx(oo,{onClose:()=>t(!1)})]})})}function oo({onClose:e}){return d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:e}),d.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:d.jsxs(T.ThreadListPrimitive.Root,{className:"cuadra-flex cuadra-flex-col",children:[d.jsx("div",{className:"cuadra-px-2 cuadra-py-1.5",children:d.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:[d.jsx(Tt,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"New Chat"]})}),d.jsx(so,{onSelect:e})]})})]})}function so({onSelect:e}){const r=T.useAssistantState(({threads:i})=>i?.threadIds??[]),t=T.useAssistantState(({threads:i})=>i?.newThreadId);return r.some(i=>i!==t)?d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"cuadra-mx-3 cuadra-my-0.5",style:{borderTop:"1px solid rgba(0,0,0,0.06)"}}),d.jsx("div",{className:"cuadra-overflow-y-auto cuadra-px-2 cuadra-pb-1.5 scrollbar-thin",style:{maxHeight:"340px"},children:d.jsx(T.ThreadListPrimitive.Items,{components:{ThreadListItem:i=>d.jsx(co,{...i,onSelect:e})}})})]}):null}function co({onSelect:e}){const r=T.useThreadListItem(),t=T.useThreadListItemRuntime(),n=T.useAssistantRuntime(),i=T.useThread(x=>x.threadId),o=r?.id===i,[a,c]=y.useState(!1),[s,l]=y.useState(!1),[f,u]=y.useState(r?.title||""),[g,m]=y.useState(!1),h=async()=>{if(!r?.remoteId||!f||f===r.title){l(!1);return}try{m(!0),await t.rename(f)}catch{}finally{m(!1),l(!1)}},b=async x=>{x.stopPropagation();try{o&&await n.switchToNewThread(),await t.delete()}catch(w){console.error("[CuadraChat] Failed to delete thread:",w)}};return y.useEffect(()=>{r?.title&&!s&&u(r.title)},[r?.title,s]),r?d.jsxs(T.ThreadListItemPrimitive.Root,{className:`cuadra-relative cuadra-flex cuadra-items-center cuadra-rounded-lg cuadra-transition-colors cuadra-cursor-pointer ${o?"cuadra-bg-muted":"hover:cuadra-bg-muted/60"}`,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:[s?d.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:d.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=>u(x.target.value),onKeyDown:x=>{x.stopPropagation(),x.key==="Enter"&&h(),x.key==="Escape"&&(l(!1),u(r.title||""))},onBlur:()=>void h(),disabled:g,autoFocus:!0})}):d.jsx(T.ThreadListItemPrimitive.Trigger,{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0 cuadra-cursor-pointer",onClick:()=>e?.(),children:d.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground cuadra-truncate cuadra-block cuadra-text-left font-brand",children:r.title||"Chat"})}),(a||o)&&!s&&d.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-0.5 cuadra-mr-1.5 cuadra-flex-shrink-0",children:[d.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-background/60 cuadra-transition-colors",onClick:x=>{x.stopPropagation(),l(!0),u(r.title||"Chat")},title:"Rename",children:d.jsx(Er,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})}),d.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-destructive/10 cuadra-transition-colors",onClick:b,title:"Delete",children:d.jsx(Dr,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-destructive"})})]})]}):null}const Ue=({children:e,className:r="",paddingX:t="px-0",paddingY:n="py-0",borderSizePx:i=2,style:o,contentStyle:a})=>d.jsx("div",{className:`cuadra-relative cuadra-bg-background md:cuadra-rounded-lg cuadra-overflow-hidden cuadra-flex cuadra-flex-col ${t} ${n} ${r}`,style:{border:i>0?`${i}px solid var(--cuadra-primary)`:"none",...o,...a},children:e}),lo=y.createContext(void 0),ze=({children:e,value:r})=>d.jsx(lo.Provider,{value:r,children:e});function uo(){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 n=document.createElement("link");n.setAttribute("data-cuadra-uikit","true"),n.rel="stylesheet",n.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:ue&&ue.tagName.toUpperCase()==="SCRIPT"&&ue.src||new URL("index.cjs",document.baseURI).href).href];let o=!1;for(const a of i)if(n.href=a,n.onload=()=>{o=!0},n.onerror=()=>{},document.head.appendChild(n),o)break},[])}const fo=y.forwardRef(function({config:r},t){uo();const n=y.useRef(null),i=y.useRef(!1),{baseUrl:o,proxyUrl:a,sessionToken:c,mode:s="multiChat",modelMode:l="fixed",modelId:f,onModelChange:u,ephemeral:g=!1,systemPrompt:m,enableReasoning:h=!1,initialThreadId:b,welcomeTitle:x,welcomeSubtitle:w,extraTopPadding:C,suggestions:v,inputPlaceholder:_,preMadeResponseDelay:M=1e3,streamingSpeed:P=50,initialMessage:O,initialPreMadeQA:S,theme:N="system",onError:p,onChatCreated:F,onUserMessage:K,onThreadIdUpdate:A,enableAttachments:E=!1,onBeforeRequest:Q,mockResponseOnBlocked:U}=r;y.useImperativeHandle(t,()=>({sendMessage:D=>{n.current?.sendMessage(D)},sendPreMadeQA:(D,ae,ne)=>{n.current?.sendPreMadeQA(D,ae,ne)},clearChat:()=>{n.current?.clearChat()}}),[]),y.useEffect(()=>{if(i.current)return;const D=setTimeout(()=>{S?(i.current=!0,n.current?.sendPreMadeQA(S.question,S.answer,{delay:M,streamingSpeed:P})):O&&(i.current=!0,n.current?.sendMessage(O))},500);return()=>clearTimeout(D)},[O,S,M,P]);const k=a||o||"",j=!!a,R=y.useMemo(()=>new It(k,c||void 0,j),[k,c,j]),[L,V]=y.useState(null),[I,B]=y.useState(!1),[G,re]=y.useState(null),[ye,be]=y.useState(!1);y.useEffect(()=>{s==="multiChat"&&be(!0)},[s]);const H=y.useCallback(async()=>{if(l==="selector"){B(!0),re(null);try{const D=await R.listModels();V(D)}catch(D){re(D instanceof Error?D:new Error("Failed to load models"))}finally{B(!1)}}},[R,l]);y.useEffect(()=>{l==="selector"&&H()},[l,H]),y.useEffect(()=>(typeof window<"u"&&(window.__cuadraUIKitRefetchModels=H),()=>{typeof window<"u"&&delete window.__cuadraUIKitRefetchModels}),[H]);const[Y,Ze]=y.useState(l==="fixed"&&f||null),et=y.useRef(Y),we=y.useCallback(D=>{const ae=et.current;Ze(D),et.current=D,u?.(D),ae!==null&&ae!==D&&s==="multiChat"&&setTimeout(()=>{const ne=window.__cuadraThreadListRuntime;if(ne?.threads?.switchToNewThread)try{ne.threads.switchToNewThread()}catch{}else if(ne?.threads?.createThread)try{ne.threads.createThread()}catch{}else if(ne?.switchToNewThread)try{ne.switchToNewThread()}catch{}},100)},[u,s]);y.useEffect(()=>{if(l==="selector"&&L?.items&&L.items.length>0&&!Y){const D=L.items[0];if(D?.id){const ae=D.id;Ze(ae),u?.(ae)}}},[l,L?.items,Y,u]);const ur=l==="fixed"?!!f:!!Y,_e=y.useMemo(()=>(L?.items||[]).filter(D=>D?.id&&D?.displayName).map(D=>({id:D.id,name:D.displayName})),[L]),Ne=y.useMemo(()=>({currentModelId:Y||"",models:_e,modelsLoading:I,modelsError:G,onModelChange:we,refetchModels:H}),[Y,_e,I,G,we,H]);return l==="selector"&&I||s==="multiChat"&&ye?d.jsx(ze,{value:Ne,children:d.jsx(Ue,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",borderSizePx:r.borderless?0:2,children:d.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:d.jsx(Ct,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"})})})}):l==="selector"&&!ur&&G?d.jsx(ze,{value:Ne,children:d.jsx(Ue,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",children:d.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:d.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2",children:d.jsx("p",{className:"cuadra-text-sm cuadra-text-destructive font-brand",children:"Failed to load models"})})})})}):d.jsx("div",{className:"cuadra-uikit cuadra-h-full cuadra-w-full",style:{height:"100%",width:"100%"},children:d.jsx(ze,{value:Ne,children:d.jsx(pn,{baseUrl:j?k:o||k,sessionToken:c,isProxyMode:j,mode:s,modelMode:l,modelId:Y||f||void 0,onModelChange:we,ephemeral:g,systemPrompt:m,enableReasoning:h,initialThreadId:b,enableAttachments:E,onError:p,onChatCreated:F,onUserMessage:K,onThreadIdUpdate:A,onBeforeRequest:Q,mockResponseOnBlocked:U,onChatsLoaded:()=>{s==="multiChat"&&be(!1)},children:d.jsx(Ue,{paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",className:`cuadra-h-full ${r.containerClass||""}`,borderSizePx:r.borderless?0:2,style:{height:"100%"},children:d.jsx("div",{className:"cuadra-h-full cuadra-flex cuadra-relative",style:{height:"100%"},children:d.jsx("div",{className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:d.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0",children:d.jsx(Xi,{ref:n,welcomeTitle:x,welcomeSubtitle:w,extraTopPadding:C,suggestions:v,inputPlaceholder:_,enableAttachments:E,preMadeResponseDelay:M,streamingSpeed:P,safeArea:r.safeArea,showChatHeader:s==="multiChat",models:l==="selector"?_e:void 0,selectedModelId:Y||void 0,onModelChange:l==="selector"?we:void 0,theme:N})})})})})})})})});function or(e,r=":root"){if(typeof document>"u")return;const t=document.documentElement;if(e.light&&mo(e.light,t),e.dark){let n=document.getElementById("cuadra-theme-dark");n||(n=document.createElement("style"),n.id="cuadra-theme-dark",document.head.appendChild(n));const i=po(e.dark);n.textContent=`.dark { ${i} }`}}const ho={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 sr(e){const r=ho[e];return r?`--cuadra-${r}`:`--cuadra-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function mo(e,r){Object.entries(e).forEach(([t,n])=>{if(n){const i=sr(t);r.style.setProperty(i,n)}})}function po(e){return Object.entries(e).map(([r,t])=>t?`${sr(r)}: ${t};`:"").filter(Boolean).join(" ")}function go(){if(typeof document>"u")return;const e=document.documentElement;Array.from(e.style).filter(n=>n.startsWith("--cuadra-")).forEach(n=>e.style.removeProperty(n));const t=document.getElementById("cuadra-theme-dark");t&&t.remove()}function xo({onReset:e,error:r}){return d.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-h-full cuadra-p-6 cuadra-text-center",children:[d.jsx("div",{className:"cuadra-mb-4",children:d.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:d.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"})})}),d.jsx("h3",{className:"cuadra-text-lg cuadra-font-medium cuadra-text-foreground cuadra-mb-2",children:"Something went wrong"}),d.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."}),d.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 Xe extends y.Component{constructor(t){super(t);$(this,"reset",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){this.props.onError?.(t,n)}render(){if(this.state.hasError){const{fallback:t}=this.props,{error:n}=this.state;return typeof t=="function"?t(n,this.reset):t||d.jsx(xo,{error:n,onReset:this.reset})}return this.props.children}}function yo(e,r){const t=n=>d.jsx(Xe,{...r,children:d.jsx(e,{...n})});return t.displayName=`withErrorBoundary(${e.displayName||e.name||"Component"})`,t}const fe=y.createContext(null);fe.displayName="CuadraChatContext";function bo(){const e=y.useContext(fe);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 wo(){const e=y.useContext(fe);return e===null?null:{controls:e.controls,isReady:e.controls!==null}}function ko({children:e}){const[r,t]=y.useState(null),n=y.useCallback(a=>{t(a)},[]),i=y.useCallback(()=>{t(null)},[]),o=y.useMemo(()=>({controls:r,registerControls:n,unregisterControls:i}),[r,n,i]);return d.jsx(fe.Provider,{value:o,children:e})}function cr(e){return"connection"in e&&typeof e.connection=="object"}function lr(e){return cr(e)?Co(e):vo(e)}function Co(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,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 vo(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
|
+
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,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 To=y.forwardRef(function({config:r},t){const n=y.useRef(null),i=y.useContext(fe);y.useEffect(()=>{r.ui.customTheme&&or(r.ui.customTheme)},[r.ui.customTheme]),y.useEffect(()=>{if(r.ui.primaryColor&&typeof document<"u"){const c=document.documentElement,s=l=>{const f=l.replace("#",""),u=parseInt(f.slice(0,2),16)/255,g=parseInt(f.slice(2,4),16)/255,m=parseInt(f.slice(4,6),16)/255,h=Math.max(u,g,m),b=Math.min(u,g,m);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 u:x=((g-m)/v+(g<m?6:0))/6;break;case g:x=((m-u)/v+2)/6;break;case m:x=((u-g)/v+4)/6;break}}return`${Math.round(x*360)} ${Math.round(w*100)}% ${Math.round(C*100)}%`};try{const l=s(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 o=y.useMemo(()=>({sendMessage:c=>n.current?.sendMessage(c),sendPreMadeQA:(c,s,l)=>n.current?.sendPreMadeQA(c,s,l),clearChat:()=>n.current?.clearChat()}),[]);y.useImperativeHandle(t,()=>o,[]),y.useEffect(()=>{if(i)return i.registerControls(o),()=>i.unregisterControls()},[i,o]),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=o),()=>{typeof window<"u"&&delete window.__cuadraChatControls}),[o]);const a={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,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 d.jsx(fo,{ref:n,config:a})}),jo=y.forwardRef(function(r,t){const n=lr(r),i=n.errorFallback;return d.jsx(Xe,{fallback:i,onError:(o,a)=>{n.callbacks.onError?.(o),process.env.NODE_ENV==="development"&&console.error("[CuadraChat] Error caught by boundary:",o,a)},children:d.jsx(To,{ref:t,config:n})})});exports.AttachmentValidationError=he;exports.Badge=Je;exports.CuadraChat=jo;exports.CuadraChatContext=fe;exports.CuadraChatProvider=ko;exports.CuadraErrorBoundary=Xe;exports.SourceCitations=ir;exports.applyTheme=or;exports.createAttachmentAdapter=He;exports.escapeHtml=Vr;exports.generateSecureUUID=jt;exports.isV2Props=cr;exports.isValidUrl=qr;exports.normalizeCuadraChatProps=lr;exports.removeTheme=go;exports.sanitizeSystemPrompt=Br;exports.streamingMetadataStore=X;exports.useCuadraChat=bo;exports.useCuadraChatOptional=wo;exports.validateBaseUrl=Wr;exports.withErrorBoundary=yo;
|
|
22
22
|
//# sourceMappingURL=index.cjs.map
|