@cuadra-ai/uikit 0.4.13 → 0.4.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +19 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +2625 -2409
- package/dist/index.mjs.map +1 -1
- package/dist/uikit.css +1 -1
- package/dist/widget/cuadra-uikit.css +1 -1
- package/dist/widget/cuadra-uikit.umd.js +26 -26
- package/dist/widget/cuadra-uikit.umd.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,36 +1,36 @@
|
|
|
1
|
-
(function($,p){typeof exports=="object"&&typeof module!="undefined"?p(exports,require("react/jsx-runtime"),require("react"),require("react-dom/client"),require("react-dom")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","react-dom/client","react-dom"],p):($=typeof globalThis!="undefined"?globalThis:$||self,p($.CuadraUIKit={},$.React,$.React,$.ReactDOM))})(this,(function($,p,
|
|
1
|
+
(function($,p){typeof exports=="object"&&typeof module!="undefined"?p(exports,require("react/jsx-runtime"),require("react"),require("react-dom/client"),require("react-dom")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","react-dom/client","react-dom"],p):($=typeof globalThis!="undefined"?globalThis:$||self,p($.CuadraUIKit={},$.React,$.React,$.ReactDOM))})(this,(function($,p,b,ge){"use strict";var Av=Object.defineProperty,Mv=Object.defineProperties;var Pv=Object.getOwnPropertyDescriptors;var In=Object.getOwnPropertySymbols;var ju=Object.prototype.hasOwnProperty,$u=Object.prototype.propertyIsEnumerable;var ys=($,p)=>(p=Symbol[$])?p:Symbol.for("Symbol."+$),Uu=$=>{throw TypeError($)},Hu=Math.pow,bs=($,p,b)=>p in $?Av($,p,{enumerable:!0,configurable:!0,writable:!0,value:b}):$[p]=b,m=($,p)=>{for(var b in p||(p={}))ju.call(p,b)&&bs($,b,p[b]);if(In)for(var b of In(p))$u.call(p,b)&&bs($,b,p[b]);return $},I=($,p)=>Mv($,Pv(p));var H=($,p)=>{var b={};for(var ge in $)ju.call($,ge)&&p.indexOf(ge)<0&&(b[ge]=$[ge]);if($!=null&&In)for(var ge of In($))p.indexOf(ge)<0&&$u.call($,ge)&&(b[ge]=$[ge]);return b};var T=($,p,b)=>bs($,typeof p!="symbol"?p+"":p,b),qu=($,p,b)=>p.has($)||Uu("Cannot "+b);var We=($,p,b)=>(qu($,p,"read from private field"),b?b.call($):p.get($)),nr=($,p,b)=>p.has($)?Uu("Cannot add the same private member more than once"):p instanceof WeakSet?p.add($):p.set($,b),ar=($,p,b,ge)=>(qu($,p,"write to private field"),ge?ge.call($,b):p.set($,b),b);var M=($,p,b)=>new Promise((ge,$e)=>{var Ue=Ie=>{try{Le(b.next(Ie))}catch(Be){$e(Be)}},Z=Ie=>{try{Le(b.throw(Ie))}catch(Be){$e(Be)}},Le=Ie=>Ie.done?ge(Ie.value):Promise.resolve(Ie.value).then(Ue,Z);Le((b=b.apply($,p)).next())}),Ae=function($,p){this[0]=$,this[1]=p},Or=($,p,b)=>{var ge=(Z,Le,Ie,Be)=>{try{var sr=b[Z](Le),Fr=(Le=sr.value)instanceof Ae,Mn=sr.done;Promise.resolve(Fr?Le[0]:Le).then(nt=>Fr?ge(Z==="return"?Z:"next",Le[1]?{done:nt.done,value:nt.value}:nt,Ie,Be):Ie({value:nt,done:Mn})).catch(nt=>ge("throw",nt,Ie,Be))}catch(nt){Be(nt)}},$e=Z=>Ue[Z]=Le=>new Promise((Ie,Be)=>ge(Z,Le,Ie,Be)),Ue={};return b=b.apply($,p),Ue[ys("asyncIterator")]=()=>Ue,$e("next"),$e("throw"),$e("return"),Ue};var Ft=($,p,b)=>(p=$[ys("asyncIterator")])?p.call($):($=$[ys("iterator")](),p={},b=(ge,$e)=>($e=$[ge])&&(p[ge]=Ue=>new Promise((Z,Le,Ie)=>(Ue=$e.call($,Ue),Ie=Ue.done,Promise.resolve(Ue.value).then(Be=>Z({value:Be,done:Ie}),Le)))),b("next"),b("return"),p);var tt,Lt,Ke,Fu,Ar,zu,Mr,Pr,Nr,Bu,Ru;var $e=typeof document!="undefined"?document.currentScript:null;function Ue(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const Z=Ue(b);const Le=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Ie=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,r,n)=>n?n.toUpperCase():r.toLowerCase()),Be=e=>{const t=Ie(e);return t.charAt(0).toUpperCase()+t.slice(1)},sr=(...e)=>e.filter((t,r,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===r).join(" ").trim(),Fr=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var Mn={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 nt=b.forwardRef((u,l)=>{var d=u,{color:e="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:a="",children:s,iconNode:i}=d,o=H(d,["color","size","strokeWidth","absoluteStrokeWidth","className","children","iconNode"]);return b.createElement("svg",m(m(I(m({ref:l},Mn),{width:t,height:t,stroke:e,strokeWidth:n?Number(r)*24/Number(t):r,className:sr("lucide",a)}),!s&&!Fr(o)&&{"aria-hidden":"true"}),o),[...i.map(([c,f])=>b.createElement(c,f)),...Array.isArray(s)?s:[s]])});const Te=(e,t)=>{const r=b.forwardRef((i,s)=>{var o=i,{className:n}=o,a=H(o,["className"]);return b.createElement(nt,m({ref:s,iconNode:t,className:sr(`lucide-${Le(Be(e))}`,`lucide-${e}`,n)},a))});return r.displayName=Be(e),r};const Wu=Te("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);const Pn=Te("brain",[["path",{d:"M12 18V5",key:"adv99a"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4",key:"1e3is1"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5",key:"1gqd8o"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77",key:"iwvgf7"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464",key:"efp6ie"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517",key:"1gq6am"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464",key:"k1g0md"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77",key:"q97ue3"}]]);const Nn=Te("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);const Ln=Te("chevron-down",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);const Ju=Te("circle-alert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);const Ku=Te("copy",[["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"}]]);const Yu=Te("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);const Dn=Te("eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);const Gu=Te("file-spreadsheet",[["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"}]]);const ws=Te("file-text",[["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"}]]);const Xu=Te("file-type",[["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"}]]);const vs=Te("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);const Qu=Te("message-square",[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]]);const ks=Te("paperclip",[["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"}]]);const Ss=Te("pencil",[["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"}]]);const On=Te("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);const _s=Te("trash-2",[["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"}]]);const Zu=Te("upload",[["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"}]]);const zr=Te("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);var ec=e=>Array.from(e).map(r=>r.getModelContext()).sort((r,n)=>{var a,s;return((a=n.priority)!=null?a:0)-((s=r.priority)!=null?s:0)}).reduce((r,n)=>{var a;if(n.system&&(r.system?r.system+=`
|
|
2
2
|
|
|
3
|
-
${n.system}`:r.system=n.system),n.tools)for(const[a,s]of Object.entries(n.tools)){const o=(i=r.tools)==null?void 0:i[a];if(o&&o!==s)throw new Error(`You tried to define a tool with the name ${a}, but it already exists.`);r.tools||(r.tools={}),r.tools[a]=s}return n.config&&(r.config=m(m({},r.config),n.config)),n.callSettings&&(r.callSettings=m(m({},r.callSettings),n.callSettings)),r},{}),Pn=class{constructor(){T(this,"_providers",new Set);T(this,"_subscribers",new Set)}getModelContext(){return Gu(this._providers)}registerModelContextProvider(e){var r;this._providers.add(e);const t=(r=e.subscribe)==null?void 0:r.call(e,()=>{this.notifySubscribers()});return this.notifySubscribers(),()=>{this._providers.delete(e),t==null||t(),this.notifySubscribers()}}notifySubscribers(){for(const e of this._subscribers)e()}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}},Nn=class{constructor(){T(this,"_contextProvider",new Pn)}registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}},ar=class{constructor(){T(this,"_subscribers",new Set)}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}waitForUpdate(){return new Promise(e=>{const t=this.subscribe(()=>{t(),e()})})}_notifySubscribers(){const e=[];for(const t of this._subscribers)try{t()}catch(r){e.push(r)}if(e.length>0)throw e.length===1?e[0]:new AggregateError(e)}},Xu=e=>e.status.type==="complete",xa=class extends ar{constructor(){super(...arguments);T(this,"isEditing",!0);T(this,"_attachments",[]);T(this,"_text","");T(this,"_role","user");T(this,"_runConfig",{});T(this,"_eventSubscribers",new Map)}get attachmentAccept(){var t,r;return(r=(t=this.getAttachmentAdapter())==null?void 0:t.accept)!=null?r:"*"}get attachments(){return this._attachments}setAttachments(t){this._attachments=t,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}get text(){return this._text}get role(){return this._role}get runConfig(){return this._runConfig}setText(t){this._text!==t&&(this._text=t,this._notifySubscribers())}setRole(t){this._role!==t&&(this._role=t,this._notifySubscribers())}setRunConfig(t){this._runConfig!==t&&(this._runConfig=t,this._notifySubscribers())}_emptyTextAndAttachments(){this._attachments=[],this._text="",this._notifySubscribers()}_onClearAttachments(){return M(this,null,function*(){const t=this.getAttachmentAdapter();t&&(yield Promise.all(this._attachments.map(r=>t.remove(r))))})}reset(){return M(this,null,function*(){if(this._attachments.length===0&&this._text===""&&this._role==="user"&&Object.keys(this._runConfig).length===0)return;this._role="user",this._runConfig={};const t=this._onClearAttachments();this._emptyTextAndAttachments(),yield t})}clearAttachments(){return M(this,null,function*(){const t=this._onClearAttachments();this.setAttachments([]),yield t})}send(){return M(this,null,function*(){const t=this.getAttachmentAdapter(),r=t&&this.attachments.length>0?Promise.all(this.attachments.map(a=>M(this,null,function*(){return Xu(a)?a:yield t.send(a)}))):[],n=this.text;this._emptyTextAndAttachments();const i={createdAt:new Date,role:this.role,content:n?[{type:"text",text:n}]:[],attachments:yield r,runConfig:this.runConfig,metadata:{custom:{}}};this.handleSend(i),this._notifyEventSubscribers("send")})}cancel(){this.handleCancel()}addAttachment(t){return M(this,null,function*(){const r=this.getAttachmentAdapter();if(!r)throw new Error("Attachments are not supported");const n=u=>{const d=this._attachments.findIndex(c=>c.id===u.id);d!==-1?this._attachments=[...this._attachments.slice(0,d),u,...this._attachments.slice(d+1)]:this._attachments=[...this._attachments,u],this._notifySubscribers()},i=r.add({file:t});if(Symbol.asyncIterator in i)try{for(var a=Ft(i),s,o,l;s=!(o=yield a.next()).done;s=!1){const u=o.value;n(u)}}catch(o){l=[o]}finally{try{s&&(o=a.return)&&(yield o.call(a))}finally{if(l)throw l[0]}}else n(yield i);this._notifyEventSubscribers("attachment-add"),this._notifySubscribers()})}removeAttachment(t){return M(this,null,function*(){const r=this.getAttachmentAdapter();if(!r)throw new Error("Attachments are not supported");const n=this._attachments.findIndex(a=>a.id===t);if(n===-1)throw new Error("Attachment not found");const i=this._attachments[n];yield r.remove(i),this._attachments=[...this._attachments.slice(0,n),...this._attachments.slice(n+1)],this._notifySubscribers()})}_notifyEventSubscribers(t){const r=this._eventSubscribers.get(t);if(r)for(const n of r)n()}unstable_on(t,r){const n=this._eventSubscribers.get(t);return n?n.add(r):this._eventSubscribers.set(t,new Set([r])),()=>{const i=this._eventSubscribers.get(t);i&&i.delete(r)}}},va=class extends xa{constructor(t){super();T(this,"_canCancel",!1);this.runtime=t,this.connect()}get canCancel(){return this._canCancel}get attachments(){return super.attachments}getAttachmentAdapter(){var t;return(t=this.runtime.adapters)==null?void 0:t.attachments}connect(){return this.runtime.subscribe(()=>{this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,this._notifySubscribers())})}handleSend(t){return M(this,null,function*(){var r,n;this.runtime.append(I(m({},t),{parentId:(n=(r=this.runtime.messages.at(-1))==null?void 0:r.id)!=null?n:null,sourceId:null}))})}handleCancel(){return M(this,null,function*(){this.runtime.cancelRun()})}};let ka=(e,t=21)=>(r=t)=>{let n="",i=r|0;for(;i--;)n+=e[Math.random()*e.length|0];return n};var _t=ka("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),Qu="__optimistic__",Zu=()=>`${Qu}${_t()}`,sr=Symbol("autoStatus"),ec=Object.freeze(Object.assign({type:"running"},{[sr]:!0})),tc=Object.freeze(Object.assign({type:"complete",reason:"unknown"},{[sr]:!0})),rc=Object.freeze(Object.assign({type:"requires-action",reason:"tool-calls"},{[sr]:!0})),nc=Object.freeze(Object.assign({type:"requires-action",reason:"interrupt"},{[sr]:!0})),Sa=(e,t,r,n,i)=>e&&i?Object.assign({type:"incomplete",reason:"error",error:i},{[sr]:!0}):e&&t?ec:r?nc:n?rc:tc;function Fr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Tt={exports:{}},_a;function ic(){if(_a)return Tt.exports;_a=1;const e=typeof Buffer!="undefined",t=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,r=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function n(o,l,u){u==null&&l!==null&&typeof l=="object"&&(u=l,l=void 0),e&&Buffer.isBuffer(o)&&(o=o.toString()),o&&o.charCodeAt(0)===65279&&(o=o.slice(1));const d=JSON.parse(o,l);if(d===null||typeof d!="object")return d;const c=u&&u.protoAction||"error",f=u&&u.constructorAction||"error";if(c==="ignore"&&f==="ignore")return d;if(c!=="ignore"&&f!=="ignore"){if(t.test(o)===!1&&r.test(o)===!1)return d}else if(c!=="ignore"&&f==="ignore"){if(t.test(o)===!1)return d}else if(r.test(o)===!1)return d;return i(d,{protoAction:c,constructorAction:f,safe:u&&u.safe})}function i(o,{protoAction:l="error",constructorAction:u="error",safe:d}={}){let c=[o];for(;c.length;){const f=c;c=[];for(const h of f){if(l!=="ignore"&&Object.prototype.hasOwnProperty.call(h,"__proto__")){if(d===!0)return null;if(l==="error")throw new SyntaxError("Object contains forbidden prototype property");delete h.__proto__}if(u!=="ignore"&&Object.prototype.hasOwnProperty.call(h,"constructor")&&h.constructor!==null&&typeof h.constructor=="object"&&Object.prototype.hasOwnProperty.call(h.constructor,"prototype")){if(d===!0)return null;if(u==="error")throw new SyntaxError("Object contains forbidden prototype property");delete h.constructor}for(const g in h){const x=h[g];x&&typeof x=="object"&&c.push(x)}}}return o}function a(o,l,u){const{stackTraceLimit:d}=Error;Error.stackTraceLimit=0;try{return n(o,l,u)}finally{Error.stackTraceLimit=d}}function s(o,l){const{stackTraceLimit:u}=Error;Error.stackTraceLimit=0;try{return n(o,l,{safe:!0})}catch(d){return}finally{Error.stackTraceLimit=u}}return Tt.exports=a,Tt.exports.default=a,Tt.exports.parse=a,Tt.exports.safeParse=s,Tt.exports.scan=i,Tt.exports}var ac=ic();const Ln=Fr(ac);function sc(e){const t=["ROOT"];let r=-1,n=null;const i=[];let a;function s(){a!==void 0&&(i.push(JSON.parse(`"${a}"`)),a=void 0)}function o(c,f,h){switch(c){case'"':{r=f,t.pop(),t.push(h),t.push("INSIDE_STRING"),s();break}case"f":case"t":case"n":{r=f,n=f,t.pop(),t.push(h),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(h),t.push("INSIDE_NUMBER"),s();break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=f,t.pop(),t.push(h),t.push("INSIDE_NUMBER"),s();break}case"{":{r=f,t.pop(),t.push(h),t.push("INSIDE_OBJECT_START"),s();break}case"[":{r=f,t.pop(),t.push(h),t.push("INSIDE_ARRAY_START"),s();break}}}function l(c,f){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=f,t.pop(),a=i.pop();break}}}function u(c,f){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),a=(Number(a)+1).toString();break}case"]":{r=f,t.pop(),a=i.pop();break}}}for(let c=0;c<e.length;c++){const f=e[c];switch(t[t.length-1]){case"ROOT":o(f,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),a="";break}case"}":{r=c,t.pop(),a=i.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),a="";break}}break}case"INSIDE_OBJECT_KEY":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}case"\\":{t.push("INSIDE_STRING_ESCAPE"),a+=f;break}default:{a+=f;break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(f){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(f,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{l(f,c);break}case"INSIDE_STRING":{switch(f){case'"':{t.pop(),r=c,a=i.pop();break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=c}break}case"INSIDE_ARRAY_START":{switch(f){case"]":{r=c,t.pop(),a=i.pop();break}default:{r=c,a="0",o(f,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(f){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),a=(Number(a)+1).toString();break}case"]":{r=c,t.pop(),a=i.pop();break}default:{r=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(f,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),t[t.length-1]==="INSIDE_STRING"?r=c:t[t.length-1]==="INSIDE_OBJECT_KEY"&&(a+=f);break}case"INSIDE_NUMBER":{switch(f){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),a=i.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(f,c);break}case"}":{t.pop(),a=i.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(f,c);break}case"]":{t.pop(),a=i.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,c);break}default:{t.pop(),a=i.pop();break}}break}case"INSIDE_LITERAL":{const g=e.substring(n,c+1);!"false".startsWith(g)&&!"true".startsWith(g)&&!"null".startsWith(g)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?l(f,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,c)):r=c;break}}}let d=e.slice(0,r+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){case"INSIDE_STRING":{d+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{d+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{d+="]";break}case"INSIDE_LITERAL":{const h=e.substring(n,e.length);"true".startsWith(h)?d+="true".slice(h.length):"false".startsWith(h)?d+="false".slice(h.length):"null".startsWith(h)&&(d+="null".slice(h.length))}}return[d,i]}var zr=Symbol("aui.parse-partial-json-object.meta"),oc=e=>e==null?void 0:e[zr],Br=e=>{if(e.length===0)return{[zr]:{state:"partial",partialPath:[]}};try{const t=Ln.parse(e);if(typeof t!="object"||t===null)throw new Error("argsText is expected to be an object");return t[zr]={state:"complete",partialPath:[]},t}catch(t){try{const[r,n]=sc(e),i=Ln.parse(r);if(typeof i!="object"||i===null)throw new Error("argsText is expected to be an object");return i[zr]={state:"partial",partialPath:n},i}catch(r){return}}},Ta=(e,t,r)=>{if(typeof e!="object"||e===null)return t.state;if(t.state==="complete")return"complete";if(r.length===0)return t.state;const[n,...i]=r;if(!Object.prototype.hasOwnProperty.call(e,n))return"partial";const[a,...s]=t.partialPath;if(n!==a)return"complete";const o=e[n];return Ta(o,{state:"partial",partialPath:s},i)},zt=(e,t)=>{const r=oc(e);if(!r)throw new Error("unable to determine object state");return Ta(e,r,t.map(String))};function lc(){return Dr(this,null,function*(){const e=this.getReader();try{for(;;){const{done:t,value:r}=yield new Ae(e.read());if(t)break;yield r}}finally{e.releaseLock()}})}function Dn(e){var t,r;return(r=e[t=Symbol.asyncIterator])!=null||(e[t]=lc),e}var On={toResponse(e,t){var r;return new Response(On.toByteStream(e,t),{headers:(r=t.headers)!=null?r:{}})},fromResponse(e,t){return On.fromByteStream(e.body,t)},toByteStream(e,t){return e.pipeThrough(t)},fromByteStream(e,t){return e.pipeThrough(t)}},Fn=function(){let e,t;const r=new Promise((n,i)=>{e=n,t=i});if(!e||!t)throw new Error("Failed to create promise");return{promise:r,resolve:e,reject:t}},uc=()=>{const e=[];let t=!1,r,n;const i=s=>{s.promise||(s.promise=s.reader.read().then(({done:o,value:l})=>{s.promise=void 0,o?(e.splice(e.indexOf(s),1),t&&e.length===0&&r.close()):r.enqueue(l),n==null||n.resolve(),n=void 0}).catch(o=>{console.error(o),e.forEach(l=>{l.reader.cancel()}),e.length=0,r.error(o),n==null||n.reject(o),n=void 0}))};return{readable:new ReadableStream({start(s){r=s},pull(){return n=Fn(),e.forEach(s=>{i(s)}),n.promise},cancel(){e.forEach(s=>{s.reader.cancel()}),e.length=0}}),isSealed(){return t},seal(){t=!0,e.length===0&&r.close()},addStream(s){if(t)throw new Error("Cannot add streams after the run callback has settled.");const o={reader:s.getReader()};e.push(o),i(o)},enqueue(s){this.addStream(new ReadableStream({start(o){o.enqueue(s),o.close()}}))}}},Ca=class{constructor(e){T(this,"_controller");T(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())}},Ia=e=>new ReadableStream({start(t){var r;return(r=e.start)==null?void 0:r.call(e,new Ca(t))},pull(t){var r;return(r=e.pull)==null?void 0:r.call(e,new Ca(t))},cancel(t){var r;return(r=e.cancel)==null?void 0:r.call(e,t)}}),Ea=()=>{let e;return[Ia({start(r){e=r}}),e]},Aa=class{constructor(e){T(this,"_isClosed",!1);T(this,"_mergeTask");T(this,"_argsTextController");this._controller=e;const t=Ia({start:n=>{this._argsTextController=n}});let r=!1;this._mergeTask=t.pipeTo(new WritableStream({write:n=>{switch(n.type){case"text-delta":r=!0,this._controller.enqueue(n);break;case"part-finish":r||this._controller.enqueue({type:"text-delta",textDelta:"{}",path:[]}),this._controller.enqueue({type:"tool-call-args-text-finish",path:[]});break;default:throw new Error(`Unexpected chunk type: ${n.type}`)}}}))}get argsText(){return this._argsTextController}setResponse(e){return M(this,null,function*(){var t;this._argsTextController.close(),yield Promise.resolve(),this._controller.enqueue(I(m({type:"result",path:[]},e.artifact!==void 0?{artifact:e.artifact}:{}),{result:e.result,isError:(t=e.isError)!=null?t:!1}))})}close(){return M(this,null,function*(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),yield this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())})}},cc=e=>new ReadableStream({start(t){var r;return(r=e.start)==null?void 0:r.call(e,new Aa(t))},pull(t){var r;return(r=e.pull)==null?void 0:r.call(e,new Aa(t))},cancel(t){var r;return(r=e.cancel)==null?void 0:r.call(e,t)}}),dc=()=>{let e;return[cc({start(r){e=r}}),e]},Ma=class{constructor(){T(this,"value",-1)}up(){return++this.value}},hc=class extends TransformStream{constructor(e){super({transform(t,r){r.enqueue(I(m({},t),{path:[e,...t.path]}))}})}};(class extends TransformStream{constructor(e){super({transform(t,r){const{path:[n,...i]}=t;if(e!==n)throw new Error(`Path mismatch: expected ${e}, got ${n}`);r.enqueue(I(m({},t),{path:i}))}})}});var fc=class extends TransformStream{constructor(e){const t=new Ma,r=new Map;super({transform(n,i){n.type==="part-start"&&n.path.length===0&&r.set(t.up(),e.up());const[a,...s]=n.path;if(a===void 0){i.enqueue(n);return}const o=r.get(a);if(o===void 0)throw new Error("Path not found");i.enqueue(I(m({},n),{path:[o,...s]}))}})}},Pa=class extends TransformStream{constructor(e){super();const t=e(super.readable);Object.defineProperty(this,"readable",{value:t,writable:!1})}},Na=class extends TransformStream{constructor(){const e=[];super({transform(t,r){if(t.type==="part-start"){if(t.path.length!==0){r.error(new Error("Nested parts are not supported"));return}e.push(t.part),r.enqueue(t);return}if(t.type==="text-delta"||t.type==="result"||t.type==="part-finish"||t.type==="tool-call-args-text-finish"){if(t.path.length!==1){r.error(new Error(`${t.type} chunks must have a path of length 1`));return}const n=t.path[0];if(n<0||n>=e.length){r.error(new Error(`Invalid path index: ${n}`));return}const i=e[n];r.enqueue(I(m({},t),{meta:i}));return}r.enqueue(t)}})}},La=ka("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),pc=class $u{constructor(t){T(this,"_state");T(this,"_parentId");this._state=t||{merger:uc(),contentCounter:new Ma}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(t){this._state.closeSubscriber=t}_addPart(t,r){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:"part-start",part:t,path:[]}),this._state.merger.addStream(r.pipeThrough(new hc(this._state.contentCounter.value)))}merge(t){this._state.merger.addStream(t.pipeThrough(new fc(this._state.contentCounter)))}appendText(t){var r;((r=this._state.append)==null?void 0:r.kind)!=="text"&&(this._state.append={kind:"text",controller:this.addTextPart()}),this._state.append.controller.append(t)}appendReasoning(t){var r;((r=this._state.append)==null?void 0:r.kind)!=="reasoning"&&(this._state.append={kind:"reasoning",controller:this.addReasoningPart()}),this._state.append.controller.append(t)}addTextPart(){const[t,r]=Ea();return this._addPart({type:"text"},t),r}addReasoningPart(){const[t,r]=Ea();return this._addPart({type:"reasoning"},t),r}addToolCallPart(t){var o;const r=typeof t=="string"?{toolName:t}:t,n=r.toolName,i=(o=r.toolCallId)!=null?o:La(),[a,s]=dc();return this._addPart(m({type:"tool-call",toolName:n,toolCallId:i},this._parentId&&{parentId:this._parentId}),a),r.argsText!==void 0&&(s.argsText.append(r.argsText),s.argsText.close()),r.args!==void 0&&(s.argsText.append(JSON.stringify(r.args)),s.argsText.close()),r.response!==void 0&&s.setResponse(r.response),s}appendSource(t){this._addPart(m(m({},t),this._parentId&&{parentId:this._parentId}),new ReadableStream({start(r){r.enqueue({type:"part-finish",path:[]}),r.close()}}))}appendFile(t){this._addPart(t,new ReadableStream({start(r){r.enqueue({type:"part-finish",path:[]}),r.close()}}))}enqueue(t){this._state.merger.enqueue(t),t.type==="part-start"&&t.path.length===0&&this._state.contentCounter.up()}withParentId(t){const r=new $u(this._state);return r._parentId=t,r}close(){var t,r,n,i;(r=(t=this._state.append)==null?void 0:t.controller)==null||r.close(),this._state.merger.seal(),(i=(n=this._state).closeSubscriber)==null||i.call(n)}};function Da(e){const t=new pc;return M(null,null,function*(){try{yield e(t)}catch(n){throw t.__internal_isClosed||t.enqueue({type:"error",path:[],error:String(n)}),n}finally{t.__internal_isClosed||t.close()}}),t.__internal_getReadable()}function Oa(){const{resolve:e,promise:t}=Fn();let r;return[Da(i=>(r=i,r.__internal_subscribeToClose(e),t)),r]}var mc=class extends TransformStream{constructor(e,t,r){const[n,i]=Oa();let a;super({start(o){var l;return a=n.pipeTo(new WritableStream({write(u){o.enqueue(u)},abort(u){o.error(u)},close(){o.terminate()}})).catch(u=>{o.error(u)}),(l=e.start)==null?void 0:l.call(e,i)},transform(o){var l;return(l=e.transform)==null?void 0:l.call(e,o,i)},flush(){return M(this,null,function*(){var o;yield(o=e.flush)==null?void 0:o.call(e,i),i.close(),yield a})}},t,r)}},or=(e,t,r)=>{var f,h,g,x,b,w,E;const{role:n,id:i,createdAt:a,attachments:s,status:o,metadata:l}=e,u={id:i!=null?i:t,createdAt:a!=null?a:new Date},d=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content,c=z=>{var C=z,{image:_}=C,O=H(C,["image"]);return _.match(/^data:image\/(png|jpeg|jpg|gif|webp);base64,(.*)$/)?I(m({},O),{image:_}):(console.warn("Invalid image data format detected"),null)};if(n!=="user"&&(s!=null&&s.length))throw new Error("attachments are only supported for user messages");if(n!=="assistant"&&o)throw new Error("status is only supported for assistant messages");if(n!=="assistant"&&(l!=null&&l.steps))throw new Error("metadata.steps is only supported for assistant messages");switch(n){case"assistant":return I(m({},u),{role:n,content:d.map(_=>{var C,U,V,R,S;const O=_.type;switch(O){case"text":case"reasoning":return _.text.trim().length===0?null:_;case"file":case"source":return _;case"image":return c(_);case"data":return _;case"tool-call":{const z=_,{parentId:D,messages:N}=z,K=H(z,["parentId","messages"]),B=m(m(I(m({},K),{toolCallId:(C=_.toolCallId)!=null?C:`tool-${_t()}`}),D!==void 0&&{parentId:D}),N!==void 0&&{messages:N});return _.args?I(m({},B),{args:_.args,argsText:(U=_.argsText)!=null?U:JSON.stringify(_.args)}):I(m({},B),{args:(R=Br((V=_.argsText)!=null?V:""))!=null?R:{},argsText:(S=_.argsText)!=null?S:""})}default:{const D=O;throw new Error(`Unsupported assistant message part type: ${D}`)}}}).filter(_=>!!_),status:o!=null?o:r,metadata:m({unstable_state:(f=l==null?void 0:l.unstable_state)!=null?f:null,unstable_annotations:(h=l==null?void 0:l.unstable_annotations)!=null?h:[],unstable_data:(g=l==null?void 0:l.unstable_data)!=null?g:[],custom:(x=l==null?void 0:l.custom)!=null?x:{},steps:(b=l==null?void 0:l.steps)!=null?b:[]},(l==null?void 0:l.submittedFeedback)&&{submittedFeedback:l.submittedFeedback})});case"user":return I(m({},u),{role:n,content:d.map(_=>{const O=_.type;switch(O){case"text":case"image":case"audio":case"file":return _;default:{const z=O;throw new Error(`Unsupported user message part type: ${z}`)}}}),attachments:s!=null?s:[],metadata:{custom:(w=l==null?void 0:l.custom)!=null?w:{}}});case"system":if(d.length!==1||d[0].type!=="text")throw new Error("System messages must have exactly one text message part.");return I(m({},u),{role:n,content:d,metadata:{custom:(E=l==null?void 0:l.custom)!=null?E:{}}});default:{const _=n;throw new Error(`Unknown message role: ${_}`)}}},zn={fromArray:e=>{const t=e.map(r=>or(r,_t(),Sa(!1,!1,!1,!1,void 0)));return{messages:t.map((r,n)=>({parentId:n>0?t[n-1].id:null,message:r}))}}},Rr=e=>e.next?Rr(e.next):"current"in e?e:null,gc=class{constructor(e){T(this,"_value",null);this.func=e}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},Fa=class{constructor(){T(this,"messages",new Map);T(this,"head",null);T(this,"root",{children:[],next:null});T(this,"_messages",new gc(()=>{var t,r;const e=new Array(((r=(t=this.head)==null?void 0:t.level)!=null?r:-1)+1);for(let n=this.head;n;n=n.prev)e[n.level]=n.current;return e}))}updateLevels(e,t){e.level=t;for(const r of e.children){const n=this.messages.get(r);n&&this.updateLevels(n,t+1)}}performOp(e,t,r){var a;const n=(a=t.prev)!=null?a:this.root,i=e!=null?e:this.root;if(!(r==="relink"&&n===i)){if(r!=="link"&&(n.children=n.children.filter(s=>s!==t.current.id),n.next===t)){const s=n.children.at(-1),o=s?this.messages.get(s):null;if(o===void 0)throw new Error("MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.");n.next=o}if(r!=="cut"){for(let o=e;o;o=o.prev)if(o.current.id===t.current.id)throw new Error("MessageRepository(performOp/link): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.");i.children=[...i.children,t.current.id],(Rr(t)===this.head||i.next===null)&&(i.next=t),t.prev=e;const s=e?e.level+1:0;this.updateLevels(t,s)}}}get headId(){var e,t;return(t=(e=this.head)==null?void 0:e.current.id)!=null?t:null}getMessages(e){var n;if(e===void 0||e===((n=this.head)==null?void 0:n.current.id))return this._messages.value;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(getMessages): Head message not found. This is likely an internal bug in assistant-ui.");const r=new Array(t.level+1);for(let i=t;i;i=i.prev)r[i.level]=i.current;return r}addOrUpdateMessage(e,t){const r=this.messages.get(t.id),n=e?this.messages.get(e):null;if(n===void 0)throw new Error("MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.");if(r){r.current=t,this.performOp(n,r,"relink"),this._messages.dirty();return}const i={prev:n,current:t,next:null,children:[],level:n?n.level+1:0};this.messages.set(t.id,i),this.performOp(n,i,"link"),this.head===n&&(this.head=i),this._messages.dirty()}getMessage(e){var r,n;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.");return{parentId:(n=(r=t.prev)==null?void 0:r.current.id)!=null?n:null,message:t.current,index:t.level}}appendOptimisticMessage(e,t){let r;do r=Zu();while(this.messages.has(r));return this.addOrUpdateMessage(e,or(t,r,{type:"running"})),r}deleteMessage(e,t){const r=this.messages.get(e);if(!r)throw new Error("MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.");const n=t===void 0?r.prev:t===null?null:this.messages.get(t);if(n===void 0)throw new Error("MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.");for(const i of r.children){const a=this.messages.get(i);if(!a)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(n,a,"relink")}this.performOp(null,r,"cut"),this.messages.delete(e),this.head===r&&(this.head=Rr(n!=null?n:this.root)),this._messages.dirty()}getBranches(e){var n;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.");const{children:r}=(n=t.prev)!=null?n:this.root;return r}switchToBranch(e){var n;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.");const r=(n=t.prev)!=null?n:this.root;r.next=t,this.head=Rr(t),this._messages.dirty()}resetHead(e){if(e===null){this.clear();return}const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.");if(t.children.length>0){const r=n=>{for(const i of n.children){const a=this.messages.get(i);a&&(r(a),this.messages.delete(i))}};r(t),t.children=[],t.next=null}this.head=t;for(let r=t;r;r=r.prev)r.prev&&(r.prev.next=r);this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){var t,r,n,i;const e=[];for(const[,a]of this.messages)e.push({message:a.current,parentId:(r=(t=a.prev)==null?void 0:t.current.id)!=null?r:null});return{headId:(i=(n=this.head)==null?void 0:n.current.id)!=null?i:null,messages:e}}import({headId:e,messages:t}){var r,n;for(const{message:i,parentId:a}of t)this.addOrUpdateMessage(a,i);this.resetHead((n=e!=null?e:(r=t.at(-1))==null?void 0:r.message.id)!=null?n:null)}},jr=class{constructor(){T(this,"_subscriptions",new Set);T(this,"_connection")}get isConnected(){return!!this._connection}notifySubscribers(){for(const e of this._subscriptions)e()}_updateConnection(){var e;if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else(e=this._connection)==null||e.call(this),this._connection=void 0}subscribe(e){return this._subscriptions.add(e),this._updateConnection(),()=>{this._subscriptions.delete(e),this._updateConnection()}}},Ge=Symbol("skip-update"),Bn=class extends jr{constructor(t){super();T(this,"_previousStateDirty",!0);T(this,"_previousState");T(this,"getState",()=>{if(!this.isConnected||this._previousStateDirty){const t=this.binding.getState();t!==Ge&&(this._previousState=t),this._previousStateDirty=!1}if(this._previousState===void 0)throw new Error("Entry not available in the store");return this._previousState});this.binding=t}get path(){return this.binding.path}_connect(){const t=()=>{this._previousStateDirty=!0,this.notifySubscribers()};return this.binding.subscribe(t)}},$r=class{constructor(e,t){this._core=e,this._threadListBinding=t,this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.switchTo=this.switchTo.bind(this),this.rename=this.rename.bind(this),this.archive=this.archive.bind(this),this.unarchive=this.unarchive.bind(this),this.delete=this.delete.bind(this),this.initialize=this.initialize.bind(this),this.generateTitle=this.generateTitle.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getState=this.getState.bind(this),this.detach=this.detach.bind(this)}getState(){return this._core.getState()}switchTo(){const e=this._core.getState();return this._threadListBinding.switchToThread(e.id)}rename(e){const t=this._core.getState();return this._threadListBinding.rename(t.id,e)}archive(){const e=this._core.getState();return this._threadListBinding.archive(e.id)}unarchive(){const e=this._core.getState();return this._threadListBinding.unarchive(e.id)}delete(){const e=this._core.getState();return this._threadListBinding.delete(e.id)}initialize(){const e=this._core.getState();return this._threadListBinding.initialize(e.id)}generateTitle(){const e=this._core.getState();return this._threadListBinding.generateTitle(e.id)}unstable_on(e,t){let r=this._core.getState().isMain,n=this._core.getState().id;return this.subscribe(()=>{const i=this._core.getState(),a=i.isMain,s=i.id;r===a&&n===s||(r=a,n=s,!(e==="switched-to"&&!a)&&(e==="switched-away"&&a||t()))})}subscribe(e){return this._core.subscribe(e)}detach(){const e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}};function yc(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0)return!1;for(const r of Object.keys(e)){const n=e[r],i=t[r];if(!Object.is(n,i))return!1}return!0}var Xe=class extends jr{constructor(t){super();T(this,"_previousState");T(this,"getState",()=>(this.isConnected||this._syncState(),this._previousState));this.binding=t;const r=t.getState();if(r===Ge)throw new Error("Entry not available in the store");this._previousState=r}get path(){return this.binding.path}_syncState(){const t=this.binding.getState();return t===Ge||yc(t,this._previousState)?!1:(this._previousState=t,!0)}_connect(){const t=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(t)}},Ur=Symbol("innerMessage"),Hr=e=>e.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
3
|
+
${n.system}`:r.system=n.system),n.tools)for(const[s,i]of Object.entries(n.tools)){const o=(a=r.tools)==null?void 0:a[s];if(o&&o!==i)throw new Error(`You tried to define a tool with the name ${s}, but it already exists.`);r.tools||(r.tools={}),r.tools[s]=i}return n.config&&(r.config=m(m({},r.config),n.config)),n.callSettings&&(r.callSettings=m(m({},r.callSettings),n.callSettings)),r},{}),Fn=class{constructor(){T(this,"_providers",new Set);T(this,"_subscribers",new Set)}getModelContext(){return ec(this._providers)}registerModelContextProvider(e){var r;this._providers.add(e);const t=(r=e.subscribe)==null?void 0:r.call(e,()=>{this.notifySubscribers()});return this.notifySubscribers(),()=>{this._providers.delete(e),t==null||t(),this.notifySubscribers()}}notifySubscribers(){for(const e of this._subscribers)e()}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}},zn=class{constructor(){T(this,"_contextProvider",new Fn)}registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}},ir=class{constructor(){T(this,"_subscribers",new Set)}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}waitForUpdate(){return new Promise(e=>{const t=this.subscribe(()=>{t(),e()})})}_notifySubscribers(){const e=[];for(const t of this._subscribers)try{t()}catch(r){e.push(r)}if(e.length>0)throw e.length===1?e[0]:new AggregateError(e)}},tc=e=>e.status.type==="complete",Ts=class extends ir{constructor(){super(...arguments);T(this,"isEditing",!0);T(this,"_attachments",[]);T(this,"_text","");T(this,"_role","user");T(this,"_runConfig",{});T(this,"_eventSubscribers",new Map)}get attachmentAccept(){var t,r;return(r=(t=this.getAttachmentAdapter())==null?void 0:t.accept)!=null?r:"*"}get attachments(){return this._attachments}setAttachments(t){this._attachments=t,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}get text(){return this._text}get role(){return this._role}get runConfig(){return this._runConfig}setText(t){this._text!==t&&(this._text=t,this._notifySubscribers())}setRole(t){this._role!==t&&(this._role=t,this._notifySubscribers())}setRunConfig(t){this._runConfig!==t&&(this._runConfig=t,this._notifySubscribers())}_emptyTextAndAttachments(){this._attachments=[],this._text="",this._notifySubscribers()}_onClearAttachments(){return M(this,null,function*(){const t=this.getAttachmentAdapter();t&&(yield Promise.all(this._attachments.map(r=>t.remove(r))))})}reset(){return M(this,null,function*(){if(this._attachments.length===0&&this._text===""&&this._role==="user"&&Object.keys(this._runConfig).length===0)return;this._role="user",this._runConfig={};const t=this._onClearAttachments();this._emptyTextAndAttachments(),yield t})}clearAttachments(){return M(this,null,function*(){const t=this._onClearAttachments();this.setAttachments([]),yield t})}send(){return M(this,null,function*(){const t=this.getAttachmentAdapter(),r=t&&this.attachments.length>0?Promise.all(this.attachments.map(s=>M(this,null,function*(){return tc(s)?s:yield t.send(s)}))):[],n=this.text;this._emptyTextAndAttachments();const a={createdAt:new Date,role:this.role,content:n?[{type:"text",text:n}]:[],attachments:yield r,runConfig:this.runConfig,metadata:{custom:{}}};this.handleSend(a),this._notifyEventSubscribers("send")})}cancel(){this.handleCancel()}addAttachment(t){return M(this,null,function*(){const r=this.getAttachmentAdapter();if(!r)throw new Error("Attachments are not supported");const n=u=>{const d=this._attachments.findIndex(c=>c.id===u.id);d!==-1?this._attachments=[...this._attachments.slice(0,d),u,...this._attachments.slice(d+1)]:this._attachments=[...this._attachments,u],this._notifySubscribers()},a=r.add({file:t});if(Symbol.asyncIterator in a)try{for(var s=Ft(a),i,o,l;i=!(o=yield s.next()).done;i=!1){const u=o.value;n(u)}}catch(o){l=[o]}finally{try{i&&(o=s.return)&&(yield o.call(s))}finally{if(l)throw l[0]}}else n(yield a);this._notifyEventSubscribers("attachment-add"),this._notifySubscribers()})}removeAttachment(t){return M(this,null,function*(){const r=this.getAttachmentAdapter();if(!r)throw new Error("Attachments are not supported");const n=this._attachments.findIndex(s=>s.id===t);if(n===-1)throw new Error("Attachment not found");const a=this._attachments[n];yield r.remove(a),this._attachments=[...this._attachments.slice(0,n),...this._attachments.slice(n+1)],this._notifySubscribers()})}_notifyEventSubscribers(t){const r=this._eventSubscribers.get(t);if(r)for(const n of r)n()}unstable_on(t,r){const n=this._eventSubscribers.get(t);return n?n.add(r):this._eventSubscribers.set(t,new Set([r])),()=>{const a=this._eventSubscribers.get(t);a&&a.delete(r)}}},Cs=class extends Ts{constructor(t){super();T(this,"_canCancel",!1);this.runtime=t,this.connect()}get canCancel(){return this._canCancel}get attachments(){return super.attachments}getAttachmentAdapter(){var t;return(t=this.runtime.adapters)==null?void 0:t.attachments}connect(){return this.runtime.subscribe(()=>{this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,this._notifySubscribers())})}handleSend(t){return M(this,null,function*(){var r,n;this.runtime.append(I(m({},t),{parentId:(n=(r=this.runtime.messages.at(-1))==null?void 0:r.id)!=null?n:null,sourceId:null}))})}handleCancel(){return M(this,null,function*(){this.runtime.cancelRun()})}};let Is=(e,t=21)=>(r=t)=>{let n="",a=r|0;for(;a--;)n+=e[Math.random()*e.length|0];return n};var _t=Is("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),rc="__optimistic__",nc=()=>`${rc}${_t()}`,or=Symbol("autoStatus"),ac=Object.freeze(Object.assign({type:"running"},{[or]:!0})),sc=Object.freeze(Object.assign({type:"complete",reason:"unknown"},{[or]:!0})),ic=Object.freeze(Object.assign({type:"requires-action",reason:"tool-calls"},{[or]:!0})),oc=Object.freeze(Object.assign({type:"requires-action",reason:"interrupt"},{[or]:!0})),Es=(e,t,r,n,a)=>e&&a?Object.assign({type:"incomplete",reason:"error",error:a},{[or]:!0}):e&&t?ac:r?oc:n?ic:sc;function Br(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Tt={exports:{}},As;function lc(){if(As)return Tt.exports;As=1;const e=typeof Buffer!="undefined",t=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,r=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function n(o,l,u){u==null&&l!==null&&typeof l=="object"&&(u=l,l=void 0),e&&Buffer.isBuffer(o)&&(o=o.toString()),o&&o.charCodeAt(0)===65279&&(o=o.slice(1));const d=JSON.parse(o,l);if(d===null||typeof d!="object")return d;const c=u&&u.protoAction||"error",f=u&&u.constructorAction||"error";if(c==="ignore"&&f==="ignore")return d;if(c!=="ignore"&&f!=="ignore"){if(t.test(o)===!1&&r.test(o)===!1)return d}else if(c!=="ignore"&&f==="ignore"){if(t.test(o)===!1)return d}else if(r.test(o)===!1)return d;return a(d,{protoAction:c,constructorAction:f,safe:u&&u.safe})}function a(o,{protoAction:l="error",constructorAction:u="error",safe:d}={}){let c=[o];for(;c.length;){const f=c;c=[];for(const h of f){if(l!=="ignore"&&Object.prototype.hasOwnProperty.call(h,"__proto__")){if(d===!0)return null;if(l==="error")throw new SyntaxError("Object contains forbidden prototype property");delete h.__proto__}if(u!=="ignore"&&Object.prototype.hasOwnProperty.call(h,"constructor")&&h.constructor!==null&&typeof h.constructor=="object"&&Object.prototype.hasOwnProperty.call(h.constructor,"prototype")){if(d===!0)return null;if(u==="error")throw new SyntaxError("Object contains forbidden prototype property");delete h.constructor}for(const g in h){const w=h[g];w&&typeof w=="object"&&c.push(w)}}}return o}function s(o,l,u){const{stackTraceLimit:d}=Error;Error.stackTraceLimit=0;try{return n(o,l,u)}finally{Error.stackTraceLimit=d}}function i(o,l){const{stackTraceLimit:u}=Error;Error.stackTraceLimit=0;try{return n(o,l,{safe:!0})}catch(d){return}finally{Error.stackTraceLimit=u}}return Tt.exports=s,Tt.exports.default=s,Tt.exports.parse=s,Tt.exports.safeParse=i,Tt.exports.scan=a,Tt.exports}var uc=lc();const Bn=Br(uc);function cc(e){const t=["ROOT"];let r=-1,n=null;const a=[];let s;function i(){s!==void 0&&(a.push(JSON.parse(`"${s}"`)),s=void 0)}function o(c,f,h){switch(c){case'"':{r=f,t.pop(),t.push(h),t.push("INSIDE_STRING"),i();break}case"f":case"t":case"n":{r=f,n=f,t.pop(),t.push(h),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(h),t.push("INSIDE_NUMBER"),i();break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=f,t.pop(),t.push(h),t.push("INSIDE_NUMBER"),i();break}case"{":{r=f,t.pop(),t.push(h),t.push("INSIDE_OBJECT_START"),i();break}case"[":{r=f,t.pop(),t.push(h),t.push("INSIDE_ARRAY_START"),i();break}}}function l(c,f){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=f,t.pop(),s=a.pop();break}}}function u(c,f){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),s=(Number(s)+1).toString();break}case"]":{r=f,t.pop(),s=a.pop();break}}}for(let c=0;c<e.length;c++){const f=e[c];switch(t[t.length-1]){case"ROOT":o(f,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),s="";break}case"}":{r=c,t.pop(),s=a.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),s="";break}}break}case"INSIDE_OBJECT_KEY":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}case"\\":{t.push("INSIDE_STRING_ESCAPE"),s+=f;break}default:{s+=f;break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(f){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(f,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{l(f,c);break}case"INSIDE_STRING":{switch(f){case'"':{t.pop(),r=c,s=a.pop();break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=c}break}case"INSIDE_ARRAY_START":{switch(f){case"]":{r=c,t.pop(),s=a.pop();break}default:{r=c,s="0",o(f,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(f){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),s=(Number(s)+1).toString();break}case"]":{r=c,t.pop(),s=a.pop();break}default:{r=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(f,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),t[t.length-1]==="INSIDE_STRING"?r=c:t[t.length-1]==="INSIDE_OBJECT_KEY"&&(s+=f);break}case"INSIDE_NUMBER":{switch(f){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),s=a.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(f,c);break}case"}":{t.pop(),s=a.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(f,c);break}case"]":{t.pop(),s=a.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,c);break}default:{t.pop(),s=a.pop();break}}break}case"INSIDE_LITERAL":{const g=e.substring(n,c+1);!"false".startsWith(g)&&!"true".startsWith(g)&&!"null".startsWith(g)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?l(f,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,c)):r=c;break}}}let d=e.slice(0,r+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){case"INSIDE_STRING":{d+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{d+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{d+="]";break}case"INSIDE_LITERAL":{const h=e.substring(n,e.length);"true".startsWith(h)?d+="true".slice(h.length):"false".startsWith(h)?d+="false".slice(h.length):"null".startsWith(h)&&(d+="null".slice(h.length))}}return[d,a]}var Rr=Symbol("aui.parse-partial-json-object.meta"),dc=e=>e==null?void 0:e[Rr],jr=e=>{if(e.length===0)return{[Rr]:{state:"partial",partialPath:[]}};try{const t=Bn.parse(e);if(typeof t!="object"||t===null)throw new Error("argsText is expected to be an object");return t[Rr]={state:"complete",partialPath:[]},t}catch(t){try{const[r,n]=cc(e),a=Bn.parse(r);if(typeof a!="object"||a===null)throw new Error("argsText is expected to be an object");return a[Rr]={state:"partial",partialPath:n},a}catch(r){return}}},Ms=(e,t,r)=>{if(typeof e!="object"||e===null)return t.state;if(t.state==="complete")return"complete";if(r.length===0)return t.state;const[n,...a]=r;if(!Object.prototype.hasOwnProperty.call(e,n))return"partial";const[s,...i]=t.partialPath;if(n!==s)return"complete";const o=e[n];return Ms(o,{state:"partial",partialPath:i},a)},zt=(e,t)=>{const r=dc(e);if(!r)throw new Error("unable to determine object state");return Ms(e,r,t.map(String))};function hc(){return Or(this,null,function*(){const e=this.getReader();try{for(;;){const{done:t,value:r}=yield new Ae(e.read());if(t)break;yield r}}finally{e.releaseLock()}})}function Rn(e){var t,r;return(r=e[t=Symbol.asyncIterator])!=null||(e[t]=hc),e}var jn={toResponse(e,t){var r;return new Response(jn.toByteStream(e,t),{headers:(r=t.headers)!=null?r:{}})},fromResponse(e,t){return jn.fromByteStream(e.body,t)},toByteStream(e,t){return e.pipeThrough(t)},fromByteStream(e,t){return e.pipeThrough(t)}},$n=function(){let e,t;const r=new Promise((n,a)=>{e=n,t=a});if(!e||!t)throw new Error("Failed to create promise");return{promise:r,resolve:e,reject:t}},fc=()=>{const e=[];let t=!1,r,n;const a=i=>{i.promise||(i.promise=i.reader.read().then(({done:o,value:l})=>{i.promise=void 0,o?(e.splice(e.indexOf(i),1),t&&e.length===0&&r.close()):r.enqueue(l),n==null||n.resolve(),n=void 0}).catch(o=>{console.error(o),e.forEach(l=>{l.reader.cancel()}),e.length=0,r.error(o),n==null||n.reject(o),n=void 0}))};return{readable:new ReadableStream({start(i){r=i},pull(){return n=$n(),e.forEach(i=>{a(i)}),n.promise},cancel(){e.forEach(i=>{i.reader.cancel()}),e.length=0}}),isSealed(){return t},seal(){t=!0,e.length===0&&r.close()},addStream(i){if(t)throw new Error("Cannot add streams after the run callback has settled.");const o={reader:i.getReader()};e.push(o),a(o)},enqueue(i){this.addStream(new ReadableStream({start(o){o.enqueue(i),o.close()}}))}}},Ps=class{constructor(e){T(this,"_controller");T(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())}},Ns=e=>new ReadableStream({start(t){var r;return(r=e.start)==null?void 0:r.call(e,new Ps(t))},pull(t){var r;return(r=e.pull)==null?void 0:r.call(e,new Ps(t))},cancel(t){var r;return(r=e.cancel)==null?void 0:r.call(e,t)}}),Ls=()=>{let e;return[Ns({start(r){e=r}}),e]},Ds=class{constructor(e){T(this,"_isClosed",!1);T(this,"_mergeTask");T(this,"_argsTextController");this._controller=e;const t=Ns({start:n=>{this._argsTextController=n}});let r=!1;this._mergeTask=t.pipeTo(new WritableStream({write:n=>{switch(n.type){case"text-delta":r=!0,this._controller.enqueue(n);break;case"part-finish":r||this._controller.enqueue({type:"text-delta",textDelta:"{}",path:[]}),this._controller.enqueue({type:"tool-call-args-text-finish",path:[]});break;default:throw new Error(`Unexpected chunk type: ${n.type}`)}}}))}get argsText(){return this._argsTextController}setResponse(e){return M(this,null,function*(){var t;this._argsTextController.close(),yield Promise.resolve(),this._controller.enqueue(I(m({type:"result",path:[]},e.artifact!==void 0?{artifact:e.artifact}:{}),{result:e.result,isError:(t=e.isError)!=null?t:!1}))})}close(){return M(this,null,function*(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),yield this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())})}},pc=e=>new ReadableStream({start(t){var r;return(r=e.start)==null?void 0:r.call(e,new Ds(t))},pull(t){var r;return(r=e.pull)==null?void 0:r.call(e,new Ds(t))},cancel(t){var r;return(r=e.cancel)==null?void 0:r.call(e,t)}}),mc=()=>{let e;return[pc({start(r){e=r}}),e]},Os=class{constructor(){T(this,"value",-1)}up(){return++this.value}},gc=class extends TransformStream{constructor(e){super({transform(t,r){r.enqueue(I(m({},t),{path:[e,...t.path]}))}})}};(class extends TransformStream{constructor(e){super({transform(t,r){const{path:[n,...a]}=t;if(e!==n)throw new Error(`Path mismatch: expected ${e}, got ${n}`);r.enqueue(I(m({},t),{path:a}))}})}});var yc=class extends TransformStream{constructor(e){const t=new Os,r=new Map;super({transform(n,a){n.type==="part-start"&&n.path.length===0&&r.set(t.up(),e.up());const[s,...i]=n.path;if(s===void 0){a.enqueue(n);return}const o=r.get(s);if(o===void 0)throw new Error("Path not found");a.enqueue(I(m({},n),{path:[o,...i]}))}})}},Fs=class extends TransformStream{constructor(e){super();const t=e(super.readable);Object.defineProperty(this,"readable",{value:t,writable:!1})}},zs=class extends TransformStream{constructor(){const e=[];super({transform(t,r){if(t.type==="part-start"){if(t.path.length!==0){r.error(new Error("Nested parts are not supported"));return}e.push(t.part),r.enqueue(t);return}if(t.type==="text-delta"||t.type==="result"||t.type==="part-finish"||t.type==="tool-call-args-text-finish"){if(t.path.length!==1){r.error(new Error(`${t.type} chunks must have a path of length 1`));return}const n=t.path[0];if(n<0||n>=e.length){r.error(new Error(`Invalid path index: ${n}`));return}const a=e[n];r.enqueue(I(m({},t),{meta:a}));return}r.enqueue(t)}})}},Bs=Is("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),bc=class Vu{constructor(t){T(this,"_state");T(this,"_parentId");this._state=t||{merger:fc(),contentCounter:new Os}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(t){this._state.closeSubscriber=t}_addPart(t,r){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:"part-start",part:t,path:[]}),this._state.merger.addStream(r.pipeThrough(new gc(this._state.contentCounter.value)))}merge(t){this._state.merger.addStream(t.pipeThrough(new yc(this._state.contentCounter)))}appendText(t){var r;((r=this._state.append)==null?void 0:r.kind)!=="text"&&(this._state.append={kind:"text",controller:this.addTextPart()}),this._state.append.controller.append(t)}appendReasoning(t){var r;((r=this._state.append)==null?void 0:r.kind)!=="reasoning"&&(this._state.append={kind:"reasoning",controller:this.addReasoningPart()}),this._state.append.controller.append(t)}addTextPart(){const[t,r]=Ls();return this._addPart({type:"text"},t),r}addReasoningPart(){const[t,r]=Ls();return this._addPart({type:"reasoning"},t),r}addToolCallPart(t){var o;const r=typeof t=="string"?{toolName:t}:t,n=r.toolName,a=(o=r.toolCallId)!=null?o:Bs(),[s,i]=mc();return this._addPart(m({type:"tool-call",toolName:n,toolCallId:a},this._parentId&&{parentId:this._parentId}),s),r.argsText!==void 0&&(i.argsText.append(r.argsText),i.argsText.close()),r.args!==void 0&&(i.argsText.append(JSON.stringify(r.args)),i.argsText.close()),r.response!==void 0&&i.setResponse(r.response),i}appendSource(t){this._addPart(m(m({},t),this._parentId&&{parentId:this._parentId}),new ReadableStream({start(r){r.enqueue({type:"part-finish",path:[]}),r.close()}}))}appendFile(t){this._addPart(t,new ReadableStream({start(r){r.enqueue({type:"part-finish",path:[]}),r.close()}}))}enqueue(t){this._state.merger.enqueue(t),t.type==="part-start"&&t.path.length===0&&this._state.contentCounter.up()}withParentId(t){const r=new Vu(this._state);return r._parentId=t,r}close(){var t,r,n,a;(r=(t=this._state.append)==null?void 0:t.controller)==null||r.close(),this._state.merger.seal(),(a=(n=this._state).closeSubscriber)==null||a.call(n)}};function Rs(e){const t=new bc;return M(null,null,function*(){try{yield e(t)}catch(n){throw t.__internal_isClosed||t.enqueue({type:"error",path:[],error:String(n)}),n}finally{t.__internal_isClosed||t.close()}}),t.__internal_getReadable()}function js(){const{resolve:e,promise:t}=$n();let r;return[Rs(a=>(r=a,r.__internal_subscribeToClose(e),t)),r]}var xc=class extends TransformStream{constructor(e,t,r){const[n,a]=js();let s;super({start(o){var l;return s=n.pipeTo(new WritableStream({write(u){o.enqueue(u)},abort(u){o.error(u)},close(){o.terminate()}})).catch(u=>{o.error(u)}),(l=e.start)==null?void 0:l.call(e,a)},transform(o){var l;return(l=e.transform)==null?void 0:l.call(e,o,a)},flush(){return M(this,null,function*(){var o;yield(o=e.flush)==null?void 0:o.call(e,a),a.close(),yield s})}},t,r)}},lr=(e,t,r)=>{var f,h,g,w,x,y,E;const{role:n,id:a,createdAt:s,attachments:i,status:o,metadata:l}=e,u={id:a!=null?a:t,createdAt:s!=null?s:new Date},d=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content,c=z=>{var C=z,{image:_}=C,O=H(C,["image"]);return _.match(/^data:image\/(png|jpeg|jpg|gif|webp);base64,(.*)$/)?I(m({},O),{image:_}):(console.warn("Invalid image data format detected"),null)};if(n!=="user"&&(i!=null&&i.length))throw new Error("attachments are only supported for user messages");if(n!=="assistant"&&o)throw new Error("status is only supported for assistant messages");if(n!=="assistant"&&(l!=null&&l.steps))throw new Error("metadata.steps is only supported for assistant messages");switch(n){case"assistant":return I(m({},u),{role:n,content:d.map(_=>{var C,U,V,R,S;const O=_.type;switch(O){case"text":case"reasoning":return _.text.trim().length===0?null:_;case"file":case"source":return _;case"image":return c(_);case"data":return _;case"tool-call":{const z=_,{parentId:D,messages:N}=z,K=H(z,["parentId","messages"]),B=m(m(I(m({},K),{toolCallId:(C=_.toolCallId)!=null?C:`tool-${_t()}`}),D!==void 0&&{parentId:D}),N!==void 0&&{messages:N});return _.args?I(m({},B),{args:_.args,argsText:(U=_.argsText)!=null?U:JSON.stringify(_.args)}):I(m({},B),{args:(R=jr((V=_.argsText)!=null?V:""))!=null?R:{},argsText:(S=_.argsText)!=null?S:""})}default:{const D=O;throw new Error(`Unsupported assistant message part type: ${D}`)}}}).filter(_=>!!_),status:o!=null?o:r,metadata:m({unstable_state:(f=l==null?void 0:l.unstable_state)!=null?f:null,unstable_annotations:(h=l==null?void 0:l.unstable_annotations)!=null?h:[],unstable_data:(g=l==null?void 0:l.unstable_data)!=null?g:[],custom:(w=l==null?void 0:l.custom)!=null?w:{},steps:(x=l==null?void 0:l.steps)!=null?x:[]},(l==null?void 0:l.submittedFeedback)&&{submittedFeedback:l.submittedFeedback})});case"user":return I(m({},u),{role:n,content:d.map(_=>{const O=_.type;switch(O){case"text":case"image":case"audio":case"file":return _;default:{const z=O;throw new Error(`Unsupported user message part type: ${z}`)}}}),attachments:i!=null?i:[],metadata:{custom:(y=l==null?void 0:l.custom)!=null?y:{}}});case"system":if(d.length!==1||d[0].type!=="text")throw new Error("System messages must have exactly one text message part.");return I(m({},u),{role:n,content:d,metadata:{custom:(E=l==null?void 0:l.custom)!=null?E:{}}});default:{const _=n;throw new Error(`Unknown message role: ${_}`)}}},Un={fromArray:e=>{const t=e.map(r=>lr(r,_t(),Es(!1,!1,!1,!1,void 0)));return{messages:t.map((r,n)=>({parentId:n>0?t[n-1].id:null,message:r}))}}},$r=e=>e.next?$r(e.next):"current"in e?e:null,wc=class{constructor(e){T(this,"_value",null);this.func=e}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},$s=class{constructor(){T(this,"messages",new Map);T(this,"head",null);T(this,"root",{children:[],next:null});T(this,"_messages",new wc(()=>{var t,r;const e=new Array(((r=(t=this.head)==null?void 0:t.level)!=null?r:-1)+1);for(let n=this.head;n;n=n.prev)e[n.level]=n.current;return e}))}updateLevels(e,t){e.level=t;for(const r of e.children){const n=this.messages.get(r);n&&this.updateLevels(n,t+1)}}performOp(e,t,r){var s;const n=(s=t.prev)!=null?s:this.root,a=e!=null?e:this.root;if(!(r==="relink"&&n===a)){if(r!=="link"&&(n.children=n.children.filter(i=>i!==t.current.id),n.next===t)){const i=n.children.at(-1),o=i?this.messages.get(i):null;if(o===void 0)throw new Error("MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.");n.next=o}if(r!=="cut"){for(let o=e;o;o=o.prev)if(o.current.id===t.current.id)throw new Error("MessageRepository(performOp/link): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.");a.children=[...a.children,t.current.id],($r(t)===this.head||a.next===null)&&(a.next=t),t.prev=e;const i=e?e.level+1:0;this.updateLevels(t,i)}}}get headId(){var e,t;return(t=(e=this.head)==null?void 0:e.current.id)!=null?t:null}getMessages(e){var n;if(e===void 0||e===((n=this.head)==null?void 0:n.current.id))return this._messages.value;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(getMessages): Head message not found. This is likely an internal bug in assistant-ui.");const r=new Array(t.level+1);for(let a=t;a;a=a.prev)r[a.level]=a.current;return r}addOrUpdateMessage(e,t){const r=this.messages.get(t.id),n=e?this.messages.get(e):null;if(n===void 0)throw new Error("MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.");if(r){r.current=t,this.performOp(n,r,"relink"),this._messages.dirty();return}const a={prev:n,current:t,next:null,children:[],level:n?n.level+1:0};this.messages.set(t.id,a),this.performOp(n,a,"link"),this.head===n&&(this.head=a),this._messages.dirty()}getMessage(e){var r,n;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.");return{parentId:(n=(r=t.prev)==null?void 0:r.current.id)!=null?n:null,message:t.current,index:t.level}}appendOptimisticMessage(e,t){let r;do r=nc();while(this.messages.has(r));return this.addOrUpdateMessage(e,lr(t,r,{type:"running"})),r}deleteMessage(e,t){const r=this.messages.get(e);if(!r)throw new Error("MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.");const n=t===void 0?r.prev:t===null?null:this.messages.get(t);if(n===void 0)throw new Error("MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.");for(const a of r.children){const s=this.messages.get(a);if(!s)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(n,s,"relink")}this.performOp(null,r,"cut"),this.messages.delete(e),this.head===r&&(this.head=$r(n!=null?n:this.root)),this._messages.dirty()}getBranches(e){var n;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.");const{children:r}=(n=t.prev)!=null?n:this.root;return r}switchToBranch(e){var n;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.");const r=(n=t.prev)!=null?n:this.root;r.next=t,this.head=$r(t),this._messages.dirty()}resetHead(e){if(e===null){this.clear();return}const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.");if(t.children.length>0){const r=n=>{for(const a of n.children){const s=this.messages.get(a);s&&(r(s),this.messages.delete(a))}};r(t),t.children=[],t.next=null}this.head=t;for(let r=t;r;r=r.prev)r.prev&&(r.prev.next=r);this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){var t,r,n,a;const e=[];for(const[,s]of this.messages)e.push({message:s.current,parentId:(r=(t=s.prev)==null?void 0:t.current.id)!=null?r:null});return{headId:(a=(n=this.head)==null?void 0:n.current.id)!=null?a:null,messages:e}}import({headId:e,messages:t}){var r,n;for(const{message:a,parentId:s}of t)this.addOrUpdateMessage(s,a);this.resetHead((n=e!=null?e:(r=t.at(-1))==null?void 0:r.message.id)!=null?n:null)}},Ur=class{constructor(){T(this,"_subscriptions",new Set);T(this,"_connection")}get isConnected(){return!!this._connection}notifySubscribers(){for(const e of this._subscriptions)e()}_updateConnection(){var e;if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else(e=this._connection)==null||e.call(this),this._connection=void 0}subscribe(e){return this._subscriptions.add(e),this._updateConnection(),()=>{this._subscriptions.delete(e),this._updateConnection()}}},Ge=Symbol("skip-update"),Hn=class extends Ur{constructor(t){super();T(this,"_previousStateDirty",!0);T(this,"_previousState");T(this,"getState",()=>{if(!this.isConnected||this._previousStateDirty){const t=this.binding.getState();t!==Ge&&(this._previousState=t),this._previousStateDirty=!1}if(this._previousState===void 0)throw new Error("Entry not available in the store");return this._previousState});this.binding=t}get path(){return this.binding.path}_connect(){const t=()=>{this._previousStateDirty=!0,this.notifySubscribers()};return this.binding.subscribe(t)}},Hr=class{constructor(e,t){this._core=e,this._threadListBinding=t,this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.switchTo=this.switchTo.bind(this),this.rename=this.rename.bind(this),this.archive=this.archive.bind(this),this.unarchive=this.unarchive.bind(this),this.delete=this.delete.bind(this),this.initialize=this.initialize.bind(this),this.generateTitle=this.generateTitle.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getState=this.getState.bind(this),this.detach=this.detach.bind(this)}getState(){return this._core.getState()}switchTo(){const e=this._core.getState();return this._threadListBinding.switchToThread(e.id)}rename(e){const t=this._core.getState();return this._threadListBinding.rename(t.id,e)}archive(){const e=this._core.getState();return this._threadListBinding.archive(e.id)}unarchive(){const e=this._core.getState();return this._threadListBinding.unarchive(e.id)}delete(){const e=this._core.getState();return this._threadListBinding.delete(e.id)}initialize(){const e=this._core.getState();return this._threadListBinding.initialize(e.id)}generateTitle(){const e=this._core.getState();return this._threadListBinding.generateTitle(e.id)}unstable_on(e,t){let r=this._core.getState().isMain,n=this._core.getState().id;return this.subscribe(()=>{const a=this._core.getState(),s=a.isMain,i=a.id;r===s&&n===i||(r=s,n=i,!(e==="switched-to"&&!s)&&(e==="switched-away"&&s||t()))})}subscribe(e){return this._core.subscribe(e)}detach(){const e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}};function vc(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0)return!1;for(const r of Object.keys(e)){const n=e[r],a=t[r];if(!Object.is(n,a))return!1}return!0}var Xe=class extends Ur{constructor(t){super();T(this,"_previousState");T(this,"getState",()=>(this.isConnected||this._syncState(),this._previousState));this.binding=t;const r=t.getState();if(r===Ge)throw new Error("Entry not available in the store");this._previousState=r}get path(){return this.binding.path}_syncState(){const t=this.binding.getState();return t===Ge||vc(t,this._previousState)?!1:(this._previousState=t,!0)}_connect(){const t=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(t)}},qr=Symbol("innerMessage"),Vr=e=>e.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
4
4
|
|
|
5
|
-
`),za=class{constructor(e){this._core=e,this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(e){return this._core.subscribe(e)}},Ba=class extends za{constructor(e,t){super(e),this._composerApi=t}remove(){const e=this._composerApi.getState();if(!e)throw new Error("Composer is not available");return e.removeAttachment(this.getState().id)}},bc=class extends Ba{get source(){return"thread-composer"}},wc=class extends Ba{get source(){return"edit-composer"}},xc=class extends za{get source(){return"message"}constructor(e){super(e)}remove(){throw new Error("Message attachments cannot be removed")}},Ra=class extends jr{constructor(e){super(),this.config=e}getState(){return this.config.binding.getState()}outerSubscribe(e){return this.config.binding.subscribe(e)}_connect(){const e=()=>{this.notifySubscribers()};let t=this.config.binding.getState(),r=t==null?void 0:t.unstable_on(this.config.event,e);const n=()=>{var s;const a=this.config.binding.getState();a!==t&&(t=a,r==null||r(),r=(s=this.config.binding.getState())==null?void 0:s.unstable_on(this.config.event,e))},i=this.outerSubscribe(n);return()=>{i==null||i(),r==null||r()}}},ja=Object.freeze([]),$a=Object.freeze({}),vc=e=>{var t,r,n,i,a,s,o,l,u;return Object.freeze({type:"thread",isEditing:(t=e==null?void 0:e.isEditing)!=null?t:!1,canCancel:(r=e==null?void 0:e.canCancel)!=null?r:!1,isEmpty:(n=e==null?void 0:e.isEmpty)!=null?n:!0,attachments:(i=e==null?void 0:e.attachments)!=null?i:ja,text:(a=e==null?void 0:e.text)!=null?a:"",role:(s=e==null?void 0:e.role)!=null?s:"user",runConfig:(o=e==null?void 0:e.runConfig)!=null?o:$a,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},kc=e=>{var t,r,n,i,a,s,o,l,u;return Object.freeze({type:"edit",isEditing:(t=e==null?void 0:e.isEditing)!=null?t:!1,canCancel:(r=e==null?void 0:e.canCancel)!=null?r:!1,isEmpty:(n=e==null?void 0:e.isEmpty)!=null?n:!0,text:(i=e==null?void 0:e.text)!=null?i:"",role:(a=e==null?void 0:e.role)!=null?a:"user",attachments:(s=e==null?void 0:e.attachments)!=null?s:ja,runConfig:(o=e==null?void 0:e.runConfig)!=null?o:$a,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},Ua=class{constructor(e){T(this,"_eventSubscriptionSubjects",new Map);this._core=e}get path(){return this._core.path}__internal_bindMethods(){this.setText=this.setText.bind(this),this.setRunConfig=this.setRunConfig.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.addAttachment=this.addAttachment.bind(this),this.reset=this.reset.bind(this),this.clearAttachments=this.clearAttachments.bind(this),this.send=this.send.bind(this),this.cancel=this.cancel.bind(this),this.setRole=this.setRole.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setText(e)}setRunConfig(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setRunConfig(e)}addAttachment(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.addAttachment(e)}reset(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.reset()}clearAttachments(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.clearAttachments()}send(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.send()}cancel(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.cancel()}setRole(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setRole(e)}subscribe(e){return this._core.subscribe(e)}unstable_on(e,t){let r=this._eventSubscriptionSubjects.get(e);return r||(r=new Ra({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}},Sc=class extends Ua{constructor(t){const r=new Bn({path:t.path,getState:()=>vc(t.getState()),subscribe:n=>t.subscribe(n)});super({path:t.path,getState:()=>t.getState(),subscribe:n=>r.subscribe(n)});T(this,"_getState");this._getState=r.getState.bind(r),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"thread"}getState(){return this._getState()}getAttachmentByIndex(t){return new bc(new Xe({path:I(m({},this.path),{attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`}),getState:()=>{const n=this.getState().attachments[t];return n?I(m({},n),{source:"thread-composer"}):Ge},subscribe:r=>this._core.subscribe(r)}),this._core)}},_c=class extends Ua{constructor(t,r){const n=new Bn({path:t.path,getState:()=>kc(t.getState()),subscribe:i=>t.subscribe(i)});super({path:t.path,getState:()=>t.getState(),subscribe:i=>n.subscribe(i)});T(this,"_getState");this._beginEdit=r,this._getState=n.getState.bind(n),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"edit"}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(t){return new wc(new Xe({path:I(m({},this.path),{attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`}),getState:()=>{const n=this.getState().attachments[t];return n?I(m({},n),{source:"edit-composer"}):Ge},subscribe:r=>this._core.subscribe(r)}),this._core)}},Tc=class In{constructor(t=null){T(this,"_state");this._state=t}get state(){return this._state}append(t){this._state=t.reduce((r,n)=>In.apply(r,n),this._state)}static apply(t,r){const n=r.type;switch(n){case"set":return In.updatePath(t,r.path,()=>r.value);case"append-text":return In.updatePath(t,r.path,i=>{if(typeof i!="string")throw new Error(`Expected string at path [${r.path.join(", ")}]`);return i+r.value});default:{const i=n;throw new Error(`Invalid operation type: ${i}`)}}}static updatePath(t,r,n){if(r.length===0)return n(t);if(t!=null||(t={}),typeof t!="object")throw new Error(`Invalid path: [${r.join(", ")}]`);const[i,...a]=r;if(Array.isArray(t)){const o=Number(i);if(Number.isNaN(o))throw new Error(`Expected array index at [${r.join(", ")}]`);if(o>t.length||o<0)throw new Error("Insert array index out of bounds");const l=[...t];return l[o]=this.updatePath(l[o],a,n),l}const s=m({},t);return s[i]=this.updatePath(s[i],a,n),s}},Cc=({unstable_state:e=null}={})=>({role:"assistant",status:{type:"running"},parts:[],get content(){return this.parts},metadata:{unstable_state:e,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}),qr=(e,t,r)=>{if(e.parts.length===0)throw new Error("No parts available to update.");if(t.path.length!==1)throw new Error("Nested paths are not supported yet.");const n=t.path[0],i=r(e.parts[n]);return I(m({},e),{parts:[...e.parts.slice(0,n),i,...e.parts.slice(n+1)],get content(){return this.parts}})},Ic=(e,t)=>{const r=t.part;if(r.type==="text"||r.type==="reasoning"){const n=m({type:r.type,text:"",status:{type:"running"}},r.parentId&&{parentId:r.parentId});return I(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else if(r.type==="tool-call"){const n=m({type:"tool-call",state:"partial-call",status:{type:"running",isArgsComplete:!1},toolCallId:r.toolCallId,toolName:r.toolName,argsText:"",args:{}},r.parentId&&{parentId:r.parentId});return I(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else if(r.type==="source"){const n=m(m({type:"source",sourceType:r.sourceType,id:r.id,url:r.url},r.title?{title:r.title}:void 0),r.parentId&&{parentId:r.parentId});return I(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else if(r.type==="file"){const n={type:"file",mimeType:r.mimeType,data:r.data};return I(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else throw new Error(`Unsupported part type: ${r.type}`)},Ec=(e,t)=>qr(e,t,r=>{if(r.type!=="tool-call")throw new Error("Last is not a tool call");return r.state!=="partial-call"?r:I(m({},r),{state:"call"})}),Ac=(e,t)=>qr(e,t,r=>I(m({},r),{status:{type:"complete",reason:"unknown"}})),Mc=(e,t)=>qr(e,t,r=>{var n;if(r.type==="text"||r.type==="reasoning")return I(m({},r),{text:r.text+t.textDelta});if(r.type==="tool-call"){const i=r.argsText+t.textDelta,a=(n=Br(i))!=null?n:r.args;return I(m({},r),{argsText:i,args:a})}else throw new Error("text-delta received but part is neither text nor tool-call")}),Pc=(e,t)=>qr(e,t,r=>{var n;if(r.type==="tool-call")return I(m(I(m({},r),{state:"result"}),t.artifact!==void 0?{artifact:t.artifact}:{}),{result:t.result,isError:(n=t.isError)!=null?n:!1,status:{type:"complete",reason:"stop"}});throw new Error("Result chunk received but part is not a tool-call")}),Ha=(e,t)=>{var n,i;if(((n=e.status)==null?void 0:n.type)==="incomplete"&&((i=e.status)==null?void 0:i.reason)==="error")return e;const r=Nc(t);return I(m({},e),{status:r})},Nc=e=>e.finishReason==="tool-calls"?{type:"requires-action",reason:"tool-calls"}:e.finishReason==="stop"||e.finishReason==="unknown"?{type:"complete",reason:e.finishReason}:{type:"incomplete",reason:e.finishReason},Lc=(e,t)=>I(m({},e),{metadata:I(m({},e.metadata),{unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]})}),Dc=(e,t)=>I(m({},e),{metadata:I(m({},e.metadata),{unstable_data:[...e.metadata.unstable_data,...t.data]})}),Oc=(e,t)=>I(m({},e),{metadata:I(m({},e.metadata),{steps:[...e.metadata.steps,{state:"started",messageId:t.messageId}]})}),Fc=(e,t)=>{var i;const r=e.metadata.steps.slice(),n=r.length-1;return r.length>0&&((i=r[n])==null?void 0:i.state)==="started"?r[n]=I(m({},r[n]),{state:"finished",finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}):r.push({state:"finished",messageId:La(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),I(m({},e),{metadata:I(m({},e.metadata),{steps:r})})},zc=(e,t)=>I(m({},e),{status:{type:"incomplete",reason:"error",error:t.error}}),Bc=(e,t)=>{const r=new Tc(e.metadata.unstable_state);return r.append(t.operations),I(m({},e),{metadata:I(m({},e.metadata),{unstable_state:r.state})})},Rc=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}},jc=class extends TransformStream{constructor({initialMessage:e,throttle:t,onError:r}={}){let n=e!=null?e:Cc(),i;const a=t?Rc(()=>{i==null||i.enqueue(n)}):()=>{i==null||i.enqueue(n)};super({start(s){i=s},transform(s){const o=s.type;switch(o){case"part-start":n=Ic(n,s);break;case"tool-call-args-text-finish":n=Ec(n,s);break;case"part-finish":n=Ac(n,s);break;case"text-delta":n=Mc(n,s);break;case"result":n=Pc(n,s);break;case"message-finish":n=Ha(n,s);break;case"annotations":n=Lc(n,s);break;case"data":n=Dc(n,s);break;case"step-start":n=Oc(n,s);break;case"step-finish":n=Fc(n,s);break;case"error":n=zc(n,s),r==null||r(s.error);break;case"update-state":n=Bc(n,s);break;default:{const l=o;throw new Error(`Unsupported chunk type: ${l}`)}}a()},flush(s){var o,l,u;if(((o=n.status)==null?void 0:o.type)==="running"){const d=(u=(l=n.parts)==null?void 0:l.some(c=>c.type==="tool-call"&&(c.state==="call"||c.state==="partial-call")&&c.result===void 0))!=null?u:!1;n=Ha(n,{finishReason:d?"tool-calls":"unknown"}),s.enqueue(n)}}})}},$c=class extends Pa{constructor(){super(e=>{const t=new mc({transform(r,n){n.appendText(r)}});return e.pipeThrough(new TextDecoderStream).pipeThrough(t)})}},Uc=class En{constructor(t){this.readable=t,this.readable=t}static fromAssistantStream(t){return new En(t.pipeThrough(new jc))}unstable_result(){return M(this,null,function*(){let t;try{for(var r=Ft(this),n,i,a;n=!(i=yield r.next()).done;n=!1){const s=i.value;t=s}}catch(i){a=[i]}finally{try{n&&(i=r.return)&&(yield i.call(r))}finally{if(a)throw a[0]}}return t||{role:"assistant",status:{type:"complete",reason:"unknown"},parts:[],content:[],metadata:{unstable_state:null,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}})}[Symbol.asyncIterator](){const t=this.readable.getReader();return{next(){return M(this,null,function*(){const{done:n,value:i}=yield t.read();return n?{done:!0,value:void 0}:{done:!1,value:i}})}}}tee(){const[t,r]=this.readable.tee();return[new En(t),new En(r)]}},qa=Symbol.for("aui.tool-response"),gt=class da{constructor(t){T(this,"artifact");T(this,"result");T(this,"isError");var r;t.artifact!==void 0&&(this.artifact=t.artifact),this.result=t.result,this.isError=(r=t.isError)!=null?r:!1}get[qa](){return!0}static[Symbol.hasInstance](t){return typeof t=="object"&&t!==null&&qa in t}static toResponse(t){return t instanceof da?t:new da({result:t===void 0?"<no result>":t})}};function Hc(e,t,r){try{const n=e();if(typeof n=="object"&&n!==null&&"then"in n)return n.then(t,r);t(n)}catch(n){r(n)}}function lr(e,t){let r=e;for(const n of t){if(r==null)return;r=r[n]}return r}var qc=class{constructor(e,t,r){T(this,"resolve");T(this,"reject");T(this,"disposed",!1);T(this,"fieldPath");this.resolve=e,this.reject=t,this.fieldPath=r}update(e){if(!this.disposed)try{if(zt(e,this.fieldPath)==="complete"){const t=lr(e,this.fieldPath);t!==void 0&&(this.resolve(t),this.dispose())}}catch(t){this.reject(t),this.dispose()}}dispose(){this.disposed=!0}},Va=class{constructor(e,t){T(this,"controller");T(this,"disposed",!1);T(this,"fieldPath");this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=lr(e,this.fieldPath);t!==void 0&&this.controller.enqueue(t),zt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},Wa=class{constructor(e,t){T(this,"controller");T(this,"disposed",!1);T(this,"fieldPath");T(this,"lastValue");this.controller=e,this.fieldPath=t}update(e){var t;if(!this.disposed)try{const r=lr(e,this.fieldPath);if(r!==void 0&&typeof r=="string"){const n=r.substring(((t=this.lastValue)==null?void 0:t.length)||0);this.lastValue=r,this.controller.enqueue(n)}zt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(r){this.controller.error(r),this.dispose()}}dispose(){this.disposed=!0}},Ja=class{constructor(e,t){T(this,"controller");T(this,"disposed",!1);T(this,"fieldPath");T(this,"processedIndexes",new Set);this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=lr(e,this.fieldPath);if(!Array.isArray(t))return;for(let r=0;r<t.length;r++)if(!this.processedIndexes.has(r)){const n=[...this.fieldPath,r];zt(e,n)==="complete"&&(this.controller.enqueue(t[r]),this.processedIndexes.add(r))}zt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},Vc=class{constructor(e){T(this,"argTextDeltas");T(this,"handles",new Set);T(this,"args",Br(""));this.argTextDeltas=e,this.processStream()}processStream(){return M(this,null,function*(){try{let e="";const t=this.argTextDeltas.getReader();for(;;){const{value:r,done:n}=yield t.read();if(n)break;e+=r;const i=Br(e);if(i!==void 0){this.args=i;for(const a of this.handles)a.update(i)}}}catch(e){console.error("Error processing argument stream:",e);for(const t of this.handles)t.dispose()}})}get(...e){return new Promise((t,r)=>{const n=new qc(t,r,e);if(this.args&&zt(this.args,e)==="complete"){const i=lr(this.args,e);if(i!==void 0){t(i);return}}this.handles.add(n),n.update(this.args)})}streamValues(...e){const t=e,r=new ReadableStream({start:n=>{const i=new Va(n,t);this.handles.add(i),i.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Va){n.dispose(),this.handles.delete(n);break}}});return Dn(r)}streamText(...e){const t=e,r=new ReadableStream({start:n=>{const i=new Wa(n,t);this.handles.add(i),i.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Wa){n.dispose(),this.handles.delete(n);break}}});return Dn(r)}forEach(...e){const t=e,r=new ReadableStream({start:n=>{const i=new Ja(n,t);this.handles.add(i),i.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Ja){n.dispose(),this.handles.delete(n);break}}});return Dn(r)}},Wc=class{constructor(e){this.promise=e}get(){return this.promise}},Jc=class{constructor(){T(this,"args");T(this,"response");T(this,"writable");T(this,"resolve");T(this,"argsText","");T(this,"result",{get:()=>M(this,null,function*(){return(yield this.response.get()).result})});const e=new TransformStream;this.writable=e.writable,this.args=new Vc(e.readable);const{promise:t,resolve:r}=Fn();this.resolve=r,this.response=new Wc(t)}appendArgsTextDelta(e){return M(this,null,function*(){const t=this.writable.getWriter();try{yield t.write(e)}catch(r){console.warn(r)}finally{t.releaseLock()}this.argsText+=e})}setResponse(e){this.resolve(e)}},Kc=class extends Pa{constructor(e){const t=new Map,r=new Map;super(n=>{const i=new TransformStream({transform(s,o){switch((s.type!=="part-finish"||s.meta.type!=="tool-call")&&o.enqueue(s),s.type){case"part-start":if(s.part.type==="tool-call"){const u=new Jc;r.set(s.part.toolCallId,u),e.streamCall({reader:u,toolCallId:s.part.toolCallId,toolName:s.part.toolName})}break;case"text-delta":{if(s.meta.type==="tool-call"){const u=s.meta.toolCallId,d=r.get(u);if(!d)throw new Error("No controller found for tool call");d.appendArgsTextDelta(s.textDelta)}break}case"result":{if(s.meta.type!=="tool-call")break;const{toolCallId:u}=s.meta,d=r.get(u);if(!d)throw new Error("No controller found for tool call");d.setResponse(new gt({result:s.result,artifact:s.artifact,isError:s.isError}));break}case"tool-call-args-text-finish":{if(s.meta.type!=="tool-call")break;const{toolCallId:u,toolName:d}=s.meta,c=r.get(u);if(!c)throw new Error("No controller found for tool call");let f=!1;const h=Hc(()=>{var b;let g;try{g=Ln.parse(c.argsText)}catch(w){throw new Error(`Function parameter parsing failed. ${JSON.stringify(w.message)}`)}const x=e.execute({toolCallId:u,toolName:d,args:g});return x!==void 0&&(f=!0,(b=e.onExecutionStart)==null||b.call(e,u,d)),x},g=>{var b;if(f&&((b=e.onExecutionEnd)==null||b.call(e,u,d)),g===void 0)return;const x=new gt({artifact:g.artifact,result:g.result,isError:g.isError});c.setResponse(x),o.enqueue(m({type:"result",path:s.path},x))},g=>{var b;f&&((b=e.onExecutionEnd)==null||b.call(e,u,d));const x=new gt({result:String(g),isError:!0});c.setResponse(x),o.enqueue(m({type:"result",path:s.path},x))});h&&t.set(u,h);break}case"part-finish":{if(s.meta.type!=="tool-call")break;const{toolCallId:u}=s.meta,d=t.get(u);d?d.then(()=>{t.delete(u),r.delete(u),o.enqueue(s)}):o.enqueue(s)}}},flush(){return M(this,null,function*(){yield Promise.all(t.values())})}});return n.pipeThrough(new Na).pipeThrough(i)})}},Yc=e=>typeof e=="object"&&e!==null&&"~standard"in e&&e["~standard"].version===1;function Gc(e,t,r,n){const i=e==null?void 0:e[r.toolName];return!i||!i.execute?void 0:(s=>M(null,null,function*(){var d;if(t.aborted)return new gt({result:"Tool execution was cancelled.",isError:!0});let o=s;if(Yc(i.parameters)){let c=i.parameters["~standard"].validate(r.args);c instanceof Promise&&(c=yield c),c.issues&&(o=(d=i.experimental_onSchemaValidationError)!=null?d:(()=>{throw new Error(`Function parameter validation failed. ${JSON.stringify(c.issues)}`)}))}const l=new Promise(c=>{const f=()=>{queueMicrotask(()=>{queueMicrotask(()=>{c(new gt({result:"Tool execution was cancelled.",isError:!0}))})})};t.aborted?f():t.addEventListener("abort",f,{once:!0})}),u=M(null,null,function*(){const c=yield o(r.args,{toolCallId:r.toolCallId,abortSignal:t,human:f=>n(r.toolCallId,f)});return gt.toResponse(c)});return Promise.race([u,l])}))(i.execute)}function Xc(e,t,r,n,i){var a,s;(s=(a=e==null?void 0:e[n.toolName])==null?void 0:a.streamCall)==null||s.call(a,r,{toolCallId:n.toolCallId,abortSignal:t,human:o=>i(n.toolCallId,o)})}function Qc(e,t,r,n){const i=typeof e=="function"?e:()=>e,a=typeof t=="function"?t:()=>t;return new Kc({execute:s=>Gc(i(),a(),s,r),streamCall:l=>{var u=l,{reader:s}=u,o=H(u,["reader"]);return Xc(i(),a(),s,o,r)},onExecutionStart:n==null?void 0:n.onExecutionStart,onExecutionEnd:n==null?void 0:n.onExecutionEnd})}var Ka=class{constructor(e,t,r){this.contentBinding=e,this.messageApi=t,this.threadApi=r,this.__internal_bindMethods()}get path(){return this.contentBinding.path}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.resumeToolCall=this.resumeToolCall.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to add tool result to non-tool message part");if(!this.messageApi)throw new Error("Message API is not available. This is likely a bug in assistant-ui.");if(!this.threadApi)throw new Error("Thread API is not available");const r=this.messageApi.getState();if(!r)throw new Error("Message is not available");const n=t.toolName,i=t.toolCallId,a=gt.toResponse(e);this.threadApi.getState().addToolResult({messageId:r.id,toolName:n,toolCallId:i,result:a.result,artifact:a.artifact,isError:a.isError})}resumeToolCall(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to resume tool call on non-tool message part");if(!this.threadApi)throw new Error("Thread API is not available");const r=t.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:r,payload:e})}subscribe(e){return this.contentBinding.subscribe(e)}},Vr=class extends jr{constructor(e){super(),this.binding=e}get path(){return this.binding.path}getState(){return this.binding.getState()}outerSubscribe(e){return this.binding.subscribe(e)}_connect(){const e=()=>{this.notifySubscribers()};let t=this.binding.getState(),r=t==null?void 0:t.subscribe(e);const n=()=>{var s;const a=this.binding.getState();a!==t&&(t=a,r==null||r(),r=(s=this.binding.getState())==null?void 0:s.subscribe(e),e())},i=this.outerSubscribe(n);return()=>{i==null||i(),r==null||r()}}},Wr=Object.freeze({type:"complete"}),Zc=(e,t,r)=>{if(e.role!=="assistant")return Wr;if(r.type==="tool-call")return r.result?Wr:e.status;const n=t===Math.max(0,e.content.length-1);return e.status.type==="requires-action"?Wr:n?e.status:Wr},Ya=(e,t)=>{const r=e.content[t];if(!r)return Ge;const n=Zc(e,t,r);return Object.freeze(I(m({},r),{[Ur]:r[Ur],status:n}))},ed=class{constructor(e,t){T(this,"composer");T(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=e,this._threadBinding=t,this.composer=new _c(new Vr({path:I(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"edit"}),getState:this._getEditComposerRuntimeCore,subscribe:r=>this._threadBinding.subscribe(r)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id)),this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.reload=this.reload.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getMessagePartByIndex=this.getMessagePartByIndex.bind(this),this.getMessagePartByToolCallId=this.getMessagePartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}getState(){return this._core.getState()}reload(e={}){const t=this._getEditComposerRuntimeCore(),r=t!=null?t:this._threadBinding.getState().composer,n=t!=null?t:r,{runConfig:i=n.runConfig}=e,a=this._core.getState();if(a.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:a.parentId,sourceId:a.id,runConfig:i})}speak(){const e=this._core.getState();return this._threadBinding.getState().speak(e.id)}stopSpeaking(){var r;const e=this._core.getState();if(((r=this._threadBinding.getState().speech)==null?void 0:r.messageId)===e.id)this._threadBinding.getState().stopSpeaking();else throw new Error("Message is not being spoken")}submitFeedback({type:e}){const t=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:t.id,type:e})}switchToBranch({position:e,branchId:t}){const r=this._core.getState();if(t&&e)throw new Error("May not specify both branchId and position");if(!t&&!e)throw new Error("Must specify either branchId or position");const i=this._threadBinding.getState().getBranches(r.id);let a=t;if(e==="previous"?a=i[r.branchNumber-2]:e==="next"&&(a=i[r.branchNumber]),!a)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(a)}unstable_getCopyText(){return Hr(this.getState())}subscribe(e){return this._core.subscribe(e)}getMessagePartByIndex(e){if(e<0)throw new Error("Message part index must be >= 0");return new Ka(new Xe({path:I(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.content[${e}]`,messagePartSelector:{type:"index",index:e}}),getState:()=>Ya(this.getState(),e),subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new Ka(new Xe({path:I(m({},this.path),{ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(e)}]`,messagePartSelector:{type:"toolCallId",toolCallId:e}}),getState:()=>{const t=this._core.getState(),r=t.content.findIndex(n=>n.type==="tool-call"&&n.toolCallId===e);return r===-1?Ge:Ya(t,r)},subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new xc(new Xe({path:I(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.attachments[${e}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:e}}),getState:()=>{const t=this.getState().attachments,r=t==null?void 0:t[e];return r?I(m({},r),{source:"message"}):Ge},subscribe:t=>this._core.subscribe(t)}))}},td=e=>{var t,r,n;return m({parentId:(t=e.parentId)!=null?t:null,sourceId:(r=e.sourceId)!=null?r:null,runConfig:(n=e.runConfig)!=null?n:{}},e.stream?{stream:e.stream}:{})},rd=e=>{var t,r,n;return{parentId:(t=e.parentId)!=null?t:null,sourceId:(r=e.sourceId)!=null?r:null,runConfig:(n=e.runConfig)!=null?n:{}}},nd=(e,t)=>{var r,n,i,a,s,o,l,u,d,c,f;return typeof t=="string"?{createdAt:new Date,parentId:(n=(r=e.at(-1))==null?void 0:r.id)!=null?n:null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:(i=t.createdAt)!=null?i:new Date,parentId:(o=(s=t.parentId)!=null?s:(a=e.at(-1))==null?void 0:a.id)!=null?o:null,sourceId:(l=t.sourceId)!=null?l:null,role:(u=t.role)!=null?u:"user",content:t.content,attachments:(d=t.attachments)!=null?d:[],metadata:(c=t.metadata)!=null?c:{custom:{}},runConfig:(f=t.runConfig)!=null?f:{},startRun:t.startRun}},id=(e,t)=>{const r=e.messages.at(-1);return Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,isRunning:(r==null?void 0:r.role)!=="assistant"?!1:r.status.type==="running",messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech})},Ga=class{constructor(e,t){T(this,"_threadBinding");T(this,"composer");T(this,"_eventSubscriptionSubjects",new Map);const r=new Xe({path:e.path,getState:()=>id(e.getState(),t.getState()),subscribe:n=>{const i=e.subscribe(n),a=t.subscribe(n);return()=>{i(),a()}}});this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>r.getState(),outerSubscribe:n=>e.outerSubscribe(n),subscribe:n=>e.subscribe(n)},this.composer=new Sc(new Vr({path:I(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"thread"}),getState:()=>this._threadBinding.getState().composer,subscribe:n=>this._threadBinding.subscribe(n)})),this.__internal_bindMethods()}get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}__internal_bindMethods(){this.append=this.append.bind(this),this.unstable_resumeRun=this.unstable_resumeRun.bind(this),this.unstable_loadExternalState=this.unstable_loadExternalState.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.reset=this.reset.bind(this),this.getMessageByIndex=this.getMessageByIndex.bind(this),this.getMessageById=this.getMessageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.getModelConfig=this.getModelConfig.bind(this),this.getState=this.getState.bind(this)}getState(){return this._threadBinding.getStateState()}append(e){this._threadBinding.getState().append(nd(this._threadBinding.getState().messages,e))}subscribe(e){return this._threadBinding.subscribe(e)}getModelContext(){return this._threadBinding.getState().getModelContext()}getModelConfig(){return this.getModelContext()}startRun(e){const t=e===null||typeof e=="string"?{parentId:e}:e;return this._threadBinding.getState().startRun(rd(t))}unstable_resumeRun(e){return this._threadBinding.getState().resumeRun(td(e))}unstable_loadExternalState(e){this._threadBinding.getState().unstable_loadExternalState(e)}cancelRun(){this._threadBinding.getState().cancelRun()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}export(){return this._threadBinding.getState().export()}import(e){this._threadBinding.getState().import(e)}reset(e){this._threadBinding.getState().reset(e)}getMessageByIndex(e){if(e<0)throw new Error("Message index must be >= 0");return this._getMessageRuntime(I(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.messages[${e}]`,messageSelector:{type:"index",index:e}}),()=>{var n,i;const t=this._threadBinding.getState().messages,r=t[e];if(r)return{message:r,parentId:(i=(n=t[e-1])==null?void 0:n.id)!=null?i:null,index:e}})}getMessageById(e){return this._getMessageRuntime(I(m({},this.path),{ref:this.path.ref+`${this.path.ref}.messages[messageId=${JSON.stringify(e)}]`,messageSelector:{type:"messageId",messageId:e}}),()=>this._threadBinding.getState().getMessageById(e))}_getMessageRuntime(e,t){return new ed(new Xe({path:e,getState:()=>{var d,c;const{message:r,parentId:n,index:i}=(d=t())!=null?d:{},{messages:a,speech:s}=this._threadBinding.getState();if(!r||n===void 0||i===void 0)return Ge;const l=this._threadBinding.getState().getBranches(r.id),u=r.metadata.submittedFeedback;return I(m({},r),{[Ur]:r[Ur],index:i,isLast:((c=a.at(-1))==null?void 0:c.id)===r.id,parentId:n,branchNumber:l.indexOf(r.id)+1,branchCount:l.length,speech:(s==null?void 0:s.messageId)===r.id?s:void 0,submittedFeedback:u})},subscribe:r=>this._threadBinding.subscribe(r)}),this._threadBinding)}unstable_on(e,t){let r=this._eventSubscriptionSubjects.get(e);return r||(r=new Ra({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}},ad=e=>({mainThreadId:e.mainThreadId,newThread:e.newThreadId,threads:e.threadIds,archivedThreads:e.archivedThreadIds,isLoading:e.isLoading,threadItems:e.threadData}),Jr=(e,t)=>{if(t===void 0)return Ge;const r=e.getItemById(t);return r?{id:r.id,threadId:r.id,remoteId:r.remoteId,externalId:r.externalId,title:r.title,status:r.status,isMain:r.id===e.mainThreadId}:Ge},sd=class{constructor(e,t=Ga){T(this,"_getState");T(this,"_mainThreadListItemRuntime");T(this,"main");this._core=e,this._runtimeFactory=t;const r=new Bn({path:{},getState:()=>ad(e),subscribe:n=>e.subscribe(n)});this._getState=r.getState.bind(r),this._mainThreadListItemRuntime=new $r(new Xe({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>Jr(this._core,this._core.mainThreadId),subscribe:n=>this._core.subscribe(n)}),this._core),this.main=new t(new Vr({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>e.getMainThreadRuntimeCore(),subscribe:n=>e.subscribe(n)}),this._mainThreadListItemRuntime),this.__internal_bindMethods()}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getById=this.getById.bind(this),this.getItemById=this.getItemById.bind(this),this.getItemByIndex=this.getItemByIndex.bind(this),this.getArchivedItemByIndex=this.getArchivedItemByIndex.bind(this)}switchToThread(e){return this._core.switchToThread(e)}switchToNewThread(){return this._core.switchToNewThread()}getState(){return this._getState()}subscribe(e){return this._core.subscribe(e)}get mainItem(){return this._mainThreadListItemRuntime}getById(e){return new this._runtimeFactory(new Vr({path:{ref:`threads[threadId=${JSON.stringify(e)}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>this._core.getThreadRuntimeCore(e),subscribe:t=>this._core.subscribe(t)}),this.mainItem)}getItemByIndex(e){return new $r(new Xe({path:{ref:`threadItems[${e}]`,threadSelector:{type:"index",index:e}},getState:()=>Jr(this._core,this._core.threadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getArchivedItemByIndex(e){return new $r(new Xe({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:"archiveIndex",index:e}},getState:()=>Jr(this._core,this._core.archivedThreadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getItemById(e){return new $r(new Xe({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>Jr(this._core,e),subscribe:t=>this._core.subscribe(t)}),this._core)}},od=e=>e.startsWith("image/")?"image":e.startsWith("text/")?"document":"file",ld=class{constructor(e){T(this,"accept","*");T(this,"uploadedUrls",new Map);this.cloud=e}add(t){return Dr(this,arguments,function*({file:e}){const r=crypto.randomUUID(),n=od(e.type);let i={id:r,type:n,name:e.name,contentType:e.type,file:e,status:{type:"running",reason:"uploading",progress:0}};yield i;try{const{signedUrl:a,publicUrl:s}=yield new Ae(this.cloud.files.generatePresignedUploadUrl({filename:e.name}));yield new Ae(fetch(a,{method:"PUT",body:e,headers:{"Content-Type":e.type},mode:"cors"})),this.uploadedUrls.set(r,s),i=I(m({},i),{status:{type:"requires-action",reason:"composer-send"}}),yield i}catch(a){i=I(m({},i),{status:{type:"incomplete",reason:"error"}}),yield i}})}remove(e){return M(this,null,function*(){this.uploadedUrls.delete(e.id)})}send(e){return M(this,null,function*(){const t=this.uploadedUrls.get(e.id);if(!t)throw new Error("Attachment not uploaded");this.uploadedUrls.delete(e.id);let r;return e.type==="image"?r=[{type:"image",image:t,filename:e.name}]:r=[{type:"file",data:t,mimeType:e.contentType,filename:e.name}],I(m({},e),{status:{type:"complete"},content:r})})}},Rn=y.createContext(null),jn=({adapters:e,children:t})=>{const r=y.useContext(Rn);return p.jsx(Rn.Provider,{value:m(m({},r),e),children:t})},ud=()=>y.useContext(Rn),cd=class extends xa{constructor(t,r,{parentId:n,message:i}){var a;super();T(this,"_nonTextParts");T(this,"_previousText");T(this,"_parentId");T(this,"_sourceId");this.runtime=t,this.endEditCallback=r,this._parentId=n,this._sourceId=i.id,this._previousText=Hr(i),this.setText(this._previousText),this.setRole(i.role),this.setAttachments((a=i.attachments)!=null?a:[]),this._nonTextParts=i.content.filter(s=>s.type!=="text"),this.setRunConfig(m({},t.composer.runConfig))}get canCancel(){return!0}getAttachmentAdapter(){var t;return(t=this.runtime.adapters)==null?void 0:t.attachments}handleSend(t){return M(this,null,function*(){Hr(t)!==this._previousText&&this.runtime.append(I(m({},t),{content:[...t.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId})),this.handleCancel()})}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},dd=class{constructor(e){T(this,"_subscriptions",new Set);T(this,"_isInitialized",!1);T(this,"repository",new Fa);T(this,"composer",new va(this));T(this,"_editComposers",new Map);T(this,"_stopSpeaking");T(this,"speech");T(this,"_eventSubscribers",new Map);this._contextProvider=e}get messages(){return this.repository.getMessages()}get state(){var t;let e;for(const r of this.messages)if(r.role==="assistant"){e=r;break}return(t=e==null?void 0:e.metadata.unstable_state)!=null?t:null}getModelContext(){return this._contextProvider.getModelContext()}getEditComposer(e){return this._editComposers.get(e)}beginEdit(e){if(this._editComposers.has(e))throw new Error("Edit already in progress");this._editComposers.set(e,new cd(this,()=>this._editComposers.delete(e),this.repository.getMessage(e))),this._notifySubscribers()}getMessageById(e){try{return this.repository.getMessage(e)}catch(t){return}}getBranches(e){return this.repository.getBranches(e)}switchToBranch(e){this.repository.switchToBranch(e),this._notifySubscribers()}_notifySubscribers(){for(const e of this._subscriptions)e()}_notifyEventSubscribers(e){const t=this._eventSubscribers.get(e);if(t)for(const r of t)r()}subscribe(e){return this._subscriptions.add(e),()=>this._subscriptions.delete(e)}submitFeedback({messageId:e,type:t}){var a;const r=(a=this.adapters)==null?void 0:a.feedback;if(!r)throw new Error("Feedback adapter not configured");const{message:n,parentId:i}=this.repository.getMessage(e);if(r.submit({message:n,type:t}),n.role==="assistant"){const s=I(m({},n),{metadata:I(m({},n.metadata),{submittedFeedback:{type:t}})});this.repository.addOrUpdateMessage(i,s)}this._notifySubscribers()}speak(e){var a,s;const t=(a=this.adapters)==null?void 0:a.speech;if(!t)throw new Error("Speech adapter not configured");const{message:r}=this.repository.getMessage(e);(s=this._stopSpeaking)==null||s.call(this);const n=t.speak(Hr(r)),i=n.subscribe(()=>{n.status.type==="ended"?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:e,status:n.status},this._notifySubscribers()});this.speech={messageId:e,status:n.status},this._notifySubscribers(),this._stopSpeaking=()=>{n.cancel(),i(),this.speech=void 0,this._stopSpeaking=void 0}}stopSpeaking(){if(!this._stopSpeaking)throw new Error("No message is being spoken");this._stopSpeaking(),this._notifySubscribers()}ensureInitialized(){this._isInitialized||(this._isInitialized=!0,this._notifyEventSubscribers("initialize"))}export(){return this.repository.export()}import(e){this.ensureInitialized(),this.repository.clear(),this.repository.import(e),this._notifySubscribers()}reset(e){this.import(zn.fromArray(e!=null?e:[]))}unstable_on(e,t){var n,i,a;if(e==="model-context-update")return(a=(i=(n=this._contextProvider).subscribe)==null?void 0:i.call(n,t))!=null?a:(()=>{});const r=this._eventSubscribers.get(e);return r?r.add(t):this._eventSubscribers.set(e,new Set([t])),()=>{this._eventSubscribers.get(e).delete(t)}}},hd=e=>{try{return JSON.parse(e),!0}catch(t){return!1}};function fd({state:e,getTools:t,onResult:r,setToolStatuses:n}){const i=y.useRef({}),a=y.useRef(new Map),s=y.useRef(new AbortController),o=y.useRef(0),l=y.useRef([]),[u]=y.useState(()=>{const[h,g]=Oa(),x=Qc(t,()=>{var b,w;return(w=(b=s.current)==null?void 0:b.signal)!=null?w:new AbortController().signal},(b,w)=>new Promise((E,_)=>{const O=a.current.get(b);O&&O.reject(new Error("Human input request was superseded by a new request")),a.current.set(b,{resolve:E,reject:_}),n(z=>I(m({},z),{[b]:{type:"interrupt",payload:{type:"human",payload:w}}}))}),{onExecutionStart:b=>{o.current++,n(w=>I(m({},w),{[b]:{type:"executing"}}))},onExecutionEnd:b=>{o.current--,n(w=>{const E=m({},w);return delete E[b],E}),o.current===0&&(l.current.forEach(w=>w()),l.current=[])}});return h.pipeThrough(x).pipeThrough(new Na).pipeTo(new WritableStream({write(b){var w;if(b.type==="result"){if((w=i.current[b.meta.toolCallId])!=null&&w.hasResult)return;r(m({type:"add-tool-result",toolCallId:b.meta.toolCallId,toolName:b.meta.toolName,result:b.result,isError:b.isError},b.artifact&&{artifact:b.artifact}))}}})),g}),d=y.useRef(new Set),c=y.useRef(!0);y.useEffect(()=>{const h=g=>{g.forEach(x=>{x.content.forEach(b=>{if(b.type==="tool-call"){if(c.current)d.current.add(b.toolCallId);else{if(d.current.has(b.toolCallId))return;let w=i.current[b.toolCallId];if(w||(w={argsText:"",hasResult:!1,argsComplete:!1,controller:u.addToolCallPart({toolName:b.toolName,toolCallId:b.toolCallId})},i.current[b.toolCallId]=w),b.argsText!==w.argsText)if(w.argsComplete)process.env.NODE_ENV!=="production"&&console.warn("argsText updated after controller was closed:",{previous:w.argsText,next:b.argsText});else{if(!b.argsText.startsWith(w.argsText))throw new Error(`Tool call argsText can only be appended, not updated: ${b.argsText} does not start with ${w.argsText}`);const E=b.argsText.slice(w.argsText.length);w.controller.argsText.append(E);const _=hd(b.argsText);_&&w.controller.argsText.close(),i.current[b.toolCallId]={argsText:b.argsText,hasResult:w.hasResult,argsComplete:_,controller:w.controller}}b.result!==void 0&&!w.hasResult&&(w.controller.setResponse(new gt({result:b.result,artifact:b.artifact,isError:b.isError})),w.controller.close(),i.current[b.toolCallId]={hasResult:!0,argsComplete:!0,argsText:w.argsText,controller:w.controller})}b.messages&&h(b.messages)}})})};h(e.messages),c.current&&(c.current=!1)},[e,u,r]);const f=()=>(a.current.forEach(({reject:h})=>{h(new Error("Tool execution aborted"))}),a.current.clear(),s.current.abort(),s.current=new AbortController,o.current===0?Promise.resolve():new Promise(h=>{l.current.push(h)}));return{reset:()=>{f(),c.current=!0},abort:f,resume:(h,g)=>{const x=a.current.get(h);if(x)a.current.delete(h),n(b=>I(m({},b),{[h]:{type:"executing"}})),x.resolve(g);else throw new Error(`Tool call ${h} is not waiting for human input`)}}}var pd=class{list(){return Promise.resolve({threads:[]})}rename(){return Promise.resolve()}archive(){return Promise.resolve()}unarchive(){return Promise.resolve()}delete(){return Promise.resolve()}initialize(e){return Promise.resolve({remoteId:e,externalId:void 0})}generateTitle(){return Promise.resolve(new ReadableStream)}fetch(e){return Promise.reject(new Error("Thread not found"))}};function md(e,t){e.commitTasks.forEach(r=>{const n=r.cellIndex,i=t.cells[n];if(i.type!=="effect")throw new Error("Cannot find effect cell");let a=!0;if(i.deps!==void 0&&r.deps!==void 0&&(a=i.deps.length!==r.deps.length||i.deps.some((s,o)=>!Object.is(s,r.deps[o]))),a){if(i.mounted){if(typeof i.deps!=typeof r.deps)throw new Error("tapEffect called with and without dependencies across re-renders");try{i.mounted&&i.cleanup&&i.cleanup()}finally{i.mounted=!1}}try{const s=r.effect();if(s!==void 0&&typeof s!="function")throw new Error(`An effect function must either return a cleanup function or nothing. Received: ${typeof s}`);i.mounted=!0,i.cleanup=typeof s=="function"?s:void 0,i.deps=r.deps}catch(s){throw s}}})}function gd(e){let t=null;for(let r=e.cells.length-1;r>=0;r--){const n=e.cells[r];if((n==null?void 0:n.type)==="effect"&&n.mounted&&n.cleanup)try{n.cleanup()}catch(i){t==null&&(t=i)}finally{n.mounted=!1}}if(t!=null)throw t}var ur=null;function yd(e,t){e.currentIndex=0;const r=ur;ur=e;try{if(t(),e.isFirstRender=!1,e.cells.length!==e.currentIndex)throw new Error(`Rendered ${e.currentIndex} hooks but expected ${e.cells.length}. Hooks must be called in the exact same order in every render.`)}finally{ur=r}}function $n(){if(!ur)throw new Error("No resource fiber available");return ur}function Xa(e,t){const r=e[Qa];if(!r)throw new Error("ResourceElement.type is not a valid Resource");return r(t)}var Qa=Symbol("fnSymbol");function Kr(e,t){return{resource:e,scheduleRerender:t,cells:[],currentIndex:0,renderContext:void 0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function Bt(e){e.isMounted=!1,gd(e)}function cr(e,t){const r={commitTasks:[],props:t,state:void 0};return yd(e,()=>{e.renderContext=r;try{r.state=Xa(e.resource,t)}finally{e.renderContext=void 0}}),r}function Rt(e,t){e.isMounted=!0,e.isNeverMounted=!1,md(t,e)}var bd=globalThis.__ASSISTANT_UI_DISABLE_LAYOUT_EFFECT__===!0,Za=bd?y.useEffect:y.useLayoutEffect;function Un(e){const[,t]=y.useState({}),r=y.useMemo(()=>Kr(e.type,()=>t({})),[e.type,t]),n=cr(r,e.props);return Za(()=>()=>Bt(r),[]),Za(()=>{Rt(r,n)}),n.state}var jt=e=>typeof e=="string"?{scope:e.split(".")[0],event:e}:{scope:e.scope,event:e.event},Ct=(e,t,r)=>t===e,$t,Hn=()=>{if($t)return $t;const e=()=>({apis:new Map,nextId:0,listeners:new Set});if(typeof window=="undefined")return $t=e(),$t;const t=window.__ASSISTANT_UI_DEVTOOLS_HOOK__;if(t)return $t=t,t;const r=e();return window.__ASSISTANT_UI_DEVTOOLS_HOOK__=r,$t=r,r},wd=(tt=class{static register(t){var o,l;const r=Hn();for(const u of r.apis.values())if(u.api===t)return()=>{};const n=r.nextId++,i={api:t,logs:[]},a=(o=t.on)==null?void 0:o.call(t,"*",u=>{const d=r.apis.get(n);d&&(d.logs.push({time:new Date,event:u.event,data:u.payload}),d.logs.length>tt.MAX_EVENT_LOGS_PER_API&&(d.logs=d.logs.slice(-200)),tt.notifyListeners(n))}),s=(l=t.subscribe)==null?void 0:l.call(t,()=>{tt.notifyListeners(n)});return r.apis.set(n,i),tt.notifyListeners(n),()=>{const u=Hn();u.apis.get(n)&&(a==null||a(),s==null||s(),u.apis.delete(n),tt.notifyListeners(n))}}static notifyListeners(t){Hn().listeners.forEach(n=>n(t))}},T(tt,"MAX_EVENT_LOGS_PER_API",200),tt);function ye(e){const t=(r,n)=>m({type:t,props:r},(n==null?void 0:n.key)!==void 0&&{key:n.key});return t[Qa]=e,t}var xd=e=>{if(e.renderContext)throw new Error("Resource updated during render");if(e.isNeverMounted)throw new Error("Resource updated before mount");e.isMounted&&e.scheduleRerender()};function vd(e){const t=$n(),r=t.currentIndex++;if(!t.isFirstRender&&r>=t.cells.length)throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");if(!t.cells[r]){const a={type:"state",value:typeof e=="function"?e():e,set:s=>{const o=a.value,l=typeof s=="function"?s(o):s;Object.is(o,l)||(a.value=l,xd(t))}};t.cells[r]=a}const n=t.cells[r];if(n.type!=="state")throw new Error("Hook order changed between renders");return n}function it(e){const t=vd(e);return[t.value,t.set]}function kd(){const e=$n(),t=e.currentIndex++;if(!e.isFirstRender&&t>=e.cells.length)throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");if(!e.cells[t]){const n={type:"effect",mounted:!1};e.cells[t]=n}if(e.cells[t].type!=="effect")throw new Error("Hook order changed between renders");return t}function De(e,t){const r=$n(),n=kd();r.renderContext.commitTasks.push({effect:e,deps:t,cellIndex:n})}function Ut(e){const[t]=it(()=>({current:e}));return t}var Sd=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Object.is(e[r],t[r]))return!1;return!0},ce=(e,t)=>{const r=Ut();return r.current||(r.current={value:e(),deps:t}),Sd(r.current.deps,t)||(r.current.value=e(),r.current.deps=t),r.current.value};function Yr(e,t){const[r,n]=it({}),i=ce(()=>Kr(e.type,()=>n({})),[e.type]),a=t?ce(()=>e.props,t):e.props,s=ce(()=>cr(i,a),[i,a,r]);return De(()=>()=>Bt(i),[i]),De(()=>{Rt(i,s)},[i,s]),s.state}function Qe(e){return Xa(e.type,e.props)}function es(e){const t=new Set;e.forEach((o,l)=>{if(o.key===void 0)throw new Error(`tapResources: All resource elements must have a key. Element at index ${l} is missing a key.`);if(t.has(o.key))throw new Error(`tapResources: Duplicate key "${o.key}" found. All keys must be unique.`);t.add(o.key)});const[r,n]=it({}),i=ce(()=>new Map(e.map(o=>[o.key,o])),[e]),[a]=it(()=>new Map),s=ce(()=>{const o=new Map,l=new Set;return i.forEach((u,d)=>{l.add(d);let c=a.get(d);(!c||c.resource!==u.type)&&(c&&Bt(c),c=Kr(u.type,()=>n({})),a.set(d,c));const f=cr(c,u.props);o.set(d,f)}),a.forEach((u,d)=>{l.has(d)||(Bt(u),a.delete(d))}),o},[i,r]);return De(()=>{s.forEach((o,l)=>{const u=a.get(l);u&&Rt(u,o)})},[s,a]),De(()=>()=>{a.forEach(o=>{Bt(o)}),a.clear()},[a]),ce(()=>e.map(o=>{var l;return(l=s.get(o.key))==null?void 0:l.state}),[e,s])}var qn=[],Vn=!1;function _d(){Vn=!1;const e=qn;qn=[];for(const t of e)try{t()}catch(r){console.error("Error in scheduled task:",r)}}function Td(e){qn.push(e),Vn||(Vn=!0,queueMicrotask(_d))}var Cd=(Lt=class{constructor(t){T(this,"_isDirty",!1);T(this,"_hasScheduledTask",!1);T(this,"_isFlushing",!1);this._task=t}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,!(this._hasScheduledTask||this._isFlushing)&&(this._hasScheduledTask=!0,Td(()=>{this._hasScheduledTask=!1,this.flushSync()}))}flushSync(){if(this._isFlushing)return;this._isFlushing=!0;let t=0;try{for(;this._isDirty;){if(t++,t>Lt.MAX_FLUSH_DEPTH)throw new Error("Maximum update depth exceeded. This can happen when a resource repeatedly calls setState inside tapEffect.");this._isDirty=!1,this._task()}}finally{this._isFlushing=!1}}},T(Lt,"MAX_FLUSH_DEPTH",50),Lt),Id=ye(({element:e,onUpdateInput:t,onFlushSync:r,onDispose:n})=>{const[i,a]=it(e.props),s=Qe({type:e.type,props:i}),o=Ut(new Set).current,l=Ut(s);return De(()=>{s!==l.current&&(l.current=s,o.forEach(d=>d()))}),ce(()=>({getState:()=>l.current,subscribe:d=>(o.add(d),()=>o.delete(d)),updateInput:d=>{t(),a(()=>d)},flushSync:r,dispose:n}),[])}),Ed=(e,t=!1)=>{let r=!t;const n={element:e,onUpdateInput:()=>{r||(r=!0,Rt(a,s))},onFlushSync:()=>{i.flushSync()},onDispose:()=>Bt(a)},i=new Cd(()=>{s=cr(a,n),r&&Rt(a,s)}),a=Kr(Id,()=>i.markDirty());let s=cr(a,n);return r&&Rt(a,s),s.state},dr=Symbol("tap.Context"),ts=e=>({[dr]:e}),rs=(e,t,r)=>{const n=e[dr];e[dr]=t;try{return r()}finally{e[dr]=n}},ns=e=>e[dr];const is=e=>{let t;const r=new Set,n=(u,d)=>{const c=typeof u=="function"?u(t):u;if(!Object.is(c,t)){const f=t;t=(d!=null?d:typeof c!="object"||c===null)?c:Object.assign({},t,c),r.forEach(h=>h(t,f))}},i=()=>t,o={setState:n,getState:i,getInitialState:()=>l,subscribe:u=>(r.add(u),()=>r.delete(u))},l=t=e(n,i,o);return o},Ad=(e=>e?is(e):is),Md=e=>e;function Pd(e,t=Md){const r=y.useSyncExternalStore(e.subscribe,y.useCallback(()=>t(e.getState()),[e,t]),y.useCallback(()=>t(e.getInitialState()),[e,t]));return y.useDebugValue(r),r}const as=e=>{const t=Ad(e),r=n=>Pd(t,n);return Object.assign(r,t),r},Ht=(e=>e?as(e):as);function ss(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function os(...e){return t=>{let r=!1;const n=e.map(i=>{const a=ss(i,t);return!r&&typeof a=="function"&&(r=!0),a});if(r)return()=>{for(let i=0;i<n.length;i++){const a=n[i];typeof a=="function"?a():ss(e[i],null)}}}}function Gr(...e){return Z.useCallback(os(...e),e)}var ls=ye(e=>{const t=ce(()=>Ed(e,!0),[e.type]);return De(()=>{t.updateInput(e.props)}),t}),Nd=class{constructor(e){this.getApi=e}get(e,t){return this.getApi()[t]}ownKeys(){return Object.keys(this.getApi())}has(e,t){return t in this.getApi()}getOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(this.getApi(),t)}set(){return!1}defineProperty(){return!1}deleteProperty(){return!1}},Ze=(e,t)=>{const r=Ut(e);De(()=>{r.current=e});const n=ce(()=>new Proxy({},new Nd(()=>r.current)),[]),i=t==null?void 0:t.key,a=e.getState();return ce(()=>({key:i,state:a,api:n}),[a,i])},yt=ye(e=>{const t=Ut(e.get);return De(()=>{t.current=e.get}),ce(()=>Me({source:e.source,query:e.query,get:()=>t.current()}),[e.source,JSON.stringify(e.query)])}),Ld=ye(e=>{const t=Yr(e.scopeElement);return ce(()=>[e.fieldName,t],[e.fieldName,t])}),Dd=ye(e=>{const o=e,{on:t,subscribe:r,flushSync:n}=o,i=H(o,["on","subscribe","flushSync"]),a=Ut({on:t,subscribe:r,flushSync:n});De(()=>{a.current={on:t,subscribe:r,flushSync:n}});const s=es(Object.entries(i).map(([l,u])=>Ld({fieldName:l,scopeElement:u},{key:l})));return ce(()=>{const l=Object.fromEntries(s),{on:u,subscribe:d,flushSync:c}=a.current;return u&&(l.on=(f,h)=>u(f,h)),d&&(l.subscribe=f=>d(f)),c&&(l.flushSync=()=>c()),l},[...s])}),us=ts(null),Od=(e,t)=>rs(us,e,t),cs=()=>{const e=ns(us);if(!e)throw new Error("Model context is not available in this context");return e},Fd=ye(({toolkit:e})=>{const[t,r]=it(()=>({tools:{}})),n=cs();De(()=>{if(!e)return;const a=[];for(const[l,u]of Object.entries(e))u.render&&a.push(i(l,u.render));const s=Object.entries(e).reduce((l,[u,d])=>{const h=d,{render:c}=h,f=H(h,["render"]);return l[u]=f,l},{}),o={getModelContext:()=>({tools:s})};return a.push(n.register(o)),()=>{a.forEach(l=>l())}},[e,n]);const i=(a,s)=>(r(o=>{var l;return I(m({},o),{tools:I(m({},o.tools),{[a]:[...(l=o.tools[a])!=null?l:[],s]})})}),()=>{r(o=>{var l,u;return I(m({},o),{tools:I(m({},o.tools),{[a]:(u=(l=o.tools[a])==null?void 0:l.filter(d=>d!==s))!=null?u:[]})})})});return Ze({getState:()=>t,setToolUI:i})}),zd=ye(()=>ce(()=>{const t=new Map;return{on:(r,n)=>{t.has(r)||t.set(r,new Set);const i=t.get(r);return i.add(n),()=>{i.delete(n),i.size===0&&t.delete(r)}},emit:(r,n)=>{const i=t.get(r),a=t.get("*");!i&&!a||queueMicrotask(()=>{if(i)for(const s of i)s(n);if(a)for(const s of a)s({event:r,payload:n})})}}},[])),ds=ts(null),Bd=(e,t)=>rs(ds,e,t),Wn=()=>{const e=ns(ds);if(!e)throw new Error("Events context is not available");return e},Rd=ye(()=>{const[e]=it(()=>({})),t=new Pn;return Ze({getState:()=>e,getModelContext:()=>t.getModelContext(),subscribe:r=>t.subscribe(r),register:r=>t.registerModelContextProvider(r)})}),jd=ye(({threads:e,modelContext:t,tools:r})=>{const n=Qe(zd()),{threads:i,tools:a,modelContext:s}=Bd(n,()=>{const l=Yr(t!=null?t:Rd(),[t]);return Od(l.api,()=>({modelContext:l,tools:Yr(r!=null?r:Fd({}),[r]),threads:Yr(e,[e])}))}),o=ce(()=>({threads:i.state,tools:a.state,modelContext:s.state}),[i.state,a.state,s.state]);return Ze({getState:()=>o,threads:i.api,tools:a.api,modelContext:s.api,on:n.on})}),$d=e=>{const t=()=>e.getState().api.threads.item("main");return{threads:Me({source:"root",query:{},get:()=>e.getState().api.threads}),tools:Me({source:"root",query:{},get:()=>e.getState().api.tools}),modelContext:Me({source:"root",query:{},get:()=>e.getState().api.modelContext}),thread:Me({source:"threads",query:{type:"main"},get:()=>e.getState().api.threads.thread("main")}),threadListItem:Me({source:"threads",query:{type:"main"},get:()=>t()}),composer:Me({source:"thread",query:{},get:()=>e.getState().api.threads.thread("main").composer}),on(r,n){const{event:i,scope:a}=jt(r);if(a==="*")return e.getState().api.on(i,n);if(Ct("thread",a)||Ct("thread-list-item",a)||Ct("composer",a))return e.getState().api.on(i,s=>{s.threadId===t().getState().id&&n(s)});throw new Error(`Event scope is not available in this component: ${a}`)},subscribe:e.subscribe,flushSync:e.flushSync}},Ud=e=>{const t=Xr(),r=Un(ls(jd(e))),n=y.useMemo(()=>$d(r),[r]);return y.useMemo(()=>fs(t,n),[t,n])},Me=e=>{const t=e.get;return t.source=e.source,t.query=e.query,t},bt=()=>()=>{},hs=y.createContext({threads:Me({source:null,query:{},get:()=>{throw new Error("Threads is only available inside <AssistantProvider />")}}),tools:Me({source:null,query:{},get:()=>{throw new Error("Tools is only available inside <AssistantProvider />")}}),modelContext:Me({source:null,query:{},get:()=>{throw new Error("ModelContext is only available inside <AssistantProvider />")}}),threadListItem:Me({source:null,query:{},get:()=>{throw new Error("ThreadListItem is only available inside <AssistantProvider />")}}),thread:Me({source:null,query:{},get:()=>{throw new Error("Thread is only available inside <AssistantProvider />")}}),composer:Me({source:null,query:{},get:()=>{throw new Error("Composer is only available inside <AssistantProvider />")}}),message:Me({source:null,query:{},get:()=>{throw new Error("Message is only available inside <ThreadPrimitive.Messages />")}}),part:Me({source:null,query:{},get:()=>{throw new Error("Part is only available inside <MessagePrimitive.Parts />")}}),attachment:Me({source:null,query:{},get:()=>{throw new Error("Attachment is only available inside <MessagePrimitive.Attachments /> or <ComposerPrimitive.Attachments />")}}),subscribe:bt,flushSync:bt,on:e=>{const{scope:t}=jt(e);throw new Error(`Event scope is not available in this component: ${t}`)}}),Xr=()=>y.useContext(hs),It=e=>{const t=Xr(),r=Un(Dd(e));return y.useMemo(()=>fs(t,r),[t,r])},Hd=e=>Ud(e);function pe(e){return e?Hd(e):Xr()}var qd=(e,t)=>e===bt?t:t===bt?e:(...r)=>{e(...r),t(...r)},Vd=(e,t)=>e===bt?t:t===bt?e:(...r)=>{const n=e(...r),i=t(...r);return()=>{n(),i()}},fs=(e,t)=>{const r=t.subscribe,n=t.flushSync;return I(m(m({},e),t),{subscribe:Vd(e.subscribe,r!=null?r:bt),flushSync:qd(e.flushSync,n!=null?n:bt)})},wt=({api:e,children:t,devToolsVisible:r=!0})=>(y.useEffect(()=>{if(!(!r||!e.subscribe))return wd.register(e)},[e,r]),p.jsx(hs.Provider,{value:e,children:t})),ps=(Nu=class{constructor(e){rr(this,Ke);nr(this,Ke,e)}get threads(){return We(this,Ke).threads().getState()}get tools(){return We(this,Ke).tools().getState()}get threadListItem(){return We(this,Ke).threadListItem().getState()}get thread(){return We(this,Ke).thread().getState()}get composer(){return We(this,Ke).composer().getState()}get message(){return We(this,Ke).message().getState()}get part(){return We(this,Ke).part().getState()}get attachment(){return We(this,Ke).attachment().getState()}},Ke=new WeakMap,Nu),ee=e=>{const t=pe(),r=y.useMemo(()=>new ps(t),[t]),n=y.useSyncExternalStore(t.subscribe,()=>e(r),()=>e(r));if(y.useDebugValue(n),n instanceof ps)throw new Error("You tried to return the entire AssistantState. This is not supported due to technical limitations.");return n},Jn=(e,t)=>{const r=pe(),n=y.useRef(t);y.useEffect(()=>{n.current=t});const{scope:i,event:a}=jt(e);y.useEffect(()=>r.on({scope:i,event:a},s=>n.current(s)),[r,i,a])};function Wd(e,t){function r(n){const i=y.useContext(e);if(!(n!=null&&n.optional)&&!i)throw new Error(`This component must be used within ${t}.`);return i}return r}function ms(e,t){function r(i){const a=e(i);return a?a[t]:null}function n(i){let a=!1,s;typeof i=="function"?s=i:i&&typeof i=="object"&&(a=!!i.optional,s=i.selector);const o=r({optional:a});return o?s?o(s):o():null}return{[t]:n,[`${t}Store`]:r}}var gs=y.createContext(null),Jd=Wd(gs,"ThreadPrimitive.Viewport"),{useThreadViewport:Qr,useThreadViewportStore:Kn}=ms(Jd,"useThreadViewport"),Kd=e=>{var r;const t=e;t.__isBound||((r=t.__internal_bindMethods)==null||r.call(t),t.__isBound=!0)};function Yd(e,t=Gd){Kd(e);const r=y.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getState()));return y.useDebugValue(r),r}var Gd=e=>e;function ys(e){function t(r){let n=!1,i;typeof r=="function"?i=r:r&&(n=!!r.optional,i=r.selector);const a=e({optional:n});return a?Yd(a,i):null}return t}function Xd(e){var n,i,a;const r=(a=(i=(n=pe().threads()).__internal_getAssistantRuntime)==null?void 0:i.call(n))!=null?a:null;if(!r)throw new Error("AssistantRuntime is not available");return r}function bs(e){const t=pe(),r=ee(()=>{var n,i,a;return t.thread.source&&(a=(i=(n=t.thread()).__internal_getRuntime)==null?void 0:i.call(n))!=null?a:null});if(!r&&!(e!=null&&e.optional))throw new Error("ThreadRuntime is not available");return r}var ws=ys(bs);function xs(e){const t=pe(),r=ee(()=>{var n,i,a;return t.threadListItem.source&&(a=(i=(n=t.threadListItem()).__internal_getRuntime)==null?void 0:i.call(n))!=null?a:null});if(!r&&!(e!=null&&e.optional))throw new Error("ThreadListItemRuntime is not available");return r}var vs=ys(xs),Et=e=>{const[,t]=it(e.getState);return De(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},Qd=ye(({runtime:e})=>{const t=Et(e),r=Wn();return De(()=>{const n=[],i=["switched-to","switched-away"];for(const a of i){const s=e.unstable_on(a,()=>{r.emit(`thread-list-item.${a}`,{threadId:e.getState().id})});n.push(s)}return()=>{for(const a of n)a()}},[e,r]),Ze({getState:()=>t,switchTo:e.switchTo,rename:e.rename,archive:e.archive,unarchive:e.unarchive,delete:e.delete,generateTitle:e.generateTitle,initialize:e.initialize,detach:e.detach,__internal_getRuntime:()=>e},{key:t.id})}),hr=e=>{const t=es(e);return{state:t.map(r=>r.state),api:r=>{var i,a;const n="index"in r?(i=t[r.index])==null?void 0:i.api:(a=t.find(s=>s.key===r.key))==null?void 0:a.api;if(!n)throw new Error(`tapLookupResources: Resource not found for lookup: ${JSON.stringify(r)}`);return n}}},ks=ye(({runtime:e})=>{const t=Et(e);return Ze({getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e},{key:t.id})}),Zd=ye(({runtime:e,index:t})=>{const r=ce(()=>e.getAttachmentByIndex(t),[e,t]);return Qe(ks({runtime:r}))}),Ss=ye(({threadIdRef:e,messageIdRef:t,runtime:r})=>{var o;const n=Et(r),i=Wn();De(()=>{const l=[],u=["send","attachment-add"];for(const d of u){const c=r.unstable_on(d,()=>{i.emit(`composer.${d}`,m({threadId:e.current},t&&{messageId:t.current}))});l.push(c)}return()=>{for(const d of l)d()}},[r,i,e,t]);const a=hr(n.attachments.map((l,u)=>Zd({runtime:r,index:u},{key:u}))),s=ce(()=>{var l;return{text:n.text,role:n.role,attachments:a.state,runConfig:n.runConfig,isEditing:n.isEditing,canCancel:n.canCancel,attachmentAccept:n.attachmentAccept,isEmpty:n.isEmpty,type:(l=n.type)!=null?l:"thread"}},[n,a.state]);return Ze({getState:()=>s,setText:r.setText,setRole:r.setRole,setRunConfig:r.setRunConfig,addAttachment:r.addAttachment,reset:r.reset,clearAttachments:r.clearAttachments,send:r.send,cancel:r.cancel,beginEdit:(o=r.beginEdit)!=null?o:(()=>{throw new Error("beginEdit is not supported in this runtime")}),attachment:l=>"id"in l?a.api({key:l.id}):a.api(l),__internal_getRuntime:()=>r})}),eh=ye(({runtime:e})=>{const t=Et(e);return Ze({getState:()=>t,addToolResult:n=>e.addToolResult(n),resumeToolCall:n=>e.resumeToolCall(n),__internal_getRuntime:()=>e},{key:t.type==="tool-call"?`toolCallId-${t.toolCallId}`:void 0})}),th=ye(({runtime:e,index:t})=>{const r=ce(()=>e.getAttachmentByIndex(t),[e,t]);return Qe(ks({runtime:r}))}),rh=ye(({runtime:e,index:t})=>{const r=ce(()=>e.getMessagePartByIndex(t),[e,t]);return Qe(eh({runtime:r}))}),nh=ye(({runtime:e,threadIdRef:t})=>{var f,h;const r=Et(e),[n,i]=it(!1),[a,s]=it(!1),o=ce(()=>({get current(){return e.getState().id}}),[e]),l=Qe(Ss({runtime:e.composer,threadIdRef:t,messageIdRef:o})),u=hr(r.content.map((g,x)=>rh({runtime:e,index:x},{key:x}))),d=hr((h=(f=r.attachments)==null?void 0:f.map((g,x)=>th({runtime:e,index:x},{key:x})))!=null?h:[]),c=ce(()=>I(m({},r),{parts:u.state,composer:l.state,isCopied:n,isHovering:a}),[r,u.state,l.state,n,a]);return Ze({getState:()=>c,composer:l.api,reload:g=>e.reload(g),speak:()=>e.speak(),stopSpeaking:()=>e.stopSpeaking(),submitFeedback:g=>e.submitFeedback(g),switchToBranch:g=>e.switchToBranch(g),getCopyText:()=>e.unstable_getCopyText(),part:g=>"index"in g?u.api({index:g.index}):u.api({key:`toolCallId-${g.toolCallId}`}),attachment:g=>"id"in g?d.api({key:g.id}):d.api(g),setIsCopied:i,setIsHovering:s,__internal_getRuntime:()=>e},{key:r.id})}),ih=ye(({runtime:e,id:t,threadIdRef:r})=>{const n=ce(()=>e.getMessageById(t),[e,t]);return Qe(nh({runtime:n,threadIdRef:r}))}),ah=ye(({runtime:e})=>{const t=Et(e),r=Wn();De(()=>{const o=[],l=["run-start","run-end","initialize","model-context-update"];for(const u of l){const d=e.unstable_on(u,()=>{var f;const c=((f=e.getState())==null?void 0:f.threadId)||"unknown";r.emit(`thread.${u}`,{threadId:c})});o.push(d)}return()=>{for(const u of o)u()}},[e]);const n=ce(()=>({get current(){return e.getState().threadId}}),[e]),i=Qe(Ss({runtime:e.composer,threadIdRef:n})),a=hr(t.messages.map(o=>ih({runtime:e,id:o.id,threadIdRef:n},{key:o.id}))),s=ce(()=>({isEmpty:a.state.length===0&&!t.isLoading,isDisabled:t.isDisabled,isLoading:t.isLoading,isRunning:t.isRunning,capabilities:t.capabilities,state:t.state,suggestions:t.suggestions,extras:t.extras,speech:t.speech,composer:i.state,messages:a.state}),[t,a,i.state]);return Ze({getState:()=>s,composer:i.api,append:e.append,startRun:e.startRun,unstable_resumeRun:e.unstable_resumeRun,cancelRun:e.cancelRun,getModelContext:e.getModelContext,export:e.export,import:e.import,reset:e.reset,stopSpeaking:e.stopSpeaking,startVoice:()=>M(null,null,function*(){throw new Error("startVoice is not supported in this runtime")}),stopVoice:()=>M(null,null,function*(){throw new Error("stopVoice is not supported in this runtime")}),message:o=>"id"in o?a.api({key:o.id}):a.api(o),__internal_getRuntime:()=>e})}),sh=ye(({runtime:e,id:t})=>{const r=ce(()=>e.getItemById(t),[e,t]);return Qe(Qd({runtime:r}))}),oh=ye(({runtime:e,__internal_assistantRuntime:t})=>{const r=Et(e),n=Qe(ah({runtime:e.main})),i=hr(Object.keys(r.threadItems).map(s=>sh({runtime:e,id:s},{key:s}))),a=ce(()=>{var s;return{mainThreadId:r.mainThreadId,newThreadId:(s=r.newThread)!=null?s:null,isLoading:r.isLoading,threadIds:r.threads,archivedThreadIds:r.archivedThreads,threadItems:i.state,main:n.state}},[r,i.state,n.state]);return Ze({getState:()=>a,thread:()=>n.api,item:s=>{if(s==="main")return i.api({key:a.mainThreadId});if("id"in s)return i.api({key:s.id});const{index:o,archived:l=!1}=s,u=l?a.archivedThreadIds[o]:a.threadIds[o];return i.api({key:u})},switchToThread:s=>{e.switchToThread(s)},switchToNewThread:()=>{e.switchToNewThread()},__internal_getAssistantRuntime:()=>t})}),lh=ye(e=>{const t=cs();return De(()=>e.registerModelContextProvider(t),[e,t]),Qe(oh({runtime:e.threads,__internal_assistantRuntime:e}))}),Yn=e=>{const t=new Map,r=()=>{let n=0;for(const i of t.values())n+=i;e(n)};return{register:()=>{const n=Symbol();return t.set(n,0),{setHeight:i=>{t.get(n)!==i&&(t.set(n,i),r())},unregister:()=>{t.delete(n),r()}}}}},uh=(e={})=>{const t=new Set,r=Yn(s=>{a.setState({height:I(m({},a.getState().height),{viewport:s})})}),n=Yn(s=>{a.setState({height:I(m({},a.getState().height),{inset:s})})}),i=Yn(s=>{a.setState({height:I(m({},a.getState().height),{userMessage:s})})}),a=Ht(()=>{var s;return{isAtBottom:!0,scrollToBottom:({behavior:o="auto"}={})=>{for(const l of t)l({behavior:o})},onScrollToBottom:o=>(t.add(o),()=>{t.delete(o)}),turnAnchor:(s=e.turnAnchor)!=null?s:"bottom",height:{viewport:0,inset:0,userMessage:0},registerViewport:r.register,registerContentInset:n.register,registerUserMessageHeight:i.register}});return a},fr=e=>e,ch=e=>{const t=Kn({optional:!0}),[r]=y.useState(()=>uh(e));return y.useEffect(()=>t==null?void 0:t.getState().onScrollToBottom(()=>{r.getState().scrollToBottom()}),[t,r]),y.useEffect(()=>{if(t)return r.subscribe(n=>{t.getState().isAtBottom!==n.isAtBottom&&fr(t).setState({isAtBottom:n.isAtBottom})})},[r,t]),y.useEffect(()=>{var a;const n={turnAnchor:(a=e.turnAnchor)!=null?a:"bottom"};r.getState().turnAnchor!==n.turnAnchor&&fr(r).setState(n)},[r,e.turnAnchor]),r},_s=({children:e,options:t={}})=>{const r=ch(t),[n]=y.useState(()=>({useThreadViewport:r}));return p.jsx(gs.Provider,{value:n,children:e})},dh=e=>{var t;return(t=e._core)==null?void 0:t.RenderComponent},hh=({children:e,runtime:t})=>{const r=pe({threads:lh(t)}),n=dh(t);return p.jsxs(wt,{api:r,children:[n&&p.jsx(n,{}),p.jsx(_s,{children:e})]})},Ts=y.memo(hh),fh=({index:e,archived:t,children:r})=>{const n=pe(),i=It({threadListItem:yt({source:"threads",query:{type:"index",index:e,archived:t},get:()=>n.threads().item({index:e,archived:t})}),on(a,s){const o=()=>n.threads().item({index:e,archived:t}),{event:l,scope:u}=jt(a);return Ct("thread-list-item",u)?n.on({scope:"*",event:l},d=>{d.threadId===o().getState().id&&s(d)}):n.on(a,s)}});return p.jsx(wt,{api:i,children:r})},ph=({id:e,children:t})=>{const r=pe(),n=It({threadListItem:yt({source:"threads",query:{type:"id",id:e},get:()=>r.threads().item({id:e})}),on(i,a){const s=()=>r.threads().item({id:e}),{event:o,scope:l}=jt(i);return Ct("thread-list-item",l)?r.on({scope:"*",event:o},u=>{u.threadId===s().getState().id&&a(u)}):r.on(i,a)}});return p.jsx(wt,{api:n,children:t})},mh=({index:e,children:t})=>{const r=pe(),n=It({message:yt({source:"thread",query:{type:"index",index:e},get:()=>r.thread().message({index:e})}),composer:yt({source:"message",query:{},get:()=>r.thread().message({index:e}).composer}),on(i,a){const s=()=>r.thread().message({index:e}),{event:o,scope:l}=jt(i);return!Ct("composer",l)&&!Ct("message",l)?r.on(i,a):r.on({scope:"thread",event:o},u=>{u.messageId===s().getState().id&&a(u)})}});return p.jsx(wt,{api:n,children:t})},gh=({index:e,children:t})=>{const r=pe(),n=It({part:yt({source:"message",query:{type:"index",index:e},get:()=>r.message().part({index:e})})});return p.jsx(wt,{api:n,children:t})},yh=({index:e,children:t})=>{const r=pe(),n=It({attachment:yt({source:"message",query:{type:"index",index:e},get:()=>r.message().attachment({index:e})})});return p.jsx(wt,{api:n,children:t})},bh=({index:e,children:t})=>{const r=pe(),n=It({attachment:yt({source:"composer",query:{type:"index",index:e},get:()=>r.composer().attachment({index:e})})});return p.jsx(wt,{api:n,children:t})},wh=ye(({text:e,isRunning:t})=>{const r=ce(()=>({type:"text",text:e,status:t?{type:"running"}:{type:"complete"}}),[e,t]);return Ze({getState:()=>r,addToolResult:()=>{throw new Error("Not supported")},resumeToolCall:()=>{throw new Error("Not supported")}})}),xh=({text:e,isRunning:t=!1,children:r})=>{const n=Un(ls(wh({text:e,isRunning:t}))),i=It({part:yt({source:"root",query:{},get:()=>n.getState().api}),subscribe:n.subscribe,flushSync:n.flushSync});return p.jsx(wt,{api:i,children:r})},Cs=(e,t)=>{var r,n;return t===void 0?((r=e.status)==null?void 0:r.type)==="requires-action"&&e.status.reason==="tool-calls"&&e.content.every(i=>i.type!=="tool-call"||!!i.result):((n=e.status)==null?void 0:n.type)==="requires-action"&&e.status.reason==="tool-calls"&&e.content.every(i=>i.type!=="tool-call"||!!i.result||!t.includes(i.toolName))},Gn=class extends Error{constructor(t,r){super(r);T(this,"name","AbortError");T(this,"detach");this.detach=t}},vh=class extends dd{constructor(t,r){super(t);T(this,"capabilities",{switchToBranch:!0,switchBranchDuringRun:!0,edit:!0,reload:!0,cancel:!0,unstable_copy:!0,speech:!1,attachments:!1,feedback:!1});T(this,"abortController",null);T(this,"isDisabled",!1);T(this,"_isLoading",!1);T(this,"_suggestions",[]);T(this,"_suggestionsController",null);T(this,"_options");T(this,"_lastRunConfig",{});T(this,"_loadPromise");this.__internal_setOptions(r)}get isLoading(){return this._isLoading}get suggestions(){return this._suggestions}get adapters(){return this._options.adapters}get extras(){}__internal_setOptions(t){var s,o,l;if(this._options===t)return;this._options=t;let r=!1;const n=((s=t.adapters)==null?void 0:s.speech)!==void 0;this.capabilities.speech!==n&&(this.capabilities.speech=n,r=!0);const i=((o=t.adapters)==null?void 0:o.attachments)!==void 0;this.capabilities.attachments!==i&&(this.capabilities.attachments=i,r=!0);const a=((l=t.adapters)==null?void 0:l.feedback)!==void 0;this.capabilities.feedback!==a&&(this.capabilities.feedback=a,r=!0),r&&this._notifySubscribers()}__internal_load(){var r,n;if(this._loadPromise)return this._loadPromise;const t=(n=(r=this.adapters.history)==null?void 0:r.load())!=null?n:Promise.resolve(null);return this._isLoading=!0,this._notifySubscribers(),this._loadPromise=t.then(i=>{var s,o;if(!i)return;this.repository.import(i),this._notifySubscribers();const a=(o=(s=this.adapters.history)==null?void 0:s.resume)==null?void 0:o.bind(this.adapters.history);i.unstable_resume&&a&&this.startRun({parentId:this.repository.headId,sourceId:this.repository.headId,runConfig:this._lastRunConfig},a)}).finally(()=>{this._isLoading=!1,this._notifySubscribers()}),this._loadPromise}append(t){return M(this,null,function*(){var i,a,s;this.ensureInitialized();const r=or(t,_t(),{type:"complete",reason:"unknown"});this.repository.addOrUpdateMessage(t.parentId,r),(i=this._options.adapters.history)==null||i.append(m({parentId:t.parentId,message:r},t.runConfig!==void 0&&{runConfig:t.runConfig})),((a=t.startRun)!=null?a:t.role==="user")?yield this.startRun({parentId:r.id,sourceId:t.sourceId,runConfig:(s=t.runConfig)!=null?s:{}}):(this.repository.resetHead(r.id),this._notifySubscribers())})}resumeRun(n){var i=n,{stream:t}=i,r=H(i,["stream"]);if(!t)throw new Error("You must pass a stream parameter to resume runs.");return this.startRun(r,t)}unstable_loadExternalState(){throw new Error("Runtime does not support importing external states.")}startRun(i,a){return M(this,arguments,function*({parentId:t,runConfig:r},n){var u,d,c;this.ensureInitialized();let o={id:_t(),role:"assistant",status:{type:"running"},content:[],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],custom:{}},createdAt:new Date};this._notifyEventSubscribers("run-start");try{this._suggestions=[],(u=this._suggestionsController)==null||u.abort(),this._suggestionsController=null,this._notifySubscribers();do o=yield this.performRoundtrip(t,o,r,n),n=void 0;while(Cs(o,this._options.unstable_humanToolNames))}finally{this._notifyEventSubscribers("run-end")}this._suggestionsController=new AbortController;const l=this._suggestionsController.signal;if(this.adapters.suggestion&&((d=o.status)==null?void 0:d.type)!=="requires-action"){const b=(c=this.adapters.suggestion)==null?void 0:c.generate({messages:this.messages});if(Symbol.asyncIterator in b)try{for(var f=Ft(b),h,g,x;h=!(g=yield f.next()).done;h=!1){const w=g.value;if(l.aborted)break;this._suggestions=w,this._notifySubscribers()}}catch(g){x=[g]}finally{try{h&&(g=f.return)&&(yield g.call(f))}finally{if(x)throw x[0]}}else{const w=yield b;if(l.aborted)return;this._suggestions=w,this._notifySubscribers()}}})}performRoundtrip(t,r,n,i){return M(this,null,function*(){var g,x,b,w,E,_,O,z,C,D;const a=t?this.repository.getMessages(t):[];(g=this.abortController)==null||g.abort(),this.abortController=new AbortController;const s=r.content,o=(x=r.metadata)==null?void 0:x.unstable_annotations,l=(b=r.metadata)==null?void 0:b.unstable_data,u=(w=r.metadata)==null?void 0:w.steps,d=(E=r.metadata)==null?void 0:E.custom,c=N=>{var se,v,Y,xe,k,Se;const K=(se=N.metadata)==null?void 0:se.steps,B=K?[...u!=null?u:[],...K]:void 0,P=(v=N.metadata)==null?void 0:v.unstable_annotations,q=(Y=N.metadata)==null?void 0:Y.unstable_data,J=P?[...o!=null?o:[],...P]:void 0,ue=q?[...l!=null?l:[],...q]:void 0;r=m(I(m(m({},r),N.content?{content:[...s,...(xe=N.content)!=null?xe:[]]}:void 0),{status:(k=N.status)!=null?k:r.status}),N.metadata?{metadata:m(m(m(m(m(m({},r.metadata),N.metadata.unstable_state?{unstable_state:N.metadata.unstable_state}:void 0),J?{unstable_annotations:J}:void 0),ue?{unstable_data:ue}:void 0),B?{steps:B}:void 0),(Se=N.metadata)!=null&&Se.custom?{custom:m(m({},d!=null?d:{}),N.metadata.custom)}:void 0)}:void 0),this.repository.addOrUpdateMessage(t,r),this._notifySubscribers()},f=(_=this._options.maxSteps)!=null?_:2;if(((C=(z=(O=r.metadata)==null?void 0:O.steps)==null?void 0:z.length)!=null?C:0)>=f)return c({status:{type:"incomplete",reason:"tool-calls"}}),r;c({status:{type:"running"}}),this.repository.resetHead(r.id),this._notifySubscribers();try{this._lastRunConfig=n!=null?n:{};const N=this.getModelContext();i=i!=null?i:this.adapters.chatModel.run.bind(this.adapters.chatModel);const K=this.abortController.signal,B=i({messages:a,runConfig:this._lastRunConfig,abortSignal:K,context:N,config:N,unstable_assistantMessageId:r.id,unstable_getMessage(){return r}});if(Symbol.asyncIterator in B)try{for(var U=Ft(B),V,R,S;V=!(R=yield U.next()).done;V=!1){const P=R.value;if(K.aborted){c({status:{type:"incomplete",reason:"cancelled"}});break}c(P)}}catch(R){S=[R]}finally{try{V&&(R=U.return)&&(yield R.call(U))}finally{if(S)throw S[0]}}else c(yield B);r.status.type==="running"&&c({status:{type:"complete",reason:"unknown"}})}catch(N){if(N instanceof Gn)c({status:{type:"incomplete",reason:"cancelled"}});else throw c({status:{type:"incomplete",reason:"error",error:N instanceof Error?N.message:`[${typeof N}] ${new String(N).toString()}`}}),N}finally{this.abortController=null,(r.status.type==="complete"||r.status.type==="incomplete")&&(yield(D=this._options.adapters.history)==null?void 0:D.append({parentId:t,message:r,runConfig:this._lastRunConfig}))}return r})}detach(){var r;const t=new Gn(!0);(r=this.abortController)==null||r.abort(t),this.abortController=null}cancelRun(){var r;const t=new Gn(!1);(r=this.abortController)==null||r.abort(t),this.abortController=null}addToolResult({messageId:t,toolCallId:r,result:n,isError:i,artifact:a}){const s=this.repository.getMessage(t),{parentId:o}=s;let{message:l}=s;if(l.role!=="assistant")throw new Error("Tried to add tool result to non-assistant message");let u=!1,d=!1;const c=l.content.map(f=>f.type!=="tool-call"||f.toolCallId!==r?f:(d=!0,f.result||(u=!0),I(m({},f),{result:n,artifact:a,isError:i})));if(!d)throw new Error("Tried to add tool result to non-existing tool call");l=I(m({},l),{content:c}),this.repository.addOrUpdateMessage(o,l),u&&Cs(l,this._options.unstable_humanToolNames)&&this.performRoundtrip(o,l,this._lastRunConfig)}resumeToolCall(t){throw new Error("Local runtime does not support resuming tool calls.")}},Is=Object.freeze([]),Xn="__DEFAULT_ID__",kh=Object.freeze({[Xn]:{id:Xn,remoteId:void 0,externalId:void 0,status:"regular",title:void 0}}),Sh=class extends ar{constructor(t){super();T(this,"_mainThread");this._mainThread=t()}get isLoading(){return!1}getMainThreadRuntimeCore(){return this._mainThread}get newThreadId(){throw new Error("Method not implemented.")}get threadIds(){throw Is}get archivedThreadIds(){throw Is}get mainThreadId(){return Xn}get threadData(){return kh}getThreadRuntimeCore(){throw new Error("Method not implemented.")}getLoadThreadsPromise(){throw new Error("Method not implemented.")}getItemById(t){if(t===this.mainThreadId)return{status:"regular",id:this.mainThreadId,remoteId:this.mainThreadId,externalId:void 0,title:void 0,isMain:!0};throw new Error("Method not implemented")}switchToThread(){return M(this,null,function*(){throw new Error("Method not implemented.")})}switchToNewThread(){throw new Error("Method not implemented.")}rename(){throw new Error("Method not implemented.")}archive(){throw new Error("Method not implemented.")}detach(){throw new Error("Method not implemented.")}unarchive(){throw new Error("Method not implemented.")}delete(){throw new Error("Method not implemented.")}initialize(t){return Promise.resolve({remoteId:t,externalId:void 0})}generateTitle(){throw new Error("Method not implemented.")}},_h=class extends Nn{constructor(t,r){super();T(this,"threads");T(this,"Provider");T(this,"_options");this._options=t,this.threads=new Sh(()=>new vh(this._contextProvider,this._options)),r&&this.threads.getMainThreadRuntimeCore().import(zn.fromArray(r))}},Es=e=>{try{const r=e.split(".")[1];if(!r)throw new Error("Invalid JWT format");let n=r.replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4!==0;)n+="=";const i=atob(n),s=JSON.parse(i).exp;if(!s||typeof s!="number")throw new Error('JWT does not contain a valid "exp" field');return s*1e3}catch(t){throw new Error(`Unable to determine the token expiry: ${t}`)}},As=(Lu=class{constructor(e){T(this,"strategy","jwt");T(this,"cachedToken",null);T(this,"tokenExpiry",null);rr(this,Er);nr(this,Er,e)}getAuthHeaders(){return M(this,null,function*(){const e=Date.now();if(this.cachedToken&&this.tokenExpiry&&this.tokenExpiry-e>30*1e3)return{Authorization:`Bearer ${this.cachedToken}`};const t=yield We(this,Er).call(this);return t?(this.cachedToken=t,this.tokenExpiry=Es(t),{Authorization:`Bearer ${t}`}):!1})}readAuthHeaders(e){const t=e.get("Authorization");if(!t)return;const[r,n]=t.split(" ");if(r!=="Bearer"||!n)throw new Error("Invalid auth header received");this.cachedToken=n,this.tokenExpiry=Es(n)}},Er=new WeakMap,Lu),Th=(Du=class{constructor(e,t,r){T(this,"strategy","api-key");rr(this,Ar);rr(this,Mr);rr(this,Pr);nr(this,Ar,e),nr(this,Mr,t),nr(this,Pr,r)}getAuthHeaders(){return M(this,null,function*(){return{Authorization:`Bearer ${We(this,Ar)}`,"Aui-User-Id":We(this,Mr),"Aui-Workspace-Id":We(this,Pr)}})}readAuthHeaders(){}},Ar=new WeakMap,Mr=new WeakMap,Pr=new WeakMap,Du),Zr="aui:refresh_token",Ch=class{constructor(e){T(this,"strategy","anon");T(this,"baseUrl");T(this,"jwtStrategy");this.baseUrl=e,this.jwtStrategy=new As(()=>M(this,null,function*(){const t=Date.now(),r=localStorage.getItem(Zr),n=r?JSON.parse(r):void 0;if(n)if(new Date(n.expires_at).getTime()-t>30*1e3){const u=yield fetch(`${this.baseUrl}/v1/auth/tokens/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:n.token})});if(u.ok){const d=yield u.json(),{access_token:c,refresh_token:f}=d;return f&&localStorage.setItem(Zr,JSON.stringify(f)),c}}else localStorage.removeItem(Zr);const i=yield fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:"POST"});if(!i.ok)return null;const a=yield i.json(),{access_token:s,refresh_token:o}=a;return!s||!o?null:(localStorage.setItem(Zr,JSON.stringify(o)),s)}))}getAuthHeaders(){return M(this,null,function*(){return this.jwtStrategy.getAuthHeaders()})}readAuthHeaders(e){this.jwtStrategy.readAuthHeaders(e)}},Ih=class extends Error{constructor(e){super(e),this.name="APIError"}},Eh=class{constructor(e){T(this,"_auth");T(this,"_baseUrl");if("authToken"in e)this._baseUrl=e.baseUrl,this._auth=new As(e.authToken);else if("apiKey"in e)this._baseUrl="https://backend.assistant-api.com",this._auth=new Th(e.apiKey,e.userId,e.workspaceId);else if("anonymous"in e)this._baseUrl=e.baseUrl,this._auth=new Ch(e.baseUrl);else throw new Error("Invalid configuration: Must provide authToken, apiKey, or anonymous configuration")}initializeAuth(){return M(this,null,function*(){return!!this._auth.getAuthHeaders()})}makeRawRequest(r){return M(this,arguments,function*(e,t={}){var l;const n=yield this._auth.getAuthHeaders();if(!n)throw new Error("Authorization failed");const i=I(m(m({},n),t.headers),{"Content-Type":"application/json"}),a=new URLSearchParams;if(t.query)for(const[u,d]of Object.entries(t.query))d!==!1&&(d===!0?a.set(u,"true"):a.set(u,d.toString()));const s=new URL(`${this._baseUrl}/v1${e}`);s.search=a.toString();const o=yield fetch(s,{method:(l=t.method)!=null?l:"GET",headers:i,body:t.body?JSON.stringify(t.body):null});if(this._auth.readAuthHeaders(o.headers),!o.ok){const u=yield o.text();try{const d=JSON.parse(u);throw new Ih(d.message)}catch(d){throw new Error(`Request failed with status ${o.status}, ${u}`)}}return o})}makeRequest(r){return M(this,arguments,function*(e,t={}){return(yield this.makeRawRequest(e,t)).json()})}},Ah=class{constructor(e){this.cloud=e}create(){return M(this,null,function*(){return this.cloud.makeRequest("/auth/tokens",{method:"POST"})})}},Mh=class{constructor(e){this.cloud=e}__internal_getAssistantOptions(e){return{api:`${this.cloud._baseUrl}/v1/runs/stream`,headers:()=>M(this,null,function*(){const t=yield this.cloud._auth.getAuthHeaders();if(!t)throw new Error("Authorization failed");return I(m({},t),{Accept:"text/plain"})}),body:{assistant_id:e,response_format:"vercel-ai-data-stream/v1",thread_id:"unstable_todo"}}}stream(e){return M(this,null,function*(){const t=yield this.cloud.makeRawRequest("/runs/stream",{method:"POST",headers:{Accept:"text/plain"},body:e});return On.fromResponse(t,new $c)})}},Ph=class{constructor(e){this.cloud=e}list(e,t){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{query:t})})}create(e,t){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{method:"POST",body:t})})}},Nh=class{constructor(e){T(this,"messages");this.cloud=e,this.messages=new Ph(e)}list(e){return M(this,null,function*(){return this.cloud.makeRequest("/threads",{query:e})})}get(e){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`)})}create(e){return M(this,null,function*(){return this.cloud.makeRequest("/threads",{method:"POST",body:e})})}update(e,t){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"PUT",body:t})})}delete(e){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"DELETE"})})}},Lh=class{constructor(e){this.cloud=e}pdfToImages(e){return M(this,null,function*(){return this.cloud.makeRequest("/files/pdf-to-images",{method:"POST",body:e})})}generatePresignedUploadUrl(e){return M(this,null,function*(){return this.cloud.makeRequest("/files/attachments/generate-presigned-upload-url",{method:"POST",body:e})})}},Dh=class{constructor(e){T(this,"threads");T(this,"auth");T(this,"runs");T(this,"files");const t=new Eh(e);this.threads=new Nh(t),this.auth={tokens:new Ah(t)},this.runs=new Mh(t),this.files=new Lh(t)}};function Qn(e,t=0){return t>100?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?!Number.isNaN(e)&&Number.isFinite(e):Array.isArray(e)?e.every(r=>Qn(r,t+1)):typeof e=="object"?Object.entries(e).every(([r,n])=>typeof r=="string"&&Qn(n,t+1)):!1}var Oh=e=>{var t;return m({role:e.role,content:e.content.map(r=>{const n=r.type;switch(n){case"text":return{type:"text",text:r.text};case"reasoning":return{type:"reasoning",text:r.text};case"source":return m({type:"source",sourceType:r.sourceType,id:r.id,url:r.url},r.title?{title:r.title}:void 0);case"tool-call":return Qn(r.result)||console.warn(`tool-call result is not JSON! ${JSON.stringify(r)}`),m(m(m({type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName},JSON.stringify(r.args)===r.argsText?{args:r.args}:{argsText:r.argsText}),r.result?{result:r.result}:{}),r.isError?{isError:!0}:{});default:{const i=n;throw new Error(`Message part type not supported by aui/v0: ${i}`)}}}),metadata:e.metadata},e.status?{status:((t=e.status)==null?void 0:t.type)==="running"?{type:"incomplete",reason:"cancelled"}:e.status}:void 0)},Fh=e=>{const t=e.content,r=or(m({id:e.id,createdAt:e.created_at},t),e.id,{type:"complete",reason:"unknown"});return{parentId:e.parent_id,message:r}},Zn=new WeakMap,zh=class{constructor(e,t){this.parent=e,this.formatAdapter=t}append(e){return M(this,null,function*(){const t=this.formatAdapter.encode(e),r=this.formatAdapter.getId(e.message);return this.parent._appendWithFormat(e.parentId,r,this.formatAdapter.format,t)})}load(){return M(this,null,function*(){return this.parent._loadWithFormat(this.formatAdapter.format,e=>this.formatAdapter.decode(e))})}},Bh=class{constructor(e,t){this.cloudRef=e,this.store=t}get _getIdForLocalId(){return Zn.has(this.store.threadListItem())||Zn.set(this.store.threadListItem(),{}),Zn.get(this.store.threadListItem())}withFormat(e){return new zh(this,e)}append(r){return M(this,arguments,function*({parentId:e,message:t}){var a;const{remoteId:n}=yield this.store.threadListItem().initialize(),i=this.cloudRef.current.threads.messages.create(n,{parent_id:e?(a=yield this._getIdForLocalId[e])!=null?a:e:null,format:"aui/v0",content:Oh(t)}).then(({message_id:s})=>(this._getIdForLocalId[t.id]=s,s));return this._getIdForLocalId[t.id]=i,i.then(()=>{})})}load(){return M(this,null,function*(){const e=this.store.threadListItem().getState().remoteId;if(!e)return{messages:[]};const{messages:t}=yield this.cloudRef.current.threads.messages.list(e,{format:"aui/v0"});return{messages:t.filter(n=>n.format==="aui/v0").map(Fh).reverse()}})}_appendWithFormat(e,t,r,n){return M(this,null,function*(){var s;const{remoteId:i}=yield this.store.threadListItem().initialize(),a=this.cloudRef.current.threads.messages.create(i,{parent_id:e?(s=yield this._getIdForLocalId[e])!=null?s:e:null,format:r,content:n}).then(({message_id:o})=>(this._getIdForLocalId[t]=o,o));return this._getIdForLocalId[t]=a,a.then(()=>{})})}_loadWithFormat(e,t){return M(this,null,function*(){const r=this.store.threadListItem().getState().remoteId;if(!r)return{messages:[]};const{messages:n}=yield this.cloudRef.current.threads.messages.list(r,{format:e});return{messages:n.filter(i=>i.format===e).map(i=>t({id:i.id,parent_id:i.parent_id,format:i.format,content:i.content})).reverse()}})}},Rh=e=>{const t=pe(),[r]=y.useState(()=>new Bh(e,t));return r},Ms=typeof process!="undefined"&&((Ou=process==null?void 0:process.env)==null?void 0:Ou.NEXT_PUBLIC_ASSISTANT_BASE_URL),ei=Ms?new Dh({baseUrl:Ms,anonymous:!0}):void 0,jh=e=>{var i;const t=y.useRef(e);y.useEffect(()=>{t.current=e},[e]);const r=y.useCallback(function({children:s}){var c;const o=Rh({get current(){var f;return(f=t.current.cloud)!=null?f:ei}}),l=(c=t.current.cloud)!=null?c:ei,u=y.useMemo(()=>new ld(l),[l]),d=y.useMemo(()=>({history:o,attachments:u}),[o,u]);return p.jsx(jn,{adapters:d,children:s})},[]),n=(i=e.cloud)!=null?i:ei;return n?{list:()=>M(null,null,function*(){const{threads:a}=yield n.threads.list();return{threads:a.map(s=>{var o;return{status:s.is_archived?"archived":"regular",remoteId:s.id,title:s.title,externalId:(o=s.external_id)!=null?o:void 0}})}}),initialize:()=>M(null,null,function*(){var u,d;const s=yield(d=(u=e.create)==null?void 0:u.call(e))!=null?d:Promise.resolve(),o=s?s.externalId:void 0,{thread_id:l}=yield n.threads.create({last_message_at:new Date,external_id:o});return{externalId:o,remoteId:l}}),rename:(a,s)=>M(null,null,function*(){return n.threads.update(a,{title:s})}),archive:a=>M(null,null,function*(){return n.threads.update(a,{is_archived:!0})}),unarchive:a=>M(null,null,function*(){return n.threads.update(a,{is_archived:!1})}),delete:a=>M(null,null,function*(){var s;return yield(s=e.delete)==null?void 0:s.call(e,a),n.threads.delete(a)}),generateTitle:(a,s)=>M(null,null,function*(){return n.runs.stream({thread_id:a,assistant_id:"system/thread_title",messages:s})}),fetch:a=>M(null,null,function*(){var o;const s=yield n.threads.get(a);return{status:s.is_archived?"archived":"regular",remoteId:s.id,title:s.title,externalId:(o=s.external_id)!=null?o:void 0}}),unstable_Provider:r}:new pd},$h=(e,n)=>{var i=n,{initialMessages:t}=i,r=H(i,["initialMessages"]);var u;const d=(u=ud())!=null?u:{},{modelContext:a}=d,s=H(d,["modelContext"]),o=y.useMemo(()=>I(m({},r),{adapters:I(m(m({},s),r.adapters),{chatModel:e})}),[e,r,s]),[l]=y.useState(()=>new _h(o,t));return y.useEffect(()=>()=>{l.threads.getMainThreadRuntimeCore().detach()},[l]),y.useEffect(()=>{l.threads.getMainThreadRuntimeCore().__internal_setOptions(o),l.threads.getMainThreadRuntimeCore().__internal_load()},[l,o]),y.useEffect(()=>{if(a)return l.registerModelContextProvider(a)},[a,l]),y.useMemo(()=>new ti(l),[l])},Ps=(e,n={})=>{var i=n,{cloud:t}=i,r=H(i,["cloud"]);const a=jh({cloud:t});return Fs({runtimeHook:function(){return $h(e,r)},adapter:a,allowNesting:!0})},ti=class{constructor(e){T(this,"threads");T(this,"_thread");this._core=e,this.threads=new sd(e.threads),this._thread=this.threads.main,this.__internal_bindMethods()}get threadList(){return this.threads}__internal_bindMethods(){this.switchToNewThread=this.switchToNewThread.bind(this),this.switchToThread=this.switchToThread.bind(this),this.registerModelContextProvider=this.registerModelContextProvider.bind(this),this.registerModelConfigProvider=this.registerModelConfigProvider.bind(this),this.reset=this.reset.bind(this)}get thread(){return this._thread}switchToNewThread(){return this._core.threads.switchToNewThread()}switchToThread(e){return this._core.threads.switchToThread(e)}registerModelContextProvider(e){return this._core.registerModelContextProvider(e)}registerModelConfigProvider(e){return this.registerModelContextProvider(e)}reset({initialMessages:e}={}){return this._core.threads.getMainThreadRuntimeCore().import(zn.fromArray(e!=null?e:[]))}},Uh=e=>{const o=e,{cloud:t,initialMessages:r,maxSteps:n,adapters:i,unstable_humanToolNames:a}=o,s=H(o,["cloud","initialMessages","maxSteps","adapters","unstable_humanToolNames"]);return{localRuntimeOptions:{cloud:t,initialMessages:r,maxSteps:n,adapters:i,unstable_humanToolNames:a},otherOptions:s}};function At(e){const t=Z.useRef(e);return Z.useEffect(()=>{t.current=e}),Z.useMemo(()=>(...r)=>{var n;return(n=t.current)==null?void 0:n.call(t,...r)},[])}var Ns=y.createContext(null),Hh=e=>({useSmoothStatus:Ht(()=>e)}),qh=({children:e})=>{const t=Ls({optional:!0}),r=pe(),[n]=y.useState(()=>Hh(r.part().getState().status));return t?e:p.jsx(Ns.Provider,{value:n,children:e})},Vh=e=>{const t=y.forwardRef((r,n)=>p.jsx(qh,{children:p.jsx(e,I(m({},r),{ref:n}))}));return t.displayName=e.displayName,t};function Ls(e){const t=y.useContext(Ns);if(!(e!=null&&e.optional)&&!t)throw new Error("This component must be used within a SmoothContextProvider.");return t}var{useSmoothStatus:Wh,useSmoothStatusStore:Jh}=ms(Ls,"useSmoothStatus"),Kh=class{constructor(e,t){T(this,"animationFrameId",null);T(this,"lastUpdateTime",Date.now());T(this,"targetText","");T(this,"animate",()=>{const e=Date.now();let r=e-this.lastUpdateTime;const n=this.targetText.length-this.currentText.length,i=Math.min(5,250/n);let a=0;for(;r>=i&&a<n;)a++,r-=i;a!==n?this.animationFrameId=requestAnimationFrame(this.animate):this.animationFrameId=null,a!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+a),this.lastUpdateTime=e-r,this.setText(this.currentText))});this.currentText=e,this.setText=t}start(){this.animationFrameId===null&&(this.lastUpdateTime=Date.now(),this.animate())}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}},ri=Object.freeze({type:"running"}),Ds=(e,t=!1)=>{const{text:r}=e,n=ee(({message:d})=>d.id),i=y.useRef(n),[a,s]=y.useState(r),o=Jh({optional:!0}),l=At(d=>{if(s(d),o){const c=a!==d||e.status.type==="running"?ri:e.status;fr(o).setState(c,!0)}});y.useEffect(()=>{if(o){const d=t&&(a!==r||e.status.type==="running")?ri:e.status;fr(o).setState(d,!0)}},[o,t,r,a,e.status]);const[u]=y.useState(new Kh(r,l));return y.useEffect(()=>{if(!t){u.stop();return}if(i.current!==n||!r.startsWith(u.targetText)){i.current=n,l(r),u.currentText=r,u.targetText=r,u.stop();return}u.targetText=r,u.start()},[l,u,n,t,r]),y.useEffect(()=>()=>{u.stop()},[u]),y.useMemo(()=>t?{type:"text",text:a,status:r===a?e.status:ri}:e,[t,a,e,r])};const Yh=Object.freeze(Object.defineProperty({__proto__:null,AssistantRuntimeImpl:ti,BaseAssistantRuntimeCore:Nn,CompositeContextProvider:Pn,DefaultThreadComposerRuntimeCore:va,MessageRepository:Fa,ThreadRuntimeImpl:Ga,fromThreadMessageLike:or,generateId:_t,getAutoStatus:Sa,splitLocalRuntimeOptions:Uh,useSmooth:Ds,useSmoothStatus:Wh,useToolInvocations:fd,withSmoothContextProvider:Vh},Symbol.toStringTag,{value:"Module"}));var Gh=class extends ar{constructor(t){super();T(this,"useRuntimeHook");T(this,"instances",new Map);T(this,"useAliveThreadsKeysChanged",Ht(()=>({})));T(this,"_InnerActiveThreadProvider",({threadId:t})=>{const{useRuntime:r}=this.useRuntimeHook(),n=r(),i=n.thread.__internal_threadBinding,a=y.useCallback(()=>{const l=this.instances.get(t);if(!l)throw new Error("Thread not found. This is a bug in assistant-ui.");l.runtime=i.getState(),this._notifySubscribers()},[t,i]),s=y.useRef(!1);s.current||a(),y.useEffect(()=>(s.current=!0,a(),i.outerSubscribe(a)),[i,a]);const o=pe();return y.useEffect(()=>n.threads.main.unstable_on("initialize",()=>{if(o.threadListItem().getState().status==="new"){o.threadListItem().initialize();const u=n.thread.unstable_on("run-end",()=>{u(),o.threadListItem().generateTitle()})}}),[n,o]),null});T(this,"_OuterActiveThreadProvider",y.memo(({threadId:t,provider:r})=>p.jsx(ph,{id:t,children:p.jsx(r,{children:p.jsx(this._InnerActiveThreadProvider,{threadId:t})})})));T(this,"__internal_RenderThreadRuntimes",({provider:t})=>(this.useAliveThreadsKeysChanged(),Array.from(this.instances.keys()).map(r=>p.jsx(this._OuterActiveThreadProvider,{threadId:r,provider:t},r))));this.useRuntimeHook=Ht(()=>({useRuntime:t}))}startThreadRuntime(t){return this.instances.has(t)||(this.instances.set(t,{}),this.useAliveThreadsKeysChanged.setState({},!0)),new Promise((r,n)=>{const i=()=>{const s=this.instances.get(t);if(!s)a(),n(new Error("Thread was deleted before runtime was started"));else if(s.runtime)a(),r(s.runtime);else return},a=this.subscribe(i);i()})}getThreadRuntimeCore(t){const r=this.instances.get(t);if(r)return r.runtime}stopThreadRuntime(t){this.instances.delete(t),this.useAliveThreadsKeysChanged.setState({},!0)}setRuntimeHook(t){this.useRuntimeHook.getState().useRuntime!==t&&this.useRuntimeHook.setState({useRuntime:t},!0)}},ve=new Error("This is the empty thread, a placeholder for the main thread. You cannot perform any actions on this thread instance. This error is probably because you tried to call a thread method in your render function. Call the method inside a `useEffect` hook instead."),Xh={getMessageById(){},getBranches(){return[]},switchToBranch(){throw ve},append(){throw ve},startRun(){throw ve},resumeRun(){throw ve},cancelRun(){throw ve},addToolResult(){throw ve},resumeToolCall(){throw ve},speak(){throw ve},stopSpeaking(){throw ve},submitFeedback(){throw ve},getModelContext(){return{}},unstable_loadExternalState(){throw ve},composer:{attachments:[],attachmentAccept:"*",addAttachment(){return M(this,null,function*(){throw ve})},removeAttachment(){return M(this,null,function*(){throw ve})},isEditing:!0,canCancel:!1,isEmpty:!0,text:"",setText(){throw ve},role:"user",setRole(){throw ve},runConfig:{},setRunConfig(){throw ve},reset(){return M(this,null,function*(){})},clearAttachments(){return M(this,null,function*(){})},send(){throw ve},cancel(){},subscribe(){return()=>{}},unstable_on(){return()=>{}}},getEditComposer(){},beginEdit(){throw ve},speech:void 0,capabilities:{switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,attachments:!1,feedback:!1},isDisabled:!1,isLoading:!1,messages:[],state:null,suggestions:[],extras:void 0,subscribe(){return()=>{}},import(){throw ve},export(){return{messages:[]}},reset(){throw ve},unstable_on(){return()=>{}}},Os=(e,t,r)=>r.reduce((n,i)=>{var a;return(a=i==null?void 0:i(n,t))!=null?a:n},e),Qh=class extends ar{constructor(t){super();T(this,"_pendingTransforms",[]);T(this,"_baseValue");T(this,"_cachedValue");this._baseValue=t,this._cachedValue=t}_updateState(){this._cachedValue=this._pendingTransforms.reduce((t,r)=>Os(t,r.task,[r.loading,r.optimistic]),this._baseValue),this._notifySubscribers()}get baseValue(){return this._baseValue}get value(){return this._cachedValue}update(t){this._baseValue=t,this._updateState()}optimisticUpdate(t){return M(this,null,function*(){const r=t.execute(),n=I(m({},t),{task:r});try{this._pendingTransforms.push(n),this._updateState();const i=yield r;return this._baseValue=Os(this._baseValue,i,[t.optimistic,t.then]),i}finally{const i=this._pendingTransforms.indexOf(n);i>-1&&this._pendingTransforms.splice(i,1),this._updateState()}})}};function Wv(e){return e}var en=(e,t)=>{const r=e.threadIdMap[t];if(r!==void 0)return e.threadData[r]},tn=(e,t,r)=>{const n=en(e,t);if(!n)return e;const{id:i,remoteId:a,status:s}=n;if(s===r)return e;const o=m({},e);switch(s){case"new":o.newThreadId=void 0;break;case"regular":o.threadIds=o.threadIds.filter(l=>l!==i);break;case"archived":o.archivedThreadIds=o.archivedThreadIds.filter(l=>l!==i);break;default:{const l=s;throw new Error(`Unsupported state: ${l}`)}}switch(r){case"regular":o.threadIds=[i,...o.threadIds];break;case"archived":o.archivedThreadIds=[i,...o.archivedThreadIds];break;case"deleted":o.threadData=Object.fromEntries(Object.entries(o.threadData).filter(([l])=>l!==i)),o.threadIdMap=Object.fromEntries(Object.entries(o.threadIdMap).filter(([l])=>l!==i&&l!==a));break;default:{const l=r;throw new Error(`Unsupported state: ${l}`)}}return r!=="deleted"&&(o.threadData=I(m({},o.threadData),{[i]:I(m({},n),{status:r})})),o},Zh=class extends ar{constructor(t,r){super();T(this,"_options");T(this,"_hookManager");T(this,"_loadThreadsPromise");T(this,"_mainThreadId");T(this,"_state",new Qh({isLoading:!1,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}}));T(this,"useProvider");T(this,"initialize",t=>M(this,null,function*(){if(this._state.value.newThreadId!==t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status==="new")throw new Error("Unexpected new state");return r.initializeTask}return this._state.optimisticUpdate({execute:()=>this._options.adapter.initialize(t),optimistic:r=>tn(r,t,"regular"),loading:(r,n)=>{const i=t;return I(m({},r),{threadData:I(m({},r.threadData),{[i]:I(m({},r.threadData[i]),{initializeTask:n})})})},then:(r,{remoteId:n,externalId:i})=>{const a=en(r,t);if(!a)return r;const s=t;return I(m({},r),{threadIdMap:I(m({},r.threadIdMap),{[n]:s}),threadData:I(m({},r.threadData),{[s]:I(m({},a),{initializeTask:Promise.resolve({remoteId:n,externalId:i}),remoteId:n,externalId:i})})})}})}));T(this,"generateTitle",t=>M(this,null,function*(){var l;const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status==="new")throw new Error("Thread is not yet initialized");const{remoteId:n}=yield r.initializeTask,i=this._hookManager.getThreadRuntimeCore(r.id);if(!i)return;const a=i.messages,s=yield this._options.adapter.generateTitle(n,a),o=Uc.fromAssistantStream(s);try{for(var u=Ft(o),d,c,f;d=!(c=yield u.next()).done;d=!1){const h=c.value;const g=(l=h.parts.filter(b=>b.type==="text")[0])==null?void 0:l.text,x=this._state.baseValue;this._state.update(I(m({},x),{threadData:I(m({},x.threadData),{[r.id]:I(m({},r),{title:g})})}))}}catch(c){f=[c]}finally{try{d&&(c=u.return)&&(yield c.call(u))}finally{if(f)throw f[0]}}}));T(this,"useBoundIds",Ht(()=>[]));T(this,"__internal_RenderComponent",()=>{const t=y.useId();y.useEffect(()=>(this.useBoundIds.setState(a=>[...a,t],!0),()=>{this.useBoundIds.setState(a=>a.filter(s=>s!==t),!0)}),[t]);const r=this.useBoundIds(),{Provider:n}=this.useProvider(),i={modelContext:this.contextProvider};return(r.length===0||r[0]===t)&&p.jsx(jn,{adapters:i,children:p.jsx(this._hookManager.__internal_RenderThreadRuntimes,{provider:n})})});this.contextProvider=r,this._state.subscribe(()=>this._notifySubscribers()),this._hookManager=new Gh(t.runtimeHook),this.useProvider=Ht(()=>{var n;return{Provider:(n=t.adapter.unstable_Provider)!=null?n:y.Fragment}}),this.__internal_setOptions(t),this.switchToNewThread()}get threadData(){return this._state.value.threadData}getLoadThreadsPromise(){return this._loadThreadsPromise||(this._loadThreadsPromise=this._state.optimisticUpdate({execute:()=>this._options.adapter.list(),loading:t=>I(m({},t),{isLoading:!0}),then:(t,r)=>{const n=[],i=[],a={},s={};for(const o of r.threads){switch(o.status){case"regular":n.push(o.remoteId);break;case"archived":i.push(o.remoteId);break;default:{const u=o.status;throw new Error(`Unsupported state: ${u}`)}}const l=o.remoteId;a[o.remoteId]=l,s[l]={id:o.remoteId,remoteId:o.remoteId,externalId:o.externalId,status:o.status,title:o.title,initializeTask:Promise.resolve({remoteId:o.remoteId,externalId:o.externalId})}}return I(m({},t),{threadIds:n,archivedThreadIds:i,threadIdMap:m(m({},t.threadIdMap),a),threadData:m(m({},t.threadData),s)})}}).then(()=>{})),this._loadThreadsPromise}__internal_setOptions(t){var n;if(this._options===t)return;this._options=t;const r=(n=t.adapter.unstable_Provider)!=null?n:y.Fragment;r!==this.useProvider.getState().Provider&&this.useProvider.setState({Provider:r},!0),this._hookManager.setRuntimeHook(t.runtimeHook)}__internal_load(){this.getLoadThreadsPromise()}get isLoading(){return this._state.value.isLoading}get threadIds(){return this._state.value.threadIds}get archivedThreadIds(){return this._state.value.archivedThreadIds}get newThreadId(){return this._state.value.newThreadId}get mainThreadId(){return this._mainThreadId}getMainThreadRuntimeCore(){const t=this._hookManager.getThreadRuntimeCore(this._mainThreadId);return t||Xh}getThreadRuntimeCore(t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");const n=this._hookManager.getThreadRuntimeCore(r.id);if(!n)throw new Error("Thread not found");return n}getItemById(t){return en(this._state.value,t)}switchToThread(t){return M(this,null,function*(){let r=this.getItemById(t);if(!r){const i=yield this._options.adapter.fetch(t),a=this._state.value,s=i.remoteId,o=I(m({},a.threadData),{[s]:{id:s,initializeTask:Promise.resolve({remoteId:i.remoteId,externalId:i.externalId}),remoteId:i.remoteId,externalId:i.externalId,status:i.status,title:i.title}}),l=I(m({},a.threadIdMap),{[i.remoteId]:s}),u=i.status==="regular"?[...a.threadIds,i.remoteId]:a.threadIds,d=i.status==="archived"?[...a.archivedThreadIds,i.remoteId]:a.archivedThreadIds;this._state.update(I(m({},a),{threadIds:u,archivedThreadIds:d,threadIdMap:l,threadData:o})),r=this.getItemById(t)}if(!r)throw new Error("Thread not found");if(this._mainThreadId===r.id)return;const n=this._hookManager.startThreadRuntime(r.id);this.mainThreadId!==void 0?yield n:n.then(()=>this._notifySubscribers()),r.status==="archived"&&(yield this.unarchive(r.id)),this._mainThreadId=r.id,this._notifySubscribers()})}switchToNewThread(){return M(this,null,function*(){for(;this._state.baseValue.newThreadId!==void 0&&this._state.value.newThreadId===void 0;)yield this._state.waitForUpdate();const t=this._state.value;let r=this._state.value.newThreadId;if(r===void 0){do r=`__LOCALID_${_t()}`;while(t.threadIdMap[r]);const n=r;this._state.update(I(m({},t),{newThreadId:r,threadIdMap:I(m({},t.threadIdMap),{[r]:n}),threadData:I(m({},t.threadData),{[n]:{status:"new",id:r,remoteId:void 0,externalId:void 0,title:void 0}})}))}return this.switchToThread(r)})}rename(t,r){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status==="new")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:()=>M(this,null,function*(){const{remoteId:i}=yield n.initializeTask;return this._options.adapter.rename(i,r)}),optimistic:i=>{const a=en(i,t);return a?I(m({},i),{threadData:I(m({},i.threadData),{[a.id]:I(m({},a),{title:r})})}):i}})}_ensureThreadIsNotMain(t){return M(this,null,function*(){if(t===this.newThreadId)throw new Error("Cannot ensure new thread is not main");t===this._mainThreadId&&(yield this.switchToNewThread())})}archive(t){return M(this,null,function*(){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular")throw new Error("Thread is not yet initialized or already archived");return this._state.optimisticUpdate({execute:()=>M(this,null,function*(){yield this._ensureThreadIsNotMain(r.id);const{remoteId:n}=yield r.initializeTask;return this._options.adapter.archive(n)}),optimistic:n=>tn(n,r.id,"archived")})})}unarchive(t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="archived")throw new Error("Thread is not archived");return this._state.optimisticUpdate({execute:()=>M(this,null,function*(){try{const{remoteId:n}=yield r.initializeTask;return yield this._options.adapter.unarchive(n)}catch(n){throw yield this._ensureThreadIsNotMain(r.id),n}}),optimistic:n=>tn(n,r.id,"regular")})}delete(t){return M(this,null,function*(){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular"&&r.status!=="archived")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:()=>M(this,null,function*(){yield this._ensureThreadIsNotMain(r.id);const{remoteId:n}=yield r.initializeTask;return yield this._options.adapter.delete(n)}),optimistic:n=>tn(n,r.id,"deleted")})})}detach(t){return M(this,null,function*(){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular"&&r.status!=="archived")throw new Error("Thread is not yet initialized");yield this._ensureThreadIsNotMain(r.id),this._hookManager.stopThreadRuntime(r.id)})}},ef=class extends Nn{constructor(t){super();T(this,"threads");this.threads=new Zh(t,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}},tf=e=>{const[t]=y.useState(()=>new ef(e));return y.useEffect(()=>{t.threads.__internal_setOptions(e),t.threads.__internal_load()},[t,e]),y.useMemo(()=>new ti(t),[t])},Fs=e=>{if(Xr().threadListItem.source!==null){if(!e.allowNesting)throw new Error("useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. Set allowNesting: true to allow nesting (the inner runtime will become a no-op).");return e.runtimeHook()}return tf(e)},rf=Symbol.for("react.lazy"),rn=Z[" use ".trim().toString()];function nf(e){return typeof e=="object"&&e!==null&&"then"in e}function zs(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===rf&&"_payload"in e&&nf(e._payload)}function Bs(e){const t=af(e),r=Z.forwardRef((n,i)=>{let u=n,{children:a}=u,s=H(u,["children"]);zs(a)&&typeof rn=="function"&&(a=rn(a._payload));const o=Z.Children.toArray(a),l=o.find(of);if(l){const d=l.props.children,c=o.map(f=>f===l?Z.Children.count(d)>1?Z.Children.only(null):Z.isValidElement(d)?d.props.children:null:f);return p.jsx(t,I(m({},s),{ref:i,children:Z.isValidElement(d)?Z.cloneElement(d,void 0,c):null}))}return p.jsx(t,I(m({},s),{ref:i,children:a}))});return r.displayName=`${e}.Slot`,r}var ni=Bs("Slot");function af(e){const t=Z.forwardRef((r,n)=>{let s=r,{children:i}=s,a=H(s,["children"]);if(zs(i)&&typeof rn=="function"&&(i=rn(i._payload)),Z.isValidElement(i)){const o=uf(i),l=lf(a,i.props);return i.type!==Z.Fragment&&(l.ref=n?os(n,o):o),Z.cloneElement(i,l)}return Z.Children.count(i)>1?Z.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var sf=Symbol("radix.slottable");function of(e){return Z.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===sf}function lf(e,t){const r=m({},t);for(const n in t){const i=e[n],a=t[n];/^on[A-Z]/.test(n)?i&&a?r[n]=(...o)=>{const l=a(...o);return i(...o),l}:i&&(r[n]=i):n==="style"?r[n]=m(m({},i),a):n==="className"&&(r[n]=[i,a].filter(Boolean).join(" "))}return m(m({},e),r)}function uf(e){var n,i;let t=(n=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:n.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=(i=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:i.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var cf=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ut=cf.reduce((e,t)=>{const r=Bs(`Primitive.${t}`),n=Z.forwardRef((i,a)=>{const u=i,{asChild:s}=u,o=H(u,["asChild"]),l=s?r:t;return typeof window!="undefined"&&(window[Symbol.for("radix-ui")]=!0),p.jsx(l,I(m({},o),{ref:a}))});return n.displayName=`Primitive.${t}`,I(m({},e),{[t]:n})},{});function qt(e,t,{checkForDefaultPrevented:r=!0}={}){return function(i){if(e==null||e(i),r===!1||!i.defaultPrevented)return t==null?void 0:t(i)}}var nn=(e,t,r=[])=>{const n=y.forwardRef((i,a)=>{var u;const s={},o={};Object.keys(i).forEach(d=>{r.includes(d)?s[d]=i[d]:o[d]=i[d]});const l=(u=t(s))!=null?u:void 0;return p.jsx(ut.button,I(m({type:"button"},o),{ref:a,disabled:o.disabled||!l,onClick:qt(o.onClick,l)}))});return n.displayName=e,n};function df(e,t=globalThis==null?void 0:globalThis.document){const r=At(e);Z.useEffect(()=>{const n=i=>{i.key==="Escape"&&r(i)};return t.addEventListener("keydown",n,{capture:!0}),()=>t.removeEventListener("keydown",n,{capture:!0})},[r,t])}var hf=()=>{const e=pe();return y.useCallback(()=>{e.attachment().remove()},[e])},ff=nn("AttachmentPrimitive.Remove",hf),pr=e=>{const t=y.useRef(void 0);return y.useCallback(n=>{t.current&&t.current(),n&&(t.current=e(n))},[e])},Rs=(e,t)=>{const r=y.useCallback(n=>{if(!e)return;const i=e(),a=()=>{const o=t?t(n):n.offsetHeight;i.setHeight(o)},s=new ResizeObserver(a);return s.observe(n),a(),()=>{s.disconnect(),i.unregister()}},[e,t]);return pr(r)},js=y.createContext(!1),$s=(e,t)=>{const r=e.match(/^([\d.]+)(em|px|rem)$/);if(!r)return 0;const n=parseFloat(r[1]),i=r[2];if(i==="px")return n;if(i==="em"){const a=parseFloat(getComputedStyle(t).fontSize)||16;return n*a}if(i==="rem"){const a=parseFloat(getComputedStyle(document.documentElement).fontSize)||16;return n*a}return 0},Us=({children:e,fillClampThreshold:t="10em",fillClampOffset:r="6em"})=>{const n=ee(({message:l})=>l.isLast&&l.index>=2),i=Kn({optional:!0}),a=y.useContext(js),s=y.useCallback(l=>{if(!i||a)return;const u=()=>{const d=i.getState();if(d.turnAnchor==="top"&&n){const{viewport:c,inset:f,userMessage:h}=d.height,g=$s(t,l),x=$s(r,l),b=h<=g?h:x,w=Math.max(0,c-f-b);l.style.minHeight=`${w}px`,l.style.flexShrink="0",l.style.transition="min-height 0s"}else l.style.minHeight="",l.style.flexShrink="",l.style.transition=""};return u(),i.subscribe(u)},[i,n,a,t,r]),o=pr(s);return p.jsx(js.Provider,{value:!0,children:p.jsx(ni,{ref:o,children:e})})};Us.displayName="ThreadPrimitive.ViewportSlack";var pf=()=>{const e=pe(),t=ee(()=>e.message()),r=y.useCallback(n=>{const i=()=>{t.setIsHovering(!0)},a=()=>{t.setIsHovering(!1)};return n.addEventListener("mouseenter",i),n.addEventListener("mouseleave",a),n.matches(":hover")&&t.setIsHovering(!0),()=>{n.removeEventListener("mouseenter",i),n.removeEventListener("mouseleave",a),t.setIsHovering(!1)}},[t]);return pr(r)},mf=()=>{const e=Qr(i=>i.turnAnchor),t=Qr(i=>i.registerUserMessageHeight),r=ee(({thread:i,message:a})=>{var s;return e==="top"&&a.role==="user"&&a.index===i.messages.length-2&&((s=i.messages.at(-1))==null?void 0:s.role)==="assistant"}),n=y.useCallback(i=>i.offsetHeight,[]);return Rs(r?t:null,n)},ii=y.forwardRef((e,t)=>{const r=pf(),n=mf(),i=Gr(t,r,n);return p.jsx(Us,{children:p.jsx(ut.div,I(m({},e),{ref:i}))})});ii.displayName="MessagePrimitive.Root";var Hs=()=>ee(({part:t})=>{if(t.type!=="text"&&t.type!=="reasoning")throw new Error("MessagePartText can only be used inside text or reasoning message parts.");return t}),qs=y.forwardRef((i,n)=>{var a=i,{smooth:e=!0,component:t="span"}=a,r=H(a,["smooth","component"]);const{text:s,status:o}=Ds(Hs(),e);return p.jsx(t,I(m({"data-status":o.type},r),{ref:n,children:s}))});qs.displayName="MessagePartPrimitive.Text";var gf=()=>ee(({part:t})=>{if(t.type!=="image")throw new Error("MessagePartImage can only be used inside image message parts.");return t}),Vs=y.forwardRef((e,t)=>{const{image:r}=gf();return p.jsx(ut.img,I(m({src:r},e),{ref:t}))});Vs.displayName="MessagePartPrimitive.Image";var Ws=({children:e})=>ee(({part:r})=>r.status.type==="running")?e:null;Ws.displayName="MessagePartPrimitive.InProgress";const Js=e=>Symbol.iterator in e,Ks=e=>"entries"in e,Ys=(e,t)=>{const r=e instanceof Map?e:new Map(e.entries()),n=t instanceof Map?t:new Map(t.entries());if(r.size!==n.size)return!1;for(const[i,a]of r)if(!n.has(i)||!Object.is(a,n.get(i)))return!1;return!0},yf=(e,t)=>{const r=e[Symbol.iterator](),n=t[Symbol.iterator]();let i=r.next(),a=n.next();for(;!i.done&&!a.done;){if(!Object.is(i.value,a.value))return!1;i=r.next(),a=n.next()}return!!i.done&&!!a.done};function bf(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:Js(e)&&Js(t)?Ks(e)&&Ks(t)?Ys(e,t):yf(e,t):Ys({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function wf(e){const t=y.useRef(void 0);return r=>{const n=e(r);return bf(t.current,n)?t.current:t.current=n}}var Gs=e=>{let t=-1;return{startGroup:r=>{t===-1&&(t=r)},endGroup:(r,n)=>{t!==-1&&(n.push({type:e,startIndex:t,endIndex:r}),t=-1)},finalize:(r,n)=>{t!==-1&&n.push({type:e,startIndex:t,endIndex:r})}}},xf=e=>{const t=[],r=Gs("toolGroup"),n=Gs("reasoningGroup");for(let i=0;i<e.length;i++){const a=e[i];a==="tool-call"?(n.endGroup(i-1,t),r.startGroup(i)):a==="reasoning"?(r.endGroup(i-1,t),n.startGroup(i)):(r.endGroup(i-1,t),n.endGroup(i-1,t),t.push({type:"single",index:i}))}return r.finalize(e.length-1,t),n.finalize(e.length-1,t),t},vf=()=>{const e=ee(wf(t=>t.message.parts.map(r=>r.type)));return y.useMemo(()=>e.length===0?[]:xf(e),[e])},kf=r=>{var n=r,{Fallback:e}=n,t=H(n,["Fallback"]);const i=ee(({tools:a})=>{var o,l;const s=(o=a.tools[t.toolName])!=null?o:e;return Array.isArray(s)?(l=s[0])!=null?l:e:s});return i?p.jsx(i,m({},t)):null},ct={Text:()=>p.jsxs("p",{style:{whiteSpace:"pre-line"},children:[p.jsx(qs,{}),p.jsx(Ws,{children:p.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>p.jsx(Vs,{}),File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},Sf=({components:{Text:e=ct.Text,Reasoning:t=ct.Reasoning,Image:r=ct.Image,Source:n=ct.Source,File:i=ct.File,Unstable_Audio:a=ct.Unstable_Audio,tools:s={}}={}})=>{var d,c,f;const o=pe(),l=ee(({part:h})=>h),u=l.type;if(u==="tool-call"){const h=o.part().addToolResult,g=o.part().resumeToolCall;if("Override"in s)return p.jsx(s.Override,I(m({},l),{addResult:h,resume:g}));const x=(c=(d=s.by_name)==null?void 0:d[l.toolName])!=null?c:s.Fallback;return p.jsx(kf,I(m({},l),{Fallback:x,addResult:h,resume:g}))}if(((f=l.status)==null?void 0:f.type)==="requires-action")throw new Error("Encountered unexpected requires-action status");switch(u){case"text":return p.jsx(e,m({},l));case"reasoning":return p.jsx(t,m({},l));case"source":return p.jsx(n,m({},l));case"image":return p.jsx(r,m({},l));case"file":return p.jsx(i,m({},l));case"audio":return p.jsx(a,m({},l));case"data":return null;default:const h=u;throw new Error(`Unknown message part type: ${h}`)}},an=y.memo(({index:e,components:t})=>p.jsx(gh,{index:e,children:p.jsx(Sf,{components:t})}),(e,t)=>{var r,n,i,a,s,o,l,u,d,c,f,h,g,x,b,w,E,_;return e.index===t.index&&((r=e.components)==null?void 0:r.Text)===((n=t.components)==null?void 0:n.Text)&&((i=e.components)==null?void 0:i.Reasoning)===((a=t.components)==null?void 0:a.Reasoning)&&((s=e.components)==null?void 0:s.Source)===((o=t.components)==null?void 0:o.Source)&&((l=e.components)==null?void 0:l.Image)===((u=t.components)==null?void 0:u.Image)&&((d=e.components)==null?void 0:d.File)===((c=t.components)==null?void 0:c.File)&&((f=e.components)==null?void 0:f.Unstable_Audio)===((h=t.components)==null?void 0:h.Unstable_Audio)&&((g=e.components)==null?void 0:g.tools)===((x=t.components)==null?void 0:x.tools)&&((b=e.components)==null?void 0:b.ToolGroup)===((w=t.components)==null?void 0:w.ToolGroup)&&((E=e.components)==null?void 0:E.ReasoningGroup)===((_=t.components)==null?void 0:_.ReasoningGroup)});an.displayName="MessagePrimitive.PartByIndex";var _f=({status:e,component:t})=>p.jsx(xh,{text:"",isRunning:e.type==="running",children:p.jsx(t,{type:"text",text:"",status:e})}),Tf=Object.freeze({type:"complete"}),Cf=({components:e})=>{var r;const t=ee(n=>{var i;return(i=n.message.status)!=null?i:Tf});return e!=null&&e.Empty?p.jsx(e.Empty,{status:t}):p.jsx(_f,{status:t,component:(r=e==null?void 0:e.Text)!=null?r:ct.Text})},If=y.memo(Cf,(e,t)=>{var r,n,i,a;return((r=e.components)==null?void 0:r.Empty)===((n=t.components)==null?void 0:n.Empty)&&((i=e.components)==null?void 0:i.Text)===((a=t.components)==null?void 0:a.Text)}),ai=({components:e})=>{const t=ee(({message:i})=>i.parts.length),r=vf(),n=y.useMemo(()=>t===0?p.jsx(If,{components:e}):r.map(i=>{var a,s;if(i.type==="single")return p.jsx(an,{index:i.index,components:e},i.index);if(i.type==="toolGroup"){const o=(a=e==null?void 0:e.ToolGroup)!=null?a:ct.ToolGroup;return p.jsx(o,{startIndex:i.startIndex,endIndex:i.endIndex,children:Array.from({length:i.endIndex-i.startIndex+1},(l,u)=>p.jsx(an,{index:i.startIndex+u,components:e},u))},`tool-${i.startIndex}`)}else{const o=(s=e==null?void 0:e.ReasoningGroup)!=null?s:ct.ReasoningGroup;return p.jsx(o,{startIndex:i.startIndex,endIndex:i.endIndex,children:Array.from({length:i.endIndex-i.startIndex+1},(l,u)=>p.jsx(an,{index:i.startIndex+u,components:e},u))},`reasoning-${i.startIndex}`)}}),[r,e,t]);return p.jsx(p.Fragment,{children:n})};ai.displayName="MessagePrimitive.Parts";var Ef=(e,t)=>{var n,i,a;const r=t.type;switch(r){case"image":return(n=e==null?void 0:e.Image)!=null?n:e==null?void 0:e.Attachment;case"document":return(i=e==null?void 0:e.Document)!=null?i:e==null?void 0:e.Attachment;case"file":return(a=e==null?void 0:e.File)!=null?a:e==null?void 0:e.Attachment;default:const s=r;throw new Error(`Unknown attachment type: ${s}`)}},Af=({components:e})=>{const t=ee(({attachment:n})=>n);if(!t)return null;const r=Ef(e,t);return r?p.jsx(r,{}):null},Xs=y.memo(({index:e,components:t})=>p.jsx(yh,{index:e,children:p.jsx(Af,{components:t})}),(e,t)=>{var r,n,i,a,s,o,l,u;return e.index===t.index&&((r=e.components)==null?void 0:r.Image)===((n=t.components)==null?void 0:n.Image)&&((i=e.components)==null?void 0:i.Document)===((a=t.components)==null?void 0:a.Document)&&((s=e.components)==null?void 0:s.File)===((o=t.components)==null?void 0:o.File)&&((l=e.components)==null?void 0:l.Attachment)===((u=t.components)==null?void 0:u.Attachment)});Xs.displayName="MessagePrimitive.AttachmentByIndex";var Qs=({components:e})=>{const t=ee(({message:n})=>n.role!=="user"?0:n.attachments.length);return y.useMemo(()=>Array.from({length:t},(n,i)=>p.jsx(Xs,{index:i,components:e},i)),[t,e])};Qs.displayName="MessagePrimitive.Attachments";var Zs=()=>{const e=pe(),t=ee(n=>n.thread.isRunning||!n.composer.isEditing||n.composer.isEmpty),r=y.useCallback(()=>{e.composer().send()},[e]);return t?null:r},Mf=nn("ComposerPrimitive.Send",Zs),eo=y.forwardRef((n,r)=>{var i=n,{onSubmit:e}=i,t=H(i,["onSubmit"]);const a=Zs(),s=o=>{o.preventDefault(),a&&a()};return p.jsx(ut.form,I(m({},t),{ref:r,onSubmit:qt(e,s)}))});eo.displayName="ComposerPrimitive.Root";function si(){return si=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},si.apply(null,arguments)}function Pf(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}var Nf=y.useLayoutEffect,Lf=function(t){var r=y.useRef(t);return Nf(function(){r.current=t}),r},to=function(t,r){if(typeof t=="function"){t(r);return}t.current=r},Df=function(t,r){var n=y.useRef();return y.useCallback(function(i){t.current=i,n.current&&to(n.current,null),n.current=r,r&&to(r,i)},[r])},ro={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},Of=function(t){Object.keys(ro).forEach(function(r){t.style.setProperty(r,ro[r],"important")})},no=Of,Oe=null,io=function(t,r){var n=t.scrollHeight;return r.sizingStyle.boxSizing==="border-box"?n+r.borderSize:n-r.paddingSize};function Ff(e,t,r,n){r===void 0&&(r=1),n===void 0&&(n=1/0),Oe||(Oe=document.createElement("textarea"),Oe.setAttribute("tabindex","-1"),Oe.setAttribute("aria-hidden","true"),no(Oe)),Oe.parentNode===null&&document.body.appendChild(Oe);var i=e.paddingSize,a=e.borderSize,s=e.sizingStyle,o=s.boxSizing;Object.keys(s).forEach(function(f){var h=f;Oe.style[h]=s[h]}),no(Oe),Oe.value=t;var l=io(Oe,e);Oe.value=t,l=io(Oe,e),Oe.value="x";var u=Oe.scrollHeight-i,d=u*r;o==="border-box"&&(d=d+i+a),l=Math.max(d,l);var c=u*n;return o==="border-box"&&(c=c+i+a),l=Math.min(c,l),[l,u]}var ao=function(){},zf=function(t,r){return t.reduce(function(n,i){return n[i]=r[i],n},{})},Bf=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],Rf=!!document.documentElement.currentStyle,jf=function(t){var r=window.getComputedStyle(t);if(r===null)return null;var n=zf(Bf,r),i=n.boxSizing;if(i==="")return null;Rf&&i==="border-box"&&(n.width=parseFloat(n.width)+parseFloat(n.borderRightWidth)+parseFloat(n.borderLeftWidth)+parseFloat(n.paddingRight)+parseFloat(n.paddingLeft)+"px");var a=parseFloat(n.paddingBottom)+parseFloat(n.paddingTop),s=parseFloat(n.borderBottomWidth)+parseFloat(n.borderTopWidth);return{sizingStyle:n,paddingSize:a,borderSize:s}},$f=jf;function oi(e,t,r){var n=Lf(r);Z.useLayoutEffect(function(){var i=function(s){return n.current(s)};if(e)return e.addEventListener(t,i),function(){return e.removeEventListener(t,i)}},[])}var Uf=function(t,r){oi(document.body,"reset",function(n){t.current.form===n.target&&r(n)})},Hf=function(t){oi(window,"resize",t)},qf=function(t){oi(document.fonts,"loadingdone",t)},Vf=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],Wf=function(t,r){var n=t.cacheMeasurements,i=t.maxRows,a=t.minRows,s=t.onChange,o=s===void 0?ao:s,l=t.onHeightChange,u=l===void 0?ao:l,d=Pf(t,Vf),c=d.value!==void 0,f=Z.useRef(null),h=Df(f,r),g=Z.useRef(0),x=Z.useRef(),b=function(){var _=f.current,O=n&&x.current?x.current:$f(_);if(O){x.current=O;var z=Ff(O,_.value||_.placeholder||"x",a,i),C=z[0],U=z[1];g.current!==C&&(g.current=C,_.style.setProperty("height",C+"px","important"),u(C,{rowHeight:U}))}},w=function(_){c||b(),o(_)};return Z.useLayoutEffect(b),Uf(f,function(){if(!c){var E=f.current.value;requestAnimationFrame(function(){var _=f.current;_&&E!==_.value&&b()})}}),Hf(b),qf(b),Z.createElement("textarea",si({},d,{onChange:w,ref:h}))},Jf=Z.forwardRef(Wf),so=e=>{const t=At(e),r=Qr(n=>n.onScrollToBottom);y.useEffect(()=>r(t),[r,t])},oo=y.forwardRef((g,h)=>{var x=g,{autoFocus:e=!1,asChild:t,disabled:r,onChange:n,onKeyDown:i,onPaste:a,submitOnEnter:s=!0,cancelOnEscape:o=!0,unstable_focusOnRunStart:l=!0,unstable_focusOnScrollToBottom:u=!0,unstable_focusOnThreadSwitched:d=!0,addAttachmentOnPaste:c=!0}=x,f=H(x,["autoFocus","asChild","disabled","onChange","onKeyDown","onPaste","submitOnEnter","cancelOnEscape","unstable_focusOnRunStart","unstable_focusOnScrollToBottom","unstable_focusOnThreadSwitched","addAttachmentOnPaste"]);const b=pe(),w=ee(({composer:S})=>S.isEditing?S.text:""),E=t?ni:Jf,_=ee(({thread:S})=>S.isDisabled)||r,O=y.useRef(null),z=Gr(h,O);df(S=>{var N;if(!o||!((N=O.current)!=null&&N.contains(S.target)))return;const D=b.composer();D.getState().canCancel&&(D.cancel(),S.preventDefault())});const C=S=>{var D,N;_||!s||S.nativeEvent.isComposing||S.key==="Enter"&&S.shiftKey===!1&&(b.thread().getState().isRunning||(S.preventDefault(),(N=(D=O.current)==null?void 0:D.closest("form"))==null||N.requestSubmit()))},U=S=>M(null,null,function*(){var K;if(!c)return;const D=b.thread().getState().capabilities,N=Array.from(((K=S.clipboardData)==null?void 0:K.files)||[]);if(D.attachments&&N.length>0)try{S.preventDefault(),yield Promise.all(N.map(B=>b.composer().addAttachment(B)))}catch(B){console.error("Error adding attachment:",B)}}),V=e&&!_,R=y.useCallback(()=>{const S=O.current;!S||!V||(S.focus({preventScroll:!0}),S.setSelectionRange(S.value.length,S.value.length))},[V]);return y.useEffect(()=>R(),[R]),so(()=>{b.composer().getState().type==="thread"&&u&&R()}),y.useEffect(()=>{if(!(b.composer().getState().type!=="thread"||!l))return b.on("thread.run-start",R)},[l,R,b]),y.useEffect(()=>{if(!(b.composer().getState().type!=="thread"||!d))return b.on("thread-list-item.switched-to",R)},[d,R,b]),p.jsx(E,I(m({name:"input",value:w},f),{ref:z,disabled:_,onChange:qt(n,S=>{b.composer().getState().isEditing&&(b.composer().setText(S.target.value),b.flushSync())}),onKeyDown:qt(i,C),onPaste:qt(a,U)}))});oo.displayName="ComposerPrimitive.Input";var Kf=({multiple:e=!0}={})=>{const t=ee(({composer:i})=>!i.isEditing),r=pe(),n=y.useCallback(()=>{const i=document.createElement("input");i.type="file",i.multiple=e,i.hidden=!0;const a=r.composer().getState().attachmentAccept;a!=="*"&&(i.accept=a),document.body.appendChild(i),i.onchange=s=>{const o=s.target.files;if(o){for(const l of o)r.composer().addAttachment(l);document.body.removeChild(i)}},i.oncancel=()=>{(!i.files||i.files.length===0)&&document.body.removeChild(i)},i.click()},[r,e]);return t?null:n},Yf=nn("ComposerPrimitive.AddAttachment",Kf,["multiple"]),Gf=(e,t)=>{var n,i,a;const r=t.type;switch(r){case"image":return(n=e==null?void 0:e.Image)!=null?n:e==null?void 0:e.Attachment;case"document":return(i=e==null?void 0:e.Document)!=null?i:e==null?void 0:e.Attachment;case"file":return(a=e==null?void 0:e.File)!=null?a:e==null?void 0:e.Attachment;default:const s=r;throw new Error(`Unknown attachment type: ${s}`)}},Xf=({components:e})=>{const t=ee(({attachment:n})=>n);if(!t)return null;const r=Gf(e,t);return r?p.jsx(r,{}):null},lo=y.memo(({index:e,components:t})=>p.jsx(bh,{index:e,children:p.jsx(Xf,{components:t})}),(e,t)=>{var r,n,i,a,s,o,l,u;return e.index===t.index&&((r=e.components)==null?void 0:r.Image)===((n=t.components)==null?void 0:n.Image)&&((i=e.components)==null?void 0:i.Document)===((a=t.components)==null?void 0:a.Document)&&((s=e.components)==null?void 0:s.File)===((o=t.components)==null?void 0:o.File)&&((l=e.components)==null?void 0:l.Attachment)===((u=t.components)==null?void 0:u.Attachment)});lo.displayName="ComposerPrimitive.AttachmentByIndex";var uo=({components:e})=>{const t=ee(n=>n.composer.attachments.length);return y.useMemo(()=>Array.from({length:t},(n,i)=>p.jsx(lo,{index:i,components:e},i)),[t,e])};uo.displayName="ComposerPrimitive.Attachments";var co=y.forwardRef((a,i)=>{var s=a,{disabled:e,asChild:t=!1,children:r}=s,n=H(s,["disabled","asChild","children"]);const[o,l]=y.useState(!1),u=pe(),d=y.useCallback(b=>{e||(b.preventDefault(),l(!0))},[e]),c=y.useCallback(b=>{e||(b.preventDefault(),o||l(!0))},[e,o]),f=y.useCallback(b=>{if(e)return;b.preventDefault();const w=b.relatedTarget;w&&b.currentTarget.contains(w)||l(!1)},[e]),h=y.useCallback(b=>M(null,null,function*(){if(!e){b.preventDefault(),l(!1);for(const w of b.dataTransfer.files)try{yield u.composer().addAttachment(w)}catch(E){console.error("Failed to add attachment:",E)}}}),[e,u]),g={onDragEnterCapture:d,onDragOverCapture:c,onDragLeaveCapture:f,onDropCapture:h},x=t?ni:"div";return p.jsx(x,I(m(m(I(m({},o?{"data-dragging":"true"}:null),{ref:i}),g),n),{children:r}))});co.displayName="ComposerPrimitive.AttachmentDropzone";var ho=y.forwardRef((e,t)=>p.jsx(ut.div,I(m({},e),{ref:t})));ho.displayName="ThreadPrimitive.Root";var fo=({children:e})=>ee(({thread:r})=>r.messages.length===0&&!r.isLoading)?e:null;fo.displayName="ThreadPrimitive.Empty";var Qf=e=>{const t=At(e),r=y.useCallback(n=>{const i=new ResizeObserver(()=>{t()}),a=new MutationObserver(()=>{t()});return i.observe(n),a.observe(n,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{i.disconnect(),a.disconnect()}},[t]);return pr(r)},Zf=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:r=!0,scrollToBottomOnThreadSwitch:n=!0})=>{const i=y.useRef(null),a=Kn();e===void 0&&(e=a.getState().turnAnchor!=="top");const s=y.useRef(0),o=y.useRef(null),l=y.useCallback(h=>{const g=i.current;g&&(o.current=h,g.scrollTo({top:g.scrollHeight,behavior:h}))},[]),u=()=>{const h=i.current;if(!h)return;const g=a.getState().isAtBottom,x=Math.abs(h.scrollHeight-h.scrollTop-h.clientHeight)<1||h.scrollHeight<=h.clientHeight;!x&&s.current<h.scrollTop||(x&&(o.current=null),(x||o.current===null)&&x!==g&&fr(a).setState({isAtBottom:x})),s.current=h.scrollTop},d=Qf(()=>{const h=o.current;h?l(h):e&&a.getState().isAtBottom&&l("instant"),u()}),c=pr(h=>(h.addEventListener("scroll",u),()=>{h.removeEventListener("scroll",u)}));return so(({behavior:h})=>{l(h)}),Jn("thread.run-start",()=>{t&&(o.current="auto",requestAnimationFrame(()=>{l("auto")}))}),Jn("thread.initialize",()=>{r&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Jn("thread-list-item.switched-to",()=>{n&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Gr(d,c,i)},ep=()=>{const e=Qr(r=>r.registerViewport),t=y.useCallback(r=>r.clientHeight,[]);return Rs(e,t)},po=y.forwardRef((o,s)=>{var l=o,{autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:r,scrollToBottomOnThreadSwitch:n,children:i}=l,a=H(l,["autoScroll","scrollToBottomOnRunStart","scrollToBottomOnInitialize","scrollToBottomOnThreadSwitch","children"]);const u=Zf({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:r,scrollToBottomOnThreadSwitch:n}),d=ep(),c=Gr(s,u,d);return p.jsx(ut.div,I(m({},a),{ref:c,children:i}))});po.displayName="ThreadPrimitive.ViewportScrollable";var mo=y.forwardRef((n,r)=>{var i=n,{turnAnchor:e}=i,t=H(i,["turnAnchor"]);return p.jsx(_s,{options:{turnAnchor:e},children:p.jsx(po,I(m({},t),{ref:r}))})});mo.displayName="ThreadPrimitive.Viewport";var go=(e,t)=>e.Message===t.Message&&e.EditComposer===t.EditComposer&&e.UserEditComposer===t.UserEditComposer&&e.AssistantEditComposer===t.AssistantEditComposer&&e.SystemEditComposer===t.SystemEditComposer&&e.UserMessage===t.UserMessage&&e.AssistantMessage===t.AssistantMessage&&e.SystemMessage===t.SystemMessage,tp=()=>null,rp=(e,t,r)=>{var n,i,a,s,o,l,u,d,c,f,h,g;switch(t){case"user":return r?(a=(i=(n=e.UserEditComposer)!=null?n:e.EditComposer)!=null?i:e.UserMessage)!=null?a:e.Message:(s=e.UserMessage)!=null?s:e.Message;case"assistant":return r?(u=(l=(o=e.AssistantEditComposer)!=null?o:e.EditComposer)!=null?l:e.AssistantMessage)!=null?u:e.Message:(d=e.AssistantMessage)!=null?d:e.Message;case"system":return r?(h=(f=(c=e.SystemEditComposer)!=null?c:e.EditComposer)!=null?f:e.SystemMessage)!=null?h:e.Message:(g=e.SystemMessage)!=null?g:tp;default:const x=t;throw new Error(`Unknown message role: ${x}`)}},np=({components:e})=>{const t=ee(({message:i})=>i.role),r=ee(({message:i})=>i.composer.isEditing),n=rp(e,t,r);return p.jsx(n,{})},yo=y.memo(({index:e,components:t})=>p.jsx(mh,{index:e,children:p.jsx(np,{components:t})}),(e,t)=>e.index===t.index&&go(e.components,t.components));yo.displayName="ThreadPrimitive.MessageByIndex";var bo=({components:e})=>{const t=ee(({thread:n})=>n.messages.length);return y.useMemo(()=>t===0?null:Array.from({length:t},(n,i)=>p.jsx(yo,{index:i,components:e},i)),[t,e])};bo.displayName="ThreadPrimitive.Messages";var ip=y.memo(bo,(e,t)=>go(e.components,t.components)),wo=y.forwardRef((i,n)=>{var a=i,{onClick:e,disabled:t}=a,r=H(a,["onClick","disabled"]);const s=ee(({threads:l})=>l.newThreadId===l.mainThreadId),o=pe();return p.jsx(ut.button,I(m(m({type:"button"},s?{"data-active":"true","aria-current":"true"}:null),r),{ref:n,disabled:t,onClick:qt(e,()=>{o.threads().switchToNewThread()})}))});wo.displayName="ThreadListPrimitive.New";var xo=y.memo(({index:e,archived:t=!1,components:r})=>{const n=r.ThreadListItem;return p.jsx(fh,{index:e,archived:t,children:p.jsx(n,{})})},(e,t)=>e.index===t.index&&e.archived===t.archived&&e.components.ThreadListItem===t.components.ThreadListItem);xo.displayName="ThreadListPrimitive.ItemByIndex";var vo=({archived:e=!1,components:t})=>{const r=ee(({threads:i})=>e?i.archivedThreadIds.length:i.threadIds.length);return y.useMemo(()=>Array.from({length:r},(i,a)=>p.jsx(xo,{index:a,archived:e,components:t},a)),[r,e,t])};vo.displayName="ThreadListPrimitive.Items";var ko=y.forwardRef((e,t)=>p.jsx(ut.div,I(m({},e),{ref:t})));ko.displayName="ThreadListPrimitive.Root";var So=y.forwardRef((e,t)=>{const r=ee(({threads:n,threadListItem:i})=>n.mainThreadId===i.id);return p.jsx(ut.div,I(m(m({},r?{"data-active":"true","aria-current":"true"}:null),e),{ref:t}))});So.displayName="ThreadListItemPrimitive.Root";var ap=()=>{const e=pe();return y.useCallback(()=>{e.threadListItem().switchTo()},[e])},sp=nn("ThreadListItemPrimitive.Trigger",ap);function op(){if(typeof crypto!="undefined"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto!="undefined"&&crypto.getRandomValues){const e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`}class _o{constructor(t,r,n=!1){T(this,"baseUrl");T(this,"sessionToken",null);T(this,"isProxyMode",!1);this.baseUrl=t.replace(/\/$/,""),this.isProxyMode=n,r&&(this.sessionToken=r)}setSessionToken(t){this.sessionToken=t}getUrl(t){if(this.isProxyMode){const r=`${this.baseUrl}${t.replace("/v1","")}`;return r.startsWith("/")||r.startsWith("./"),r}return`${this.baseUrl}${t}`}createOrContinueChat(t,r){return M(this,null,function*(){const n=this.getUrl("/v1/chats"),a={"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&&(a.Authorization=`Bearer ${this.sessionToken}`);const s=I(m({},t),{stream:!0}),o=yield fetch(n,{method:"POST",headers:a,body:JSON.stringify(s),signal:r,cache:"no-store"});if(!o.ok){const l=yield o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}if(!o.body)throw new Error("Response body is null");return o.body})}getChat(t){return M(this,null,function*(){const r=this.getUrl(`/v1/chats/${t}`),n={"Content-Type":"application/json"};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(r,{method:"GET",headers:n});if(!i.ok){const a=yield i.json().catch(()=>({}));throw new Error(a.detail||a.message||`API error: ${i.status} ${i.statusText}`)}return i.json()})}listChats(t){return M(this,null,function*(){const r=this.getUrl("/v1/chats"),n=r.startsWith("/")||r.startsWith("./")?new URL(r,window.location.origin):new URL(r);t!=null&&t.limit&&n.searchParams.set("limit",t.limit.toString()),t!=null&&t.cursor&&n.searchParams.set("cursor",t.cursor),t!=null&&t["expand[]"]&&t["expand[]"].forEach(s=>{n.searchParams.append("expand[]",s)});const i={"Content-Type":"application/json"};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const a=yield fetch(n.toString(),{method:"GET",headers:i});if(!a.ok){const s=yield a.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${a.status} ${a.statusText}`)}return a.json()})}generateIdempotencyKey(){return op()}updateChat(t,r){return M(this,null,function*(){const n=`/v1/chats/${t}`,i=this.getUrl(n),a=i.startsWith("/")||i.startsWith("./")?new URL(i,window.location.origin):new URL(i),o={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(a.toString(),{method:"PATCH",headers:o,body:JSON.stringify(r)});if(!l.ok){const d=yield l.text();let c={};try{c=JSON.parse(d)}catch(f){c={detail:d}}throw new Error(c.detail||c.message||`API error: ${l.status} ${l.statusText}`)}if(l.status===204)return{};const u=yield l.text();if(!u)return{};try{return JSON.parse(u)}catch(d){return{}}})}deleteChat(t){return M(this,null,function*(){const r=`/v1/chats/${t}`,n=this.getUrl(r),i=n.startsWith("/")||n.startsWith("./")?new URL(n,window.location.origin):new URL(n),s={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(s.Authorization=`Bearer ${this.sessionToken}`);const o=yield fetch(i.toString(),{method:"DELETE",headers:s});if(!o.ok){const l=yield o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}})}generateChatTitle(t,r){return M(this,null,function*(){const n=`/v1/chats/${t}/title`,i=this.getUrl(n),a=i.startsWith("/")||i.startsWith("./")?new URL(i,window.location.origin):new URL(i),o={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(a.toString(),{method:"POST",headers:o,body:r?JSON.stringify(r):void 0});if(!l.ok){const u=yield l.json().catch(()=>({}));throw new Error(u.detail||u.message||`API error: ${l.status} ${l.statusText}`)}return l.json()})}listModels(t){return M(this,null,function*(){const r=this.getUrl("/v1/models"),n=r.startsWith("/")||r.startsWith("./")?new URL(r,window.location.origin):new URL(r);t!=null&&t.limit&&n.searchParams.set("limit",t.limit.toString()),t!=null&&t.cursor&&n.searchParams.set("cursor",t.cursor),t!=null&&t["expand[]"]&&t["expand[]"].forEach(s=>{n.searchParams.append("expand[]",s)});const i={"Content-Type":"application/json"};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const a=yield fetch(n.toString(),{method:"GET",headers:i});if(!a.ok){const s=yield a.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${a.status} ${a.statusText}`)}return a.json()})}getModel(t){return M(this,null,function*(){const r=this.getUrl(`/v1/models/${t}`),n={"Content-Type":"application/json"};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(r,{method:"GET",headers:n});if(!i.ok){const a=yield i.json().catch(()=>({}));throw new Error(a.detail||a.message||`API error: ${i.status} ${i.statusText}`)}return i.json()})}uploadFile(t,r,n){return M(this,null,function*(){const i=this.getUrl("/v1/files"),a=this.generateIdempotencyKey(),s=new FormData;s.append("file",t),r&&s.append("resource_type",r),n&&s.append("resource_id",n);const o={"Idempotency-Key":a};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(i,{method:"POST",headers:o,body:s});if(!l.ok){const u=yield l.json().catch(()=>({}));throw new Error(u.detail||u.message||`API error: ${l.status} ${l.statusText}`)}return l.json()})}}function lp(e,t){return Dr(this,null,function*(){const r=e.getReader(),n=new TextDecoder;let i="";try{for(;;){if(t!=null&&t.aborted){r.cancel();break}const{done:a,value:s}=yield new Ae(r.read());if(a)break;i+=n.decode(s,{stream:!0});const o=i.split(`
|
|
5
|
+
`),Us=class{constructor(e){this._core=e,this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(e){return this._core.subscribe(e)}},Hs=class extends Us{constructor(e,t){super(e),this._composerApi=t}remove(){const e=this._composerApi.getState();if(!e)throw new Error("Composer is not available");return e.removeAttachment(this.getState().id)}},kc=class extends Hs{get source(){return"thread-composer"}},Sc=class extends Hs{get source(){return"edit-composer"}},_c=class extends Us{get source(){return"message"}constructor(e){super(e)}remove(){throw new Error("Message attachments cannot be removed")}},qs=class extends Ur{constructor(e){super(),this.config=e}getState(){return this.config.binding.getState()}outerSubscribe(e){return this.config.binding.subscribe(e)}_connect(){const e=()=>{this.notifySubscribers()};let t=this.config.binding.getState(),r=t==null?void 0:t.unstable_on(this.config.event,e);const n=()=>{var i;const s=this.config.binding.getState();s!==t&&(t=s,r==null||r(),r=(i=this.config.binding.getState())==null?void 0:i.unstable_on(this.config.event,e))},a=this.outerSubscribe(n);return()=>{a==null||a(),r==null||r()}}},Vs=Object.freeze([]),Ws=Object.freeze({}),Tc=e=>{var t,r,n,a,s,i,o,l,u;return Object.freeze({type:"thread",isEditing:(t=e==null?void 0:e.isEditing)!=null?t:!1,canCancel:(r=e==null?void 0:e.canCancel)!=null?r:!1,isEmpty:(n=e==null?void 0:e.isEmpty)!=null?n:!0,attachments:(a=e==null?void 0:e.attachments)!=null?a:Vs,text:(s=e==null?void 0:e.text)!=null?s:"",role:(i=e==null?void 0:e.role)!=null?i:"user",runConfig:(o=e==null?void 0:e.runConfig)!=null?o:Ws,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},Cc=e=>{var t,r,n,a,s,i,o,l,u;return Object.freeze({type:"edit",isEditing:(t=e==null?void 0:e.isEditing)!=null?t:!1,canCancel:(r=e==null?void 0:e.canCancel)!=null?r:!1,isEmpty:(n=e==null?void 0:e.isEmpty)!=null?n:!0,text:(a=e==null?void 0:e.text)!=null?a:"",role:(s=e==null?void 0:e.role)!=null?s:"user",attachments:(i=e==null?void 0:e.attachments)!=null?i:Vs,runConfig:(o=e==null?void 0:e.runConfig)!=null?o:Ws,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},Js=class{constructor(e){T(this,"_eventSubscriptionSubjects",new Map);this._core=e}get path(){return this._core.path}__internal_bindMethods(){this.setText=this.setText.bind(this),this.setRunConfig=this.setRunConfig.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.addAttachment=this.addAttachment.bind(this),this.reset=this.reset.bind(this),this.clearAttachments=this.clearAttachments.bind(this),this.send=this.send.bind(this),this.cancel=this.cancel.bind(this),this.setRole=this.setRole.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setText(e)}setRunConfig(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setRunConfig(e)}addAttachment(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.addAttachment(e)}reset(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.reset()}clearAttachments(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.clearAttachments()}send(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.send()}cancel(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.cancel()}setRole(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setRole(e)}subscribe(e){return this._core.subscribe(e)}unstable_on(e,t){let r=this._eventSubscriptionSubjects.get(e);return r||(r=new qs({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}},Ic=class extends Js{constructor(t){const r=new Hn({path:t.path,getState:()=>Tc(t.getState()),subscribe:n=>t.subscribe(n)});super({path:t.path,getState:()=>t.getState(),subscribe:n=>r.subscribe(n)});T(this,"_getState");this._getState=r.getState.bind(r),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"thread"}getState(){return this._getState()}getAttachmentByIndex(t){return new kc(new Xe({path:I(m({},this.path),{attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`}),getState:()=>{const n=this.getState().attachments[t];return n?I(m({},n),{source:"thread-composer"}):Ge},subscribe:r=>this._core.subscribe(r)}),this._core)}},Ec=class extends Js{constructor(t,r){const n=new Hn({path:t.path,getState:()=>Cc(t.getState()),subscribe:a=>t.subscribe(a)});super({path:t.path,getState:()=>t.getState(),subscribe:a=>n.subscribe(a)});T(this,"_getState");this._beginEdit=r,this._getState=n.getState.bind(n),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"edit"}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(t){return new Sc(new Xe({path:I(m({},this.path),{attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`}),getState:()=>{const n=this.getState().attachments[t];return n?I(m({},n),{source:"edit-composer"}):Ge},subscribe:r=>this._core.subscribe(r)}),this._core)}},Ac=class En{constructor(t=null){T(this,"_state");this._state=t}get state(){return this._state}append(t){this._state=t.reduce((r,n)=>En.apply(r,n),this._state)}static apply(t,r){const n=r.type;switch(n){case"set":return En.updatePath(t,r.path,()=>r.value);case"append-text":return En.updatePath(t,r.path,a=>{if(typeof a!="string")throw new Error(`Expected string at path [${r.path.join(", ")}]`);return a+r.value});default:{const a=n;throw new Error(`Invalid operation type: ${a}`)}}}static updatePath(t,r,n){if(r.length===0)return n(t);if(t!=null||(t={}),typeof t!="object")throw new Error(`Invalid path: [${r.join(", ")}]`);const[a,...s]=r;if(Array.isArray(t)){const o=Number(a);if(Number.isNaN(o))throw new Error(`Expected array index at [${r.join(", ")}]`);if(o>t.length||o<0)throw new Error("Insert array index out of bounds");const l=[...t];return l[o]=this.updatePath(l[o],s,n),l}const i=m({},t);return i[a]=this.updatePath(i[a],s,n),i}},Mc=({unstable_state:e=null}={})=>({role:"assistant",status:{type:"running"},parts:[],get content(){return this.parts},metadata:{unstable_state:e,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}),Wr=(e,t,r)=>{if(e.parts.length===0)throw new Error("No parts available to update.");if(t.path.length!==1)throw new Error("Nested paths are not supported yet.");const n=t.path[0],a=r(e.parts[n]);return I(m({},e),{parts:[...e.parts.slice(0,n),a,...e.parts.slice(n+1)],get content(){return this.parts}})},Pc=(e,t)=>{const r=t.part;if(r.type==="text"||r.type==="reasoning"){const n=m({type:r.type,text:"",status:{type:"running"}},r.parentId&&{parentId:r.parentId});return I(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else if(r.type==="tool-call"){const n=m({type:"tool-call",state:"partial-call",status:{type:"running",isArgsComplete:!1},toolCallId:r.toolCallId,toolName:r.toolName,argsText:"",args:{}},r.parentId&&{parentId:r.parentId});return I(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else if(r.type==="source"){const n=m(m({type:"source",sourceType:r.sourceType,id:r.id,url:r.url},r.title?{title:r.title}:void 0),r.parentId&&{parentId:r.parentId});return I(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else if(r.type==="file"){const n={type:"file",mimeType:r.mimeType,data:r.data};return I(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else throw new Error(`Unsupported part type: ${r.type}`)},Nc=(e,t)=>Wr(e,t,r=>{if(r.type!=="tool-call")throw new Error("Last is not a tool call");return r.state!=="partial-call"?r:I(m({},r),{state:"call"})}),Lc=(e,t)=>Wr(e,t,r=>I(m({},r),{status:{type:"complete",reason:"unknown"}})),Dc=(e,t)=>Wr(e,t,r=>{var n;if(r.type==="text"||r.type==="reasoning")return I(m({},r),{text:r.text+t.textDelta});if(r.type==="tool-call"){const a=r.argsText+t.textDelta,s=(n=jr(a))!=null?n:r.args;return I(m({},r),{argsText:a,args:s})}else throw new Error("text-delta received but part is neither text nor tool-call")}),Oc=(e,t)=>Wr(e,t,r=>{var n;if(r.type==="tool-call")return I(m(I(m({},r),{state:"result"}),t.artifact!==void 0?{artifact:t.artifact}:{}),{result:t.result,isError:(n=t.isError)!=null?n:!1,status:{type:"complete",reason:"stop"}});throw new Error("Result chunk received but part is not a tool-call")}),Ks=(e,t)=>{var n,a;if(((n=e.status)==null?void 0:n.type)==="incomplete"&&((a=e.status)==null?void 0:a.reason)==="error")return e;const r=Fc(t);return I(m({},e),{status:r})},Fc=e=>e.finishReason==="tool-calls"?{type:"requires-action",reason:"tool-calls"}:e.finishReason==="stop"||e.finishReason==="unknown"?{type:"complete",reason:e.finishReason}:{type:"incomplete",reason:e.finishReason},zc=(e,t)=>I(m({},e),{metadata:I(m({},e.metadata),{unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]})}),Bc=(e,t)=>I(m({},e),{metadata:I(m({},e.metadata),{unstable_data:[...e.metadata.unstable_data,...t.data]})}),Rc=(e,t)=>I(m({},e),{metadata:I(m({},e.metadata),{steps:[...e.metadata.steps,{state:"started",messageId:t.messageId}]})}),jc=(e,t)=>{var a;const r=e.metadata.steps.slice(),n=r.length-1;return r.length>0&&((a=r[n])==null?void 0:a.state)==="started"?r[n]=I(m({},r[n]),{state:"finished",finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}):r.push({state:"finished",messageId:Bs(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),I(m({},e),{metadata:I(m({},e.metadata),{steps:r})})},$c=(e,t)=>I(m({},e),{status:{type:"incomplete",reason:"error",error:t.error}}),Uc=(e,t)=>{const r=new Ac(e.metadata.unstable_state);return r.append(t.operations),I(m({},e),{metadata:I(m({},e.metadata),{unstable_state:r.state})})},Hc=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}},qc=class extends TransformStream{constructor({initialMessage:e,throttle:t,onError:r}={}){let n=e!=null?e:Mc(),a;const s=t?Hc(()=>{a==null||a.enqueue(n)}):()=>{a==null||a.enqueue(n)};super({start(i){a=i},transform(i){const o=i.type;switch(o){case"part-start":n=Pc(n,i);break;case"tool-call-args-text-finish":n=Nc(n,i);break;case"part-finish":n=Lc(n,i);break;case"text-delta":n=Dc(n,i);break;case"result":n=Oc(n,i);break;case"message-finish":n=Ks(n,i);break;case"annotations":n=zc(n,i);break;case"data":n=Bc(n,i);break;case"step-start":n=Rc(n,i);break;case"step-finish":n=jc(n,i);break;case"error":n=$c(n,i),r==null||r(i.error);break;case"update-state":n=Uc(n,i);break;default:{const l=o;throw new Error(`Unsupported chunk type: ${l}`)}}s()},flush(i){var o,l,u;if(((o=n.status)==null?void 0:o.type)==="running"){const d=(u=(l=n.parts)==null?void 0:l.some(c=>c.type==="tool-call"&&(c.state==="call"||c.state==="partial-call")&&c.result===void 0))!=null?u:!1;n=Ks(n,{finishReason:d?"tool-calls":"unknown"}),i.enqueue(n)}}})}},Vc=class extends Fs{constructor(){super(e=>{const t=new xc({transform(r,n){n.appendText(r)}});return e.pipeThrough(new TextDecoderStream).pipeThrough(t)})}},Wc=class An{constructor(t){this.readable=t,this.readable=t}static fromAssistantStream(t){return new An(t.pipeThrough(new qc))}unstable_result(){return M(this,null,function*(){let t;try{for(var r=Ft(this),n,a,s;n=!(a=yield r.next()).done;n=!1){const i=a.value;t=i}}catch(a){s=[a]}finally{try{n&&(a=r.return)&&(yield a.call(r))}finally{if(s)throw s[0]}}return t||{role:"assistant",status:{type:"complete",reason:"unknown"},parts:[],content:[],metadata:{unstable_state:null,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}})}[Symbol.asyncIterator](){const t=this.readable.getReader();return{next(){return M(this,null,function*(){const{done:n,value:a}=yield t.read();return n?{done:!0,value:void 0}:{done:!1,value:a}})}}}tee(){const[t,r]=this.readable.tee();return[new An(t),new An(r)]}},Ys=Symbol.for("aui.tool-response"),gt=class xs{constructor(t){T(this,"artifact");T(this,"result");T(this,"isError");var r;t.artifact!==void 0&&(this.artifact=t.artifact),this.result=t.result,this.isError=(r=t.isError)!=null?r:!1}get[Ys](){return!0}static[Symbol.hasInstance](t){return typeof t=="object"&&t!==null&&Ys in t}static toResponse(t){return t instanceof xs?t:new xs({result:t===void 0?"<no result>":t})}};function Jc(e,t,r){try{const n=e();if(typeof n=="object"&&n!==null&&"then"in n)return n.then(t,r);t(n)}catch(n){r(n)}}function ur(e,t){let r=e;for(const n of t){if(r==null)return;r=r[n]}return r}var Kc=class{constructor(e,t,r){T(this,"resolve");T(this,"reject");T(this,"disposed",!1);T(this,"fieldPath");this.resolve=e,this.reject=t,this.fieldPath=r}update(e){if(!this.disposed)try{if(zt(e,this.fieldPath)==="complete"){const t=ur(e,this.fieldPath);t!==void 0&&(this.resolve(t),this.dispose())}}catch(t){this.reject(t),this.dispose()}}dispose(){this.disposed=!0}},Gs=class{constructor(e,t){T(this,"controller");T(this,"disposed",!1);T(this,"fieldPath");this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=ur(e,this.fieldPath);t!==void 0&&this.controller.enqueue(t),zt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},Xs=class{constructor(e,t){T(this,"controller");T(this,"disposed",!1);T(this,"fieldPath");T(this,"lastValue");this.controller=e,this.fieldPath=t}update(e){var t;if(!this.disposed)try{const r=ur(e,this.fieldPath);if(r!==void 0&&typeof r=="string"){const n=r.substring(((t=this.lastValue)==null?void 0:t.length)||0);this.lastValue=r,this.controller.enqueue(n)}zt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(r){this.controller.error(r),this.dispose()}}dispose(){this.disposed=!0}},Qs=class{constructor(e,t){T(this,"controller");T(this,"disposed",!1);T(this,"fieldPath");T(this,"processedIndexes",new Set);this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=ur(e,this.fieldPath);if(!Array.isArray(t))return;for(let r=0;r<t.length;r++)if(!this.processedIndexes.has(r)){const n=[...this.fieldPath,r];zt(e,n)==="complete"&&(this.controller.enqueue(t[r]),this.processedIndexes.add(r))}zt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},Yc=class{constructor(e){T(this,"argTextDeltas");T(this,"handles",new Set);T(this,"args",jr(""));this.argTextDeltas=e,this.processStream()}processStream(){return M(this,null,function*(){try{let e="";const t=this.argTextDeltas.getReader();for(;;){const{value:r,done:n}=yield t.read();if(n)break;e+=r;const a=jr(e);if(a!==void 0){this.args=a;for(const s of this.handles)s.update(a)}}}catch(e){console.error("Error processing argument stream:",e);for(const t of this.handles)t.dispose()}})}get(...e){return new Promise((t,r)=>{const n=new Kc(t,r,e);if(this.args&&zt(this.args,e)==="complete"){const a=ur(this.args,e);if(a!==void 0){t(a);return}}this.handles.add(n),n.update(this.args)})}streamValues(...e){const t=e,r=new ReadableStream({start:n=>{const a=new Gs(n,t);this.handles.add(a),a.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Gs){n.dispose(),this.handles.delete(n);break}}});return Rn(r)}streamText(...e){const t=e,r=new ReadableStream({start:n=>{const a=new Xs(n,t);this.handles.add(a),a.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Xs){n.dispose(),this.handles.delete(n);break}}});return Rn(r)}forEach(...e){const t=e,r=new ReadableStream({start:n=>{const a=new Qs(n,t);this.handles.add(a),a.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Qs){n.dispose(),this.handles.delete(n);break}}});return Rn(r)}},Gc=class{constructor(e){this.promise=e}get(){return this.promise}},Xc=class{constructor(){T(this,"args");T(this,"response");T(this,"writable");T(this,"resolve");T(this,"argsText","");T(this,"result",{get:()=>M(this,null,function*(){return(yield this.response.get()).result})});const e=new TransformStream;this.writable=e.writable,this.args=new Yc(e.readable);const{promise:t,resolve:r}=$n();this.resolve=r,this.response=new Gc(t)}appendArgsTextDelta(e){return M(this,null,function*(){const t=this.writable.getWriter();try{yield t.write(e)}catch(r){console.warn(r)}finally{t.releaseLock()}this.argsText+=e})}setResponse(e){this.resolve(e)}},Qc=class extends Fs{constructor(e){const t=new Map,r=new Map;super(n=>{const a=new TransformStream({transform(i,o){switch((i.type!=="part-finish"||i.meta.type!=="tool-call")&&o.enqueue(i),i.type){case"part-start":if(i.part.type==="tool-call"){const u=new Xc;r.set(i.part.toolCallId,u),e.streamCall({reader:u,toolCallId:i.part.toolCallId,toolName:i.part.toolName})}break;case"text-delta":{if(i.meta.type==="tool-call"){const u=i.meta.toolCallId,d=r.get(u);if(!d)throw new Error("No controller found for tool call");d.appendArgsTextDelta(i.textDelta)}break}case"result":{if(i.meta.type!=="tool-call")break;const{toolCallId:u}=i.meta,d=r.get(u);if(!d)throw new Error("No controller found for tool call");d.setResponse(new gt({result:i.result,artifact:i.artifact,isError:i.isError}));break}case"tool-call-args-text-finish":{if(i.meta.type!=="tool-call")break;const{toolCallId:u,toolName:d}=i.meta,c=r.get(u);if(!c)throw new Error("No controller found for tool call");let f=!1;const h=Jc(()=>{var x;let g;try{g=Bn.parse(c.argsText)}catch(y){throw new Error(`Function parameter parsing failed. ${JSON.stringify(y.message)}`)}const w=e.execute({toolCallId:u,toolName:d,args:g});return w!==void 0&&(f=!0,(x=e.onExecutionStart)==null||x.call(e,u,d)),w},g=>{var x;if(f&&((x=e.onExecutionEnd)==null||x.call(e,u,d)),g===void 0)return;const w=new gt({artifact:g.artifact,result:g.result,isError:g.isError});c.setResponse(w),o.enqueue(m({type:"result",path:i.path},w))},g=>{var x;f&&((x=e.onExecutionEnd)==null||x.call(e,u,d));const w=new gt({result:String(g),isError:!0});c.setResponse(w),o.enqueue(m({type:"result",path:i.path},w))});h&&t.set(u,h);break}case"part-finish":{if(i.meta.type!=="tool-call")break;const{toolCallId:u}=i.meta,d=t.get(u);d?d.then(()=>{t.delete(u),r.delete(u),o.enqueue(i)}):o.enqueue(i)}}},flush(){return M(this,null,function*(){yield Promise.all(t.values())})}});return n.pipeThrough(new zs).pipeThrough(a)})}},Zc=e=>typeof e=="object"&&e!==null&&"~standard"in e&&e["~standard"].version===1;function ed(e,t,r,n){const a=e==null?void 0:e[r.toolName];return!a||!a.execute?void 0:(i=>M(null,null,function*(){var d;if(t.aborted)return new gt({result:"Tool execution was cancelled.",isError:!0});let o=i;if(Zc(a.parameters)){let c=a.parameters["~standard"].validate(r.args);c instanceof Promise&&(c=yield c),c.issues&&(o=(d=a.experimental_onSchemaValidationError)!=null?d:(()=>{throw new Error(`Function parameter validation failed. ${JSON.stringify(c.issues)}`)}))}const l=new Promise(c=>{const f=()=>{queueMicrotask(()=>{queueMicrotask(()=>{c(new gt({result:"Tool execution was cancelled.",isError:!0}))})})};t.aborted?f():t.addEventListener("abort",f,{once:!0})}),u=M(null,null,function*(){const c=yield o(r.args,{toolCallId:r.toolCallId,abortSignal:t,human:f=>n(r.toolCallId,f)});return gt.toResponse(c)});return Promise.race([u,l])}))(a.execute)}function td(e,t,r,n,a){var s,i;(i=(s=e==null?void 0:e[n.toolName])==null?void 0:s.streamCall)==null||i.call(s,r,{toolCallId:n.toolCallId,abortSignal:t,human:o=>a(n.toolCallId,o)})}function rd(e,t,r,n){const a=typeof e=="function"?e:()=>e,s=typeof t=="function"?t:()=>t;return new Qc({execute:i=>ed(a(),s(),i,r),streamCall:l=>{var u=l,{reader:i}=u,o=H(u,["reader"]);return td(a(),s(),i,o,r)},onExecutionStart:n==null?void 0:n.onExecutionStart,onExecutionEnd:n==null?void 0:n.onExecutionEnd})}var Zs=class{constructor(e,t,r){this.contentBinding=e,this.messageApi=t,this.threadApi=r,this.__internal_bindMethods()}get path(){return this.contentBinding.path}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.resumeToolCall=this.resumeToolCall.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to add tool result to non-tool message part");if(!this.messageApi)throw new Error("Message API is not available. This is likely a bug in assistant-ui.");if(!this.threadApi)throw new Error("Thread API is not available");const r=this.messageApi.getState();if(!r)throw new Error("Message is not available");const n=t.toolName,a=t.toolCallId,s=gt.toResponse(e);this.threadApi.getState().addToolResult({messageId:r.id,toolName:n,toolCallId:a,result:s.result,artifact:s.artifact,isError:s.isError})}resumeToolCall(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to resume tool call on non-tool message part");if(!this.threadApi)throw new Error("Thread API is not available");const r=t.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:r,payload:e})}subscribe(e){return this.contentBinding.subscribe(e)}},Jr=class extends Ur{constructor(e){super(),this.binding=e}get path(){return this.binding.path}getState(){return this.binding.getState()}outerSubscribe(e){return this.binding.subscribe(e)}_connect(){const e=()=>{this.notifySubscribers()};let t=this.binding.getState(),r=t==null?void 0:t.subscribe(e);const n=()=>{var i;const s=this.binding.getState();s!==t&&(t=s,r==null||r(),r=(i=this.binding.getState())==null?void 0:i.subscribe(e),e())},a=this.outerSubscribe(n);return()=>{a==null||a(),r==null||r()}}},Kr=Object.freeze({type:"complete"}),nd=(e,t,r)=>{if(e.role!=="assistant")return Kr;if(r.type==="tool-call")return r.result?Kr:e.status;const n=t===Math.max(0,e.content.length-1);return e.status.type==="requires-action"?Kr:n?e.status:Kr},ei=(e,t)=>{const r=e.content[t];if(!r)return Ge;const n=nd(e,t,r);return Object.freeze(I(m({},r),{[qr]:r[qr],status:n}))},ad=class{constructor(e,t){T(this,"composer");T(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=e,this._threadBinding=t,this.composer=new Ec(new Jr({path:I(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"edit"}),getState:this._getEditComposerRuntimeCore,subscribe:r=>this._threadBinding.subscribe(r)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id)),this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.reload=this.reload.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getMessagePartByIndex=this.getMessagePartByIndex.bind(this),this.getMessagePartByToolCallId=this.getMessagePartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}getState(){return this._core.getState()}reload(e={}){const t=this._getEditComposerRuntimeCore(),r=t!=null?t:this._threadBinding.getState().composer,n=t!=null?t:r,{runConfig:a=n.runConfig}=e,s=this._core.getState();if(s.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:s.parentId,sourceId:s.id,runConfig:a})}speak(){const e=this._core.getState();return this._threadBinding.getState().speak(e.id)}stopSpeaking(){var r;const e=this._core.getState();if(((r=this._threadBinding.getState().speech)==null?void 0:r.messageId)===e.id)this._threadBinding.getState().stopSpeaking();else throw new Error("Message is not being spoken")}submitFeedback({type:e}){const t=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:t.id,type:e})}switchToBranch({position:e,branchId:t}){const r=this._core.getState();if(t&&e)throw new Error("May not specify both branchId and position");if(!t&&!e)throw new Error("Must specify either branchId or position");const a=this._threadBinding.getState().getBranches(r.id);let s=t;if(e==="previous"?s=a[r.branchNumber-2]:e==="next"&&(s=a[r.branchNumber]),!s)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(s)}unstable_getCopyText(){return Vr(this.getState())}subscribe(e){return this._core.subscribe(e)}getMessagePartByIndex(e){if(e<0)throw new Error("Message part index must be >= 0");return new Zs(new Xe({path:I(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.content[${e}]`,messagePartSelector:{type:"index",index:e}}),getState:()=>ei(this.getState(),e),subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new Zs(new Xe({path:I(m({},this.path),{ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(e)}]`,messagePartSelector:{type:"toolCallId",toolCallId:e}}),getState:()=>{const t=this._core.getState(),r=t.content.findIndex(n=>n.type==="tool-call"&&n.toolCallId===e);return r===-1?Ge:ei(t,r)},subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new _c(new Xe({path:I(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.attachments[${e}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:e}}),getState:()=>{const t=this.getState().attachments,r=t==null?void 0:t[e];return r?I(m({},r),{source:"message"}):Ge},subscribe:t=>this._core.subscribe(t)}))}},sd=e=>{var t,r,n;return m({parentId:(t=e.parentId)!=null?t:null,sourceId:(r=e.sourceId)!=null?r:null,runConfig:(n=e.runConfig)!=null?n:{}},e.stream?{stream:e.stream}:{})},id=e=>{var t,r,n;return{parentId:(t=e.parentId)!=null?t:null,sourceId:(r=e.sourceId)!=null?r:null,runConfig:(n=e.runConfig)!=null?n:{}}},od=(e,t)=>{var r,n,a,s,i,o,l,u,d,c,f;return typeof t=="string"?{createdAt:new Date,parentId:(n=(r=e.at(-1))==null?void 0:r.id)!=null?n:null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:(a=t.createdAt)!=null?a:new Date,parentId:(o=(i=t.parentId)!=null?i:(s=e.at(-1))==null?void 0:s.id)!=null?o:null,sourceId:(l=t.sourceId)!=null?l:null,role:(u=t.role)!=null?u:"user",content:t.content,attachments:(d=t.attachments)!=null?d:[],metadata:(c=t.metadata)!=null?c:{custom:{}},runConfig:(f=t.runConfig)!=null?f:{},startRun:t.startRun}},ld=(e,t)=>{const r=e.messages.at(-1);return Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,isRunning:(r==null?void 0:r.role)!=="assistant"?!1:r.status.type==="running",messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech})},ti=class{constructor(e,t){T(this,"_threadBinding");T(this,"composer");T(this,"_eventSubscriptionSubjects",new Map);const r=new Xe({path:e.path,getState:()=>ld(e.getState(),t.getState()),subscribe:n=>{const a=e.subscribe(n),s=t.subscribe(n);return()=>{a(),s()}}});this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>r.getState(),outerSubscribe:n=>e.outerSubscribe(n),subscribe:n=>e.subscribe(n)},this.composer=new Ic(new Jr({path:I(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"thread"}),getState:()=>this._threadBinding.getState().composer,subscribe:n=>this._threadBinding.subscribe(n)})),this.__internal_bindMethods()}get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}__internal_bindMethods(){this.append=this.append.bind(this),this.unstable_resumeRun=this.unstable_resumeRun.bind(this),this.unstable_loadExternalState=this.unstable_loadExternalState.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.reset=this.reset.bind(this),this.getMessageByIndex=this.getMessageByIndex.bind(this),this.getMessageById=this.getMessageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.getModelConfig=this.getModelConfig.bind(this),this.getState=this.getState.bind(this)}getState(){return this._threadBinding.getStateState()}append(e){this._threadBinding.getState().append(od(this._threadBinding.getState().messages,e))}subscribe(e){return this._threadBinding.subscribe(e)}getModelContext(){return this._threadBinding.getState().getModelContext()}getModelConfig(){return this.getModelContext()}startRun(e){const t=e===null||typeof e=="string"?{parentId:e}:e;return this._threadBinding.getState().startRun(id(t))}unstable_resumeRun(e){return this._threadBinding.getState().resumeRun(sd(e))}unstable_loadExternalState(e){this._threadBinding.getState().unstable_loadExternalState(e)}cancelRun(){this._threadBinding.getState().cancelRun()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}export(){return this._threadBinding.getState().export()}import(e){this._threadBinding.getState().import(e)}reset(e){this._threadBinding.getState().reset(e)}getMessageByIndex(e){if(e<0)throw new Error("Message index must be >= 0");return this._getMessageRuntime(I(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.messages[${e}]`,messageSelector:{type:"index",index:e}}),()=>{var n,a;const t=this._threadBinding.getState().messages,r=t[e];if(r)return{message:r,parentId:(a=(n=t[e-1])==null?void 0:n.id)!=null?a:null,index:e}})}getMessageById(e){return this._getMessageRuntime(I(m({},this.path),{ref:this.path.ref+`${this.path.ref}.messages[messageId=${JSON.stringify(e)}]`,messageSelector:{type:"messageId",messageId:e}}),()=>this._threadBinding.getState().getMessageById(e))}_getMessageRuntime(e,t){return new ad(new Xe({path:e,getState:()=>{var d,c;const{message:r,parentId:n,index:a}=(d=t())!=null?d:{},{messages:s,speech:i}=this._threadBinding.getState();if(!r||n===void 0||a===void 0)return Ge;const l=this._threadBinding.getState().getBranches(r.id),u=r.metadata.submittedFeedback;return I(m({},r),{[qr]:r[qr],index:a,isLast:((c=s.at(-1))==null?void 0:c.id)===r.id,parentId:n,branchNumber:l.indexOf(r.id)+1,branchCount:l.length,speech:(i==null?void 0:i.messageId)===r.id?i:void 0,submittedFeedback:u})},subscribe:r=>this._threadBinding.subscribe(r)}),this._threadBinding)}unstable_on(e,t){let r=this._eventSubscriptionSubjects.get(e);return r||(r=new qs({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}},ud=e=>({mainThreadId:e.mainThreadId,newThread:e.newThreadId,threads:e.threadIds,archivedThreads:e.archivedThreadIds,isLoading:e.isLoading,threadItems:e.threadData}),Yr=(e,t)=>{if(t===void 0)return Ge;const r=e.getItemById(t);return r?{id:r.id,threadId:r.id,remoteId:r.remoteId,externalId:r.externalId,title:r.title,status:r.status,isMain:r.id===e.mainThreadId}:Ge},cd=class{constructor(e,t=ti){T(this,"_getState");T(this,"_mainThreadListItemRuntime");T(this,"main");this._core=e,this._runtimeFactory=t;const r=new Hn({path:{},getState:()=>ud(e),subscribe:n=>e.subscribe(n)});this._getState=r.getState.bind(r),this._mainThreadListItemRuntime=new Hr(new Xe({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>Yr(this._core,this._core.mainThreadId),subscribe:n=>this._core.subscribe(n)}),this._core),this.main=new t(new Jr({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>e.getMainThreadRuntimeCore(),subscribe:n=>e.subscribe(n)}),this._mainThreadListItemRuntime),this.__internal_bindMethods()}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getById=this.getById.bind(this),this.getItemById=this.getItemById.bind(this),this.getItemByIndex=this.getItemByIndex.bind(this),this.getArchivedItemByIndex=this.getArchivedItemByIndex.bind(this)}switchToThread(e){return this._core.switchToThread(e)}switchToNewThread(){return this._core.switchToNewThread()}getState(){return this._getState()}subscribe(e){return this._core.subscribe(e)}get mainItem(){return this._mainThreadListItemRuntime}getById(e){return new this._runtimeFactory(new Jr({path:{ref:`threads[threadId=${JSON.stringify(e)}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>this._core.getThreadRuntimeCore(e),subscribe:t=>this._core.subscribe(t)}),this.mainItem)}getItemByIndex(e){return new Hr(new Xe({path:{ref:`threadItems[${e}]`,threadSelector:{type:"index",index:e}},getState:()=>Yr(this._core,this._core.threadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getArchivedItemByIndex(e){return new Hr(new Xe({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:"archiveIndex",index:e}},getState:()=>Yr(this._core,this._core.archivedThreadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getItemById(e){return new Hr(new Xe({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>Yr(this._core,e),subscribe:t=>this._core.subscribe(t)}),this._core)}},dd=e=>e.startsWith("image/")?"image":e.startsWith("text/")?"document":"file",hd=class{constructor(e){T(this,"accept","*");T(this,"uploadedUrls",new Map);this.cloud=e}add(t){return Or(this,arguments,function*({file:e}){const r=crypto.randomUUID(),n=dd(e.type);let a={id:r,type:n,name:e.name,contentType:e.type,file:e,status:{type:"running",reason:"uploading",progress:0}};yield a;try{const{signedUrl:s,publicUrl:i}=yield new Ae(this.cloud.files.generatePresignedUploadUrl({filename:e.name}));yield new Ae(fetch(s,{method:"PUT",body:e,headers:{"Content-Type":e.type},mode:"cors"})),this.uploadedUrls.set(r,i),a=I(m({},a),{status:{type:"requires-action",reason:"composer-send"}}),yield a}catch(s){a=I(m({},a),{status:{type:"incomplete",reason:"error"}}),yield a}})}remove(e){return M(this,null,function*(){this.uploadedUrls.delete(e.id)})}send(e){return M(this,null,function*(){const t=this.uploadedUrls.get(e.id);if(!t)throw new Error("Attachment not uploaded");this.uploadedUrls.delete(e.id);let r;return e.type==="image"?r=[{type:"image",image:t,filename:e.name}]:r=[{type:"file",data:t,mimeType:e.contentType,filename:e.name}],I(m({},e),{status:{type:"complete"},content:r})})}},qn=b.createContext(null),Vn=({adapters:e,children:t})=>{const r=b.useContext(qn);return p.jsx(qn.Provider,{value:m(m({},r),e),children:t})},fd=()=>b.useContext(qn),pd=class extends Ts{constructor(t,r,{parentId:n,message:a}){var s;super();T(this,"_nonTextParts");T(this,"_previousText");T(this,"_parentId");T(this,"_sourceId");this.runtime=t,this.endEditCallback=r,this._parentId=n,this._sourceId=a.id,this._previousText=Vr(a),this.setText(this._previousText),this.setRole(a.role),this.setAttachments((s=a.attachments)!=null?s:[]),this._nonTextParts=a.content.filter(i=>i.type!=="text"),this.setRunConfig(m({},t.composer.runConfig))}get canCancel(){return!0}getAttachmentAdapter(){var t;return(t=this.runtime.adapters)==null?void 0:t.attachments}handleSend(t){return M(this,null,function*(){Vr(t)!==this._previousText&&this.runtime.append(I(m({},t),{content:[...t.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId})),this.handleCancel()})}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},md=class{constructor(e){T(this,"_subscriptions",new Set);T(this,"_isInitialized",!1);T(this,"repository",new $s);T(this,"composer",new Cs(this));T(this,"_editComposers",new Map);T(this,"_stopSpeaking");T(this,"speech");T(this,"_eventSubscribers",new Map);this._contextProvider=e}get messages(){return this.repository.getMessages()}get state(){var t;let e;for(const r of this.messages)if(r.role==="assistant"){e=r;break}return(t=e==null?void 0:e.metadata.unstable_state)!=null?t:null}getModelContext(){return this._contextProvider.getModelContext()}getEditComposer(e){return this._editComposers.get(e)}beginEdit(e){if(this._editComposers.has(e))throw new Error("Edit already in progress");this._editComposers.set(e,new pd(this,()=>this._editComposers.delete(e),this.repository.getMessage(e))),this._notifySubscribers()}getMessageById(e){try{return this.repository.getMessage(e)}catch(t){return}}getBranches(e){return this.repository.getBranches(e)}switchToBranch(e){this.repository.switchToBranch(e),this._notifySubscribers()}_notifySubscribers(){for(const e of this._subscriptions)e()}_notifyEventSubscribers(e){const t=this._eventSubscribers.get(e);if(t)for(const r of t)r()}subscribe(e){return this._subscriptions.add(e),()=>this._subscriptions.delete(e)}submitFeedback({messageId:e,type:t}){var s;const r=(s=this.adapters)==null?void 0:s.feedback;if(!r)throw new Error("Feedback adapter not configured");const{message:n,parentId:a}=this.repository.getMessage(e);if(r.submit({message:n,type:t}),n.role==="assistant"){const i=I(m({},n),{metadata:I(m({},n.metadata),{submittedFeedback:{type:t}})});this.repository.addOrUpdateMessage(a,i)}this._notifySubscribers()}speak(e){var s,i;const t=(s=this.adapters)==null?void 0:s.speech;if(!t)throw new Error("Speech adapter not configured");const{message:r}=this.repository.getMessage(e);(i=this._stopSpeaking)==null||i.call(this);const n=t.speak(Vr(r)),a=n.subscribe(()=>{n.status.type==="ended"?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:e,status:n.status},this._notifySubscribers()});this.speech={messageId:e,status:n.status},this._notifySubscribers(),this._stopSpeaking=()=>{n.cancel(),a(),this.speech=void 0,this._stopSpeaking=void 0}}stopSpeaking(){if(!this._stopSpeaking)throw new Error("No message is being spoken");this._stopSpeaking(),this._notifySubscribers()}ensureInitialized(){this._isInitialized||(this._isInitialized=!0,this._notifyEventSubscribers("initialize"))}export(){return this.repository.export()}import(e){this.ensureInitialized(),this.repository.clear(),this.repository.import(e),this._notifySubscribers()}reset(e){this.import(Un.fromArray(e!=null?e:[]))}unstable_on(e,t){var n,a,s;if(e==="model-context-update")return(s=(a=(n=this._contextProvider).subscribe)==null?void 0:a.call(n,t))!=null?s:(()=>{});const r=this._eventSubscribers.get(e);return r?r.add(t):this._eventSubscribers.set(e,new Set([t])),()=>{this._eventSubscribers.get(e).delete(t)}}},gd=e=>{try{return JSON.parse(e),!0}catch(t){return!1}};function yd({state:e,getTools:t,onResult:r,setToolStatuses:n}){const a=b.useRef({}),s=b.useRef(new Map),i=b.useRef(new AbortController),o=b.useRef(0),l=b.useRef([]),[u]=b.useState(()=>{const[h,g]=js(),w=rd(t,()=>{var x,y;return(y=(x=i.current)==null?void 0:x.signal)!=null?y:new AbortController().signal},(x,y)=>new Promise((E,_)=>{const O=s.current.get(x);O&&O.reject(new Error("Human input request was superseded by a new request")),s.current.set(x,{resolve:E,reject:_}),n(z=>I(m({},z),{[x]:{type:"interrupt",payload:{type:"human",payload:y}}}))}),{onExecutionStart:x=>{o.current++,n(y=>I(m({},y),{[x]:{type:"executing"}}))},onExecutionEnd:x=>{o.current--,n(y=>{const E=m({},y);return delete E[x],E}),o.current===0&&(l.current.forEach(y=>y()),l.current=[])}});return h.pipeThrough(w).pipeThrough(new zs).pipeTo(new WritableStream({write(x){var y;if(x.type==="result"){if((y=a.current[x.meta.toolCallId])!=null&&y.hasResult)return;r(m({type:"add-tool-result",toolCallId:x.meta.toolCallId,toolName:x.meta.toolName,result:x.result,isError:x.isError},x.artifact&&{artifact:x.artifact}))}}})),g}),d=b.useRef(new Set),c=b.useRef(!0);b.useEffect(()=>{const h=g=>{g.forEach(w=>{w.content.forEach(x=>{if(x.type==="tool-call"){if(c.current)d.current.add(x.toolCallId);else{if(d.current.has(x.toolCallId))return;let y=a.current[x.toolCallId];if(y||(y={argsText:"",hasResult:!1,argsComplete:!1,controller:u.addToolCallPart({toolName:x.toolName,toolCallId:x.toolCallId})},a.current[x.toolCallId]=y),x.argsText!==y.argsText)if(y.argsComplete)process.env.NODE_ENV!=="production"&&console.warn("argsText updated after controller was closed:",{previous:y.argsText,next:x.argsText});else{if(!x.argsText.startsWith(y.argsText))throw new Error(`Tool call argsText can only be appended, not updated: ${x.argsText} does not start with ${y.argsText}`);const E=x.argsText.slice(y.argsText.length);y.controller.argsText.append(E);const _=gd(x.argsText);_&&y.controller.argsText.close(),a.current[x.toolCallId]={argsText:x.argsText,hasResult:y.hasResult,argsComplete:_,controller:y.controller}}x.result!==void 0&&!y.hasResult&&(y.controller.setResponse(new gt({result:x.result,artifact:x.artifact,isError:x.isError})),y.controller.close(),a.current[x.toolCallId]={hasResult:!0,argsComplete:!0,argsText:y.argsText,controller:y.controller})}x.messages&&h(x.messages)}})})};h(e.messages),c.current&&(c.current=!1)},[e,u,r]);const f=()=>(s.current.forEach(({reject:h})=>{h(new Error("Tool execution aborted"))}),s.current.clear(),i.current.abort(),i.current=new AbortController,o.current===0?Promise.resolve():new Promise(h=>{l.current.push(h)}));return{reset:()=>{f(),c.current=!0},abort:f,resume:(h,g)=>{const w=s.current.get(h);if(w)s.current.delete(h),n(x=>I(m({},x),{[h]:{type:"executing"}})),w.resolve(g);else throw new Error(`Tool call ${h} is not waiting for human input`)}}}var bd=class{list(){return Promise.resolve({threads:[]})}rename(){return Promise.resolve()}archive(){return Promise.resolve()}unarchive(){return Promise.resolve()}delete(){return Promise.resolve()}initialize(e){return Promise.resolve({remoteId:e,externalId:void 0})}generateTitle(){return Promise.resolve(new ReadableStream)}fetch(e){return Promise.reject(new Error("Thread not found"))}};function xd(e,t){e.commitTasks.forEach(r=>{const n=r.cellIndex,a=t.cells[n];if(a.type!=="effect")throw new Error("Cannot find effect cell");let s=!0;if(a.deps!==void 0&&r.deps!==void 0&&(s=a.deps.length!==r.deps.length||a.deps.some((i,o)=>!Object.is(i,r.deps[o]))),s){if(a.mounted){if(typeof a.deps!=typeof r.deps)throw new Error("tapEffect called with and without dependencies across re-renders");try{a.mounted&&a.cleanup&&a.cleanup()}finally{a.mounted=!1}}try{const i=r.effect();if(i!==void 0&&typeof i!="function")throw new Error(`An effect function must either return a cleanup function or nothing. Received: ${typeof i}`);a.mounted=!0,a.cleanup=typeof i=="function"?i:void 0,a.deps=r.deps}catch(i){throw i}}})}function wd(e){let t=null;for(let r=e.cells.length-1;r>=0;r--){const n=e.cells[r];if((n==null?void 0:n.type)==="effect"&&n.mounted&&n.cleanup)try{n.cleanup()}catch(a){t==null&&(t=a)}finally{n.mounted=!1}}if(t!=null)throw t}var cr=null;function vd(e,t){e.currentIndex=0;const r=cr;cr=e;try{if(t(),e.isFirstRender=!1,e.cells.length!==e.currentIndex)throw new Error(`Rendered ${e.currentIndex} hooks but expected ${e.cells.length}. Hooks must be called in the exact same order in every render.`)}finally{cr=r}}function Wn(){if(!cr)throw new Error("No resource fiber available");return cr}function ri(e,t){const r=e[ni];if(!r)throw new Error("ResourceElement.type is not a valid Resource");return r(t)}var ni=Symbol("fnSymbol");function Gr(e,t){return{resource:e,scheduleRerender:t,cells:[],currentIndex:0,renderContext:void 0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function Bt(e){e.isMounted=!1,wd(e)}function dr(e,t){const r={commitTasks:[],props:t,state:void 0};return vd(e,()=>{e.renderContext=r;try{r.state=ri(e.resource,t)}finally{e.renderContext=void 0}}),r}function Rt(e,t){e.isMounted=!0,e.isNeverMounted=!1,xd(t,e)}var kd=globalThis.__ASSISTANT_UI_DISABLE_LAYOUT_EFFECT__===!0,ai=kd?b.useEffect:b.useLayoutEffect;function Jn(e){const[,t]=b.useState({}),r=b.useMemo(()=>Gr(e.type,()=>t({})),[e.type,t]),n=dr(r,e.props);return ai(()=>()=>Bt(r),[]),ai(()=>{Rt(r,n)}),n.state}var jt=e=>typeof e=="string"?{scope:e.split(".")[0],event:e}:{scope:e.scope,event:e.event},Ct=(e,t,r)=>t===e,$t,Kn=()=>{if($t)return $t;const e=()=>({apis:new Map,nextId:0,listeners:new Set});if(typeof window=="undefined")return $t=e(),$t;const t=window.__ASSISTANT_UI_DEVTOOLS_HOOK__;if(t)return $t=t,t;const r=e();return window.__ASSISTANT_UI_DEVTOOLS_HOOK__=r,$t=r,r},Sd=(tt=class{static register(t){var o,l;const r=Kn();for(const u of r.apis.values())if(u.api===t)return()=>{};const n=r.nextId++,a={api:t,logs:[]},s=(o=t.on)==null?void 0:o.call(t,"*",u=>{const d=r.apis.get(n);d&&(d.logs.push({time:new Date,event:u.event,data:u.payload}),d.logs.length>tt.MAX_EVENT_LOGS_PER_API&&(d.logs=d.logs.slice(-200)),tt.notifyListeners(n))}),i=(l=t.subscribe)==null?void 0:l.call(t,()=>{tt.notifyListeners(n)});return r.apis.set(n,a),tt.notifyListeners(n),()=>{const u=Kn();u.apis.get(n)&&(s==null||s(),i==null||i(),u.apis.delete(n),tt.notifyListeners(n))}}static notifyListeners(t){Kn().listeners.forEach(n=>n(t))}},T(tt,"MAX_EVENT_LOGS_PER_API",200),tt);function ye(e){const t=(r,n)=>m({type:t,props:r},(n==null?void 0:n.key)!==void 0&&{key:n.key});return t[ni]=e,t}var _d=e=>{if(e.renderContext)throw new Error("Resource updated during render");if(e.isNeverMounted)throw new Error("Resource updated before mount");e.isMounted&&e.scheduleRerender()};function Td(e){const t=Wn(),r=t.currentIndex++;if(!t.isFirstRender&&r>=t.cells.length)throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");if(!t.cells[r]){const s={type:"state",value:typeof e=="function"?e():e,set:i=>{const o=s.value,l=typeof i=="function"?i(o):i;Object.is(o,l)||(s.value=l,_d(t))}};t.cells[r]=s}const n=t.cells[r];if(n.type!=="state")throw new Error("Hook order changed between renders");return n}function at(e){const t=Td(e);return[t.value,t.set]}function Cd(){const e=Wn(),t=e.currentIndex++;if(!e.isFirstRender&&t>=e.cells.length)throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");if(!e.cells[t]){const n={type:"effect",mounted:!1};e.cells[t]=n}if(e.cells[t].type!=="effect")throw new Error("Hook order changed between renders");return t}function De(e,t){const r=Wn(),n=Cd();r.renderContext.commitTasks.push({effect:e,deps:t,cellIndex:n})}function Ut(e){const[t]=at(()=>({current:e}));return t}var Id=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Object.is(e[r],t[r]))return!1;return!0},ce=(e,t)=>{const r=Ut();return r.current||(r.current={value:e(),deps:t}),Id(r.current.deps,t)||(r.current.value=e(),r.current.deps=t),r.current.value};function Xr(e,t){const[r,n]=at({}),a=ce(()=>Gr(e.type,()=>n({})),[e.type]),s=t?ce(()=>e.props,t):e.props,i=ce(()=>dr(a,s),[a,s,r]);return De(()=>()=>Bt(a),[a]),De(()=>{Rt(a,i)},[a,i]),i.state}function Qe(e){return ri(e.type,e.props)}function si(e){const t=new Set;e.forEach((o,l)=>{if(o.key===void 0)throw new Error(`tapResources: All resource elements must have a key. Element at index ${l} is missing a key.`);if(t.has(o.key))throw new Error(`tapResources: Duplicate key "${o.key}" found. All keys must be unique.`);t.add(o.key)});const[r,n]=at({}),a=ce(()=>new Map(e.map(o=>[o.key,o])),[e]),[s]=at(()=>new Map),i=ce(()=>{const o=new Map,l=new Set;return a.forEach((u,d)=>{l.add(d);let c=s.get(d);(!c||c.resource!==u.type)&&(c&&Bt(c),c=Gr(u.type,()=>n({})),s.set(d,c));const f=dr(c,u.props);o.set(d,f)}),s.forEach((u,d)=>{l.has(d)||(Bt(u),s.delete(d))}),o},[a,r]);return De(()=>{i.forEach((o,l)=>{const u=s.get(l);u&&Rt(u,o)})},[i,s]),De(()=>()=>{s.forEach(o=>{Bt(o)}),s.clear()},[s]),ce(()=>e.map(o=>{var l;return(l=i.get(o.key))==null?void 0:l.state}),[e,i])}var Yn=[],Gn=!1;function Ed(){Gn=!1;const e=Yn;Yn=[];for(const t of e)try{t()}catch(r){console.error("Error in scheduled task:",r)}}function Ad(e){Yn.push(e),Gn||(Gn=!0,queueMicrotask(Ed))}var Md=(Lt=class{constructor(t){T(this,"_isDirty",!1);T(this,"_hasScheduledTask",!1);T(this,"_isFlushing",!1);this._task=t}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,!(this._hasScheduledTask||this._isFlushing)&&(this._hasScheduledTask=!0,Ad(()=>{this._hasScheduledTask=!1,this.flushSync()}))}flushSync(){if(this._isFlushing)return;this._isFlushing=!0;let t=0;try{for(;this._isDirty;){if(t++,t>Lt.MAX_FLUSH_DEPTH)throw new Error("Maximum update depth exceeded. This can happen when a resource repeatedly calls setState inside tapEffect.");this._isDirty=!1,this._task()}}finally{this._isFlushing=!1}}},T(Lt,"MAX_FLUSH_DEPTH",50),Lt),Pd=ye(({element:e,onUpdateInput:t,onFlushSync:r,onDispose:n})=>{const[a,s]=at(e.props),i=Qe({type:e.type,props:a}),o=Ut(new Set).current,l=Ut(i);return De(()=>{i!==l.current&&(l.current=i,o.forEach(d=>d()))}),ce(()=>({getState:()=>l.current,subscribe:d=>(o.add(d),()=>o.delete(d)),updateInput:d=>{t(),s(()=>d)},flushSync:r,dispose:n}),[])}),Nd=(e,t=!1)=>{let r=!t;const n={element:e,onUpdateInput:()=>{r||(r=!0,Rt(s,i))},onFlushSync:()=>{a.flushSync()},onDispose:()=>Bt(s)},a=new Md(()=>{i=dr(s,n),r&&Rt(s,i)}),s=Gr(Pd,()=>a.markDirty());let i=dr(s,n);return r&&Rt(s,i),i.state},hr=Symbol("tap.Context"),ii=e=>({[hr]:e}),oi=(e,t,r)=>{const n=e[hr];e[hr]=t;try{return r()}finally{e[hr]=n}},li=e=>e[hr];const ui=e=>{let t;const r=new Set,n=(u,d)=>{const c=typeof u=="function"?u(t):u;if(!Object.is(c,t)){const f=t;t=(d!=null?d:typeof c!="object"||c===null)?c:Object.assign({},t,c),r.forEach(h=>h(t,f))}},a=()=>t,o={setState:n,getState:a,getInitialState:()=>l,subscribe:u=>(r.add(u),()=>r.delete(u))},l=t=e(n,a,o);return o},Ld=(e=>e?ui(e):ui),Dd=e=>e;function Od(e,t=Dd){const r=b.useSyncExternalStore(e.subscribe,b.useCallback(()=>t(e.getState()),[e,t]),b.useCallback(()=>t(e.getInitialState()),[e,t]));return b.useDebugValue(r),r}const ci=e=>{const t=Ld(e),r=n=>Od(t,n);return Object.assign(r,t),r},Ht=(e=>e?ci(e):ci);function di(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function hi(...e){return t=>{let r=!1;const n=e.map(a=>{const s=di(a,t);return!r&&typeof s=="function"&&(r=!0),s});if(r)return()=>{for(let a=0;a<n.length;a++){const s=n[a];typeof s=="function"?s():di(e[a],null)}}}}function Qr(...e){return Z.useCallback(hi(...e),e)}var fi=ye(e=>{const t=ce(()=>Nd(e,!0),[e.type]);return De(()=>{t.updateInput(e.props)}),t}),Fd=class{constructor(e){this.getApi=e}get(e,t){return this.getApi()[t]}ownKeys(){return Object.keys(this.getApi())}has(e,t){return t in this.getApi()}getOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(this.getApi(),t)}set(){return!1}defineProperty(){return!1}deleteProperty(){return!1}},Ze=(e,t)=>{const r=Ut(e);De(()=>{r.current=e});const n=ce(()=>new Proxy({},new Fd(()=>r.current)),[]),a=t==null?void 0:t.key,s=e.getState();return ce(()=>({key:a,state:s,api:n}),[s,a])},yt=ye(e=>{const t=Ut(e.get);return De(()=>{t.current=e.get}),ce(()=>Me({source:e.source,query:e.query,get:()=>t.current()}),[e.source,JSON.stringify(e.query)])}),zd=ye(e=>{const t=Xr(e.scopeElement);return ce(()=>[e.fieldName,t],[e.fieldName,t])}),Bd=ye(e=>{const o=e,{on:t,subscribe:r,flushSync:n}=o,a=H(o,["on","subscribe","flushSync"]),s=Ut({on:t,subscribe:r,flushSync:n});De(()=>{s.current={on:t,subscribe:r,flushSync:n}});const i=si(Object.entries(a).map(([l,u])=>zd({fieldName:l,scopeElement:u},{key:l})));return ce(()=>{const l=Object.fromEntries(i),{on:u,subscribe:d,flushSync:c}=s.current;return u&&(l.on=(f,h)=>u(f,h)),d&&(l.subscribe=f=>d(f)),c&&(l.flushSync=()=>c()),l},[...i])}),pi=ii(null),Rd=(e,t)=>oi(pi,e,t),mi=()=>{const e=li(pi);if(!e)throw new Error("Model context is not available in this context");return e},jd=ye(({toolkit:e})=>{const[t,r]=at(()=>({tools:{}})),n=mi();De(()=>{if(!e)return;const s=[];for(const[l,u]of Object.entries(e))u.render&&s.push(a(l,u.render));const i=Object.entries(e).reduce((l,[u,d])=>{const h=d,{render:c}=h,f=H(h,["render"]);return l[u]=f,l},{}),o={getModelContext:()=>({tools:i})};return s.push(n.register(o)),()=>{s.forEach(l=>l())}},[e,n]);const a=(s,i)=>(r(o=>{var l;return I(m({},o),{tools:I(m({},o.tools),{[s]:[...(l=o.tools[s])!=null?l:[],i]})})}),()=>{r(o=>{var l,u;return I(m({},o),{tools:I(m({},o.tools),{[s]:(u=(l=o.tools[s])==null?void 0:l.filter(d=>d!==i))!=null?u:[]})})})});return Ze({getState:()=>t,setToolUI:a})}),$d=ye(()=>ce(()=>{const t=new Map;return{on:(r,n)=>{t.has(r)||t.set(r,new Set);const a=t.get(r);return a.add(n),()=>{a.delete(n),a.size===0&&t.delete(r)}},emit:(r,n)=>{const a=t.get(r),s=t.get("*");!a&&!s||queueMicrotask(()=>{if(a)for(const i of a)i(n);if(s)for(const i of s)i({event:r,payload:n})})}}},[])),gi=ii(null),Ud=(e,t)=>oi(gi,e,t),Xn=()=>{const e=li(gi);if(!e)throw new Error("Events context is not available");return e},Hd=ye(()=>{const[e]=at(()=>({})),t=new Fn;return Ze({getState:()=>e,getModelContext:()=>t.getModelContext(),subscribe:r=>t.subscribe(r),register:r=>t.registerModelContextProvider(r)})}),qd=ye(({threads:e,modelContext:t,tools:r})=>{const n=Qe($d()),{threads:a,tools:s,modelContext:i}=Ud(n,()=>{const l=Xr(t!=null?t:Hd(),[t]);return Rd(l.api,()=>({modelContext:l,tools:Xr(r!=null?r:jd({}),[r]),threads:Xr(e,[e])}))}),o=ce(()=>({threads:a.state,tools:s.state,modelContext:i.state}),[a.state,s.state,i.state]);return Ze({getState:()=>o,threads:a.api,tools:s.api,modelContext:i.api,on:n.on})}),Vd=e=>{const t=()=>e.getState().api.threads.item("main");return{threads:Me({source:"root",query:{},get:()=>e.getState().api.threads}),tools:Me({source:"root",query:{},get:()=>e.getState().api.tools}),modelContext:Me({source:"root",query:{},get:()=>e.getState().api.modelContext}),thread:Me({source:"threads",query:{type:"main"},get:()=>e.getState().api.threads.thread("main")}),threadListItem:Me({source:"threads",query:{type:"main"},get:()=>t()}),composer:Me({source:"thread",query:{},get:()=>e.getState().api.threads.thread("main").composer}),on(r,n){const{event:a,scope:s}=jt(r);if(s==="*")return e.getState().api.on(a,n);if(Ct("thread",s)||Ct("thread-list-item",s)||Ct("composer",s))return e.getState().api.on(a,i=>{i.threadId===t().getState().id&&n(i)});throw new Error(`Event scope is not available in this component: ${s}`)},subscribe:e.subscribe,flushSync:e.flushSync}},Wd=e=>{const t=Zr(),r=Jn(fi(qd(e))),n=b.useMemo(()=>Vd(r),[r]);return b.useMemo(()=>bi(t,n),[t,n])},Me=e=>{const t=e.get;return t.source=e.source,t.query=e.query,t},bt=()=>()=>{},yi=b.createContext({threads:Me({source:null,query:{},get:()=>{throw new Error("Threads is only available inside <AssistantProvider />")}}),tools:Me({source:null,query:{},get:()=>{throw new Error("Tools is only available inside <AssistantProvider />")}}),modelContext:Me({source:null,query:{},get:()=>{throw new Error("ModelContext is only available inside <AssistantProvider />")}}),threadListItem:Me({source:null,query:{},get:()=>{throw new Error("ThreadListItem is only available inside <AssistantProvider />")}}),thread:Me({source:null,query:{},get:()=>{throw new Error("Thread is only available inside <AssistantProvider />")}}),composer:Me({source:null,query:{},get:()=>{throw new Error("Composer is only available inside <AssistantProvider />")}}),message:Me({source:null,query:{},get:()=>{throw new Error("Message is only available inside <ThreadPrimitive.Messages />")}}),part:Me({source:null,query:{},get:()=>{throw new Error("Part is only available inside <MessagePrimitive.Parts />")}}),attachment:Me({source:null,query:{},get:()=>{throw new Error("Attachment is only available inside <MessagePrimitive.Attachments /> or <ComposerPrimitive.Attachments />")}}),subscribe:bt,flushSync:bt,on:e=>{const{scope:t}=jt(e);throw new Error(`Event scope is not available in this component: ${t}`)}}),Zr=()=>b.useContext(yi),It=e=>{const t=Zr(),r=Jn(Bd(e));return b.useMemo(()=>bi(t,r),[t,r])},Jd=e=>Wd(e);function pe(e){return e?Jd(e):Zr()}var Kd=(e,t)=>e===bt?t:t===bt?e:(...r)=>{e(...r),t(...r)},Yd=(e,t)=>e===bt?t:t===bt?e:(...r)=>{const n=e(...r),a=t(...r);return()=>{n(),a()}},bi=(e,t)=>{const r=t.subscribe,n=t.flushSync;return I(m(m({},e),t),{subscribe:Yd(e.subscribe,r!=null?r:bt),flushSync:Kd(e.flushSync,n!=null?n:bt)})},xt=({api:e,children:t,devToolsVisible:r=!0})=>(b.useEffect(()=>{if(!(!r||!e.subscribe))return Sd.register(e)},[e,r]),p.jsx(yi.Provider,{value:e,children:t})),xi=(Fu=class{constructor(e){nr(this,Ke);ar(this,Ke,e)}get threads(){return We(this,Ke).threads().getState()}get tools(){return We(this,Ke).tools().getState()}get threadListItem(){return We(this,Ke).threadListItem().getState()}get thread(){return We(this,Ke).thread().getState()}get composer(){return We(this,Ke).composer().getState()}get message(){return We(this,Ke).message().getState()}get part(){return We(this,Ke).part().getState()}get attachment(){return We(this,Ke).attachment().getState()}},Ke=new WeakMap,Fu),ee=e=>{const t=pe(),r=b.useMemo(()=>new xi(t),[t]),n=b.useSyncExternalStore(t.subscribe,()=>e(r),()=>e(r));if(b.useDebugValue(n),n instanceof xi)throw new Error("You tried to return the entire AssistantState. This is not supported due to technical limitations.");return n},Qn=(e,t)=>{const r=pe(),n=b.useRef(t);b.useEffect(()=>{n.current=t});const{scope:a,event:s}=jt(e);b.useEffect(()=>r.on({scope:a,event:s},i=>n.current(i)),[r,a,s])};function Gd(e,t){function r(n){const a=b.useContext(e);if(!(n!=null&&n.optional)&&!a)throw new Error(`This component must be used within ${t}.`);return a}return r}function wi(e,t){function r(a){const s=e(a);return s?s[t]:null}function n(a){let s=!1,i;typeof a=="function"?i=a:a&&typeof a=="object"&&(s=!!a.optional,i=a.selector);const o=r({optional:s});return o?i?o(i):o():null}return{[t]:n,[`${t}Store`]:r}}var vi=b.createContext(null),Xd=Gd(vi,"ThreadPrimitive.Viewport"),{useThreadViewport:en,useThreadViewportStore:Zn}=wi(Xd,"useThreadViewport"),Qd=e=>{var r;const t=e;t.__isBound||((r=t.__internal_bindMethods)==null||r.call(t),t.__isBound=!0)};function Zd(e,t=eh){Qd(e);const r=b.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getState()));return b.useDebugValue(r),r}var eh=e=>e;function ki(e){function t(r){let n=!1,a;typeof r=="function"?a=r:r&&(n=!!r.optional,a=r.selector);const s=e({optional:n});return s?Zd(s,a):null}return t}function th(e){var n,a,s;const r=(s=(a=(n=pe().threads()).__internal_getAssistantRuntime)==null?void 0:a.call(n))!=null?s:null;if(!r)throw new Error("AssistantRuntime is not available");return r}function Si(e){const t=pe(),r=ee(()=>{var n,a,s;return t.thread.source&&(s=(a=(n=t.thread()).__internal_getRuntime)==null?void 0:a.call(n))!=null?s:null});if(!r&&!(e!=null&&e.optional))throw new Error("ThreadRuntime is not available");return r}var _i=ki(Si);function Ti(e){const t=pe(),r=ee(()=>{var n,a,s;return t.threadListItem.source&&(s=(a=(n=t.threadListItem()).__internal_getRuntime)==null?void 0:a.call(n))!=null?s:null});if(!r&&!(e!=null&&e.optional))throw new Error("ThreadListItemRuntime is not available");return r}var Ci=ki(Ti),Et=e=>{const[,t]=at(e.getState);return De(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},rh=ye(({runtime:e})=>{const t=Et(e),r=Xn();return De(()=>{const n=[],a=["switched-to","switched-away"];for(const s of a){const i=e.unstable_on(s,()=>{r.emit(`thread-list-item.${s}`,{threadId:e.getState().id})});n.push(i)}return()=>{for(const s of n)s()}},[e,r]),Ze({getState:()=>t,switchTo:e.switchTo,rename:e.rename,archive:e.archive,unarchive:e.unarchive,delete:e.delete,generateTitle:e.generateTitle,initialize:e.initialize,detach:e.detach,__internal_getRuntime:()=>e},{key:t.id})}),fr=e=>{const t=si(e);return{state:t.map(r=>r.state),api:r=>{var a,s;const n="index"in r?(a=t[r.index])==null?void 0:a.api:(s=t.find(i=>i.key===r.key))==null?void 0:s.api;if(!n)throw new Error(`tapLookupResources: Resource not found for lookup: ${JSON.stringify(r)}`);return n}}},Ii=ye(({runtime:e})=>{const t=Et(e);return Ze({getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e},{key:t.id})}),nh=ye(({runtime:e,index:t})=>{const r=ce(()=>e.getAttachmentByIndex(t),[e,t]);return Qe(Ii({runtime:r}))}),Ei=ye(({threadIdRef:e,messageIdRef:t,runtime:r})=>{var o;const n=Et(r),a=Xn();De(()=>{const l=[],u=["send","attachment-add"];for(const d of u){const c=r.unstable_on(d,()=>{a.emit(`composer.${d}`,m({threadId:e.current},t&&{messageId:t.current}))});l.push(c)}return()=>{for(const d of l)d()}},[r,a,e,t]);const s=fr(n.attachments.map((l,u)=>nh({runtime:r,index:u},{key:u}))),i=ce(()=>{var l;return{text:n.text,role:n.role,attachments:s.state,runConfig:n.runConfig,isEditing:n.isEditing,canCancel:n.canCancel,attachmentAccept:n.attachmentAccept,isEmpty:n.isEmpty,type:(l=n.type)!=null?l:"thread"}},[n,s.state]);return Ze({getState:()=>i,setText:r.setText,setRole:r.setRole,setRunConfig:r.setRunConfig,addAttachment:r.addAttachment,reset:r.reset,clearAttachments:r.clearAttachments,send:r.send,cancel:r.cancel,beginEdit:(o=r.beginEdit)!=null?o:(()=>{throw new Error("beginEdit is not supported in this runtime")}),attachment:l=>"id"in l?s.api({key:l.id}):s.api(l),__internal_getRuntime:()=>r})}),ah=ye(({runtime:e})=>{const t=Et(e);return Ze({getState:()=>t,addToolResult:n=>e.addToolResult(n),resumeToolCall:n=>e.resumeToolCall(n),__internal_getRuntime:()=>e},{key:t.type==="tool-call"?`toolCallId-${t.toolCallId}`:void 0})}),sh=ye(({runtime:e,index:t})=>{const r=ce(()=>e.getAttachmentByIndex(t),[e,t]);return Qe(Ii({runtime:r}))}),ih=ye(({runtime:e,index:t})=>{const r=ce(()=>e.getMessagePartByIndex(t),[e,t]);return Qe(ah({runtime:r}))}),oh=ye(({runtime:e,threadIdRef:t})=>{var f,h;const r=Et(e),[n,a]=at(!1),[s,i]=at(!1),o=ce(()=>({get current(){return e.getState().id}}),[e]),l=Qe(Ei({runtime:e.composer,threadIdRef:t,messageIdRef:o})),u=fr(r.content.map((g,w)=>ih({runtime:e,index:w},{key:w}))),d=fr((h=(f=r.attachments)==null?void 0:f.map((g,w)=>sh({runtime:e,index:w},{key:w})))!=null?h:[]),c=ce(()=>I(m({},r),{parts:u.state,composer:l.state,isCopied:n,isHovering:s}),[r,u.state,l.state,n,s]);return Ze({getState:()=>c,composer:l.api,reload:g=>e.reload(g),speak:()=>e.speak(),stopSpeaking:()=>e.stopSpeaking(),submitFeedback:g=>e.submitFeedback(g),switchToBranch:g=>e.switchToBranch(g),getCopyText:()=>e.unstable_getCopyText(),part:g=>"index"in g?u.api({index:g.index}):u.api({key:`toolCallId-${g.toolCallId}`}),attachment:g=>"id"in g?d.api({key:g.id}):d.api(g),setIsCopied:a,setIsHovering:i,__internal_getRuntime:()=>e},{key:r.id})}),lh=ye(({runtime:e,id:t,threadIdRef:r})=>{const n=ce(()=>e.getMessageById(t),[e,t]);return Qe(oh({runtime:n,threadIdRef:r}))}),uh=ye(({runtime:e})=>{const t=Et(e),r=Xn();De(()=>{const o=[],l=["run-start","run-end","initialize","model-context-update"];for(const u of l){const d=e.unstable_on(u,()=>{var f;const c=((f=e.getState())==null?void 0:f.threadId)||"unknown";r.emit(`thread.${u}`,{threadId:c})});o.push(d)}return()=>{for(const u of o)u()}},[e]);const n=ce(()=>({get current(){return e.getState().threadId}}),[e]),a=Qe(Ei({runtime:e.composer,threadIdRef:n})),s=fr(t.messages.map(o=>lh({runtime:e,id:o.id,threadIdRef:n},{key:o.id}))),i=ce(()=>({isEmpty:s.state.length===0&&!t.isLoading,isDisabled:t.isDisabled,isLoading:t.isLoading,isRunning:t.isRunning,capabilities:t.capabilities,state:t.state,suggestions:t.suggestions,extras:t.extras,speech:t.speech,composer:a.state,messages:s.state}),[t,s,a.state]);return Ze({getState:()=>i,composer:a.api,append:e.append,startRun:e.startRun,unstable_resumeRun:e.unstable_resumeRun,cancelRun:e.cancelRun,getModelContext:e.getModelContext,export:e.export,import:e.import,reset:e.reset,stopSpeaking:e.stopSpeaking,startVoice:()=>M(null,null,function*(){throw new Error("startVoice is not supported in this runtime")}),stopVoice:()=>M(null,null,function*(){throw new Error("stopVoice is not supported in this runtime")}),message:o=>"id"in o?s.api({key:o.id}):s.api(o),__internal_getRuntime:()=>e})}),ch=ye(({runtime:e,id:t})=>{const r=ce(()=>e.getItemById(t),[e,t]);return Qe(rh({runtime:r}))}),dh=ye(({runtime:e,__internal_assistantRuntime:t})=>{const r=Et(e),n=Qe(uh({runtime:e.main})),a=fr(Object.keys(r.threadItems).map(i=>ch({runtime:e,id:i},{key:i}))),s=ce(()=>{var i;return{mainThreadId:r.mainThreadId,newThreadId:(i=r.newThread)!=null?i:null,isLoading:r.isLoading,threadIds:r.threads,archivedThreadIds:r.archivedThreads,threadItems:a.state,main:n.state}},[r,a.state,n.state]);return Ze({getState:()=>s,thread:()=>n.api,item:i=>{if(i==="main")return a.api({key:s.mainThreadId});if("id"in i)return a.api({key:i.id});const{index:o,archived:l=!1}=i,u=l?s.archivedThreadIds[o]:s.threadIds[o];return a.api({key:u})},switchToThread:i=>{e.switchToThread(i)},switchToNewThread:()=>{e.switchToNewThread()},__internal_getAssistantRuntime:()=>t})}),hh=ye(e=>{const t=mi();return De(()=>e.registerModelContextProvider(t),[e,t]),Qe(dh({runtime:e.threads,__internal_assistantRuntime:e}))}),ea=e=>{const t=new Map,r=()=>{let n=0;for(const a of t.values())n+=a;e(n)};return{register:()=>{const n=Symbol();return t.set(n,0),{setHeight:a=>{t.get(n)!==a&&(t.set(n,a),r())},unregister:()=>{t.delete(n),r()}}}}},fh=(e={})=>{const t=new Set,r=ea(i=>{s.setState({height:I(m({},s.getState().height),{viewport:i})})}),n=ea(i=>{s.setState({height:I(m({},s.getState().height),{inset:i})})}),a=ea(i=>{s.setState({height:I(m({},s.getState().height),{userMessage:i})})}),s=Ht(()=>{var i;return{isAtBottom:!0,scrollToBottom:({behavior:o="auto"}={})=>{for(const l of t)l({behavior:o})},onScrollToBottom:o=>(t.add(o),()=>{t.delete(o)}),turnAnchor:(i=e.turnAnchor)!=null?i:"bottom",height:{viewport:0,inset:0,userMessage:0},registerViewport:r.register,registerContentInset:n.register,registerUserMessageHeight:a.register}});return s},pr=e=>e,ph=e=>{const t=Zn({optional:!0}),[r]=b.useState(()=>fh(e));return b.useEffect(()=>t==null?void 0:t.getState().onScrollToBottom(()=>{r.getState().scrollToBottom()}),[t,r]),b.useEffect(()=>{if(t)return r.subscribe(n=>{t.getState().isAtBottom!==n.isAtBottom&&pr(t).setState({isAtBottom:n.isAtBottom})})},[r,t]),b.useEffect(()=>{var s;const n={turnAnchor:(s=e.turnAnchor)!=null?s:"bottom"};r.getState().turnAnchor!==n.turnAnchor&&pr(r).setState(n)},[r,e.turnAnchor]),r},Ai=({children:e,options:t={}})=>{const r=ph(t),[n]=b.useState(()=>({useThreadViewport:r}));return p.jsx(vi.Provider,{value:n,children:e})},mh=e=>{var t;return(t=e._core)==null?void 0:t.RenderComponent},gh=({children:e,runtime:t})=>{const r=pe({threads:hh(t)}),n=mh(t);return p.jsxs(xt,{api:r,children:[n&&p.jsx(n,{}),p.jsx(Ai,{children:e})]})},Mi=b.memo(gh),yh=({index:e,archived:t,children:r})=>{const n=pe(),a=It({threadListItem:yt({source:"threads",query:{type:"index",index:e,archived:t},get:()=>n.threads().item({index:e,archived:t})}),on(s,i){const o=()=>n.threads().item({index:e,archived:t}),{event:l,scope:u}=jt(s);return Ct("thread-list-item",u)?n.on({scope:"*",event:l},d=>{d.threadId===o().getState().id&&i(d)}):n.on(s,i)}});return p.jsx(xt,{api:a,children:r})},bh=({id:e,children:t})=>{const r=pe(),n=It({threadListItem:yt({source:"threads",query:{type:"id",id:e},get:()=>r.threads().item({id:e})}),on(a,s){const i=()=>r.threads().item({id:e}),{event:o,scope:l}=jt(a);return Ct("thread-list-item",l)?r.on({scope:"*",event:o},u=>{u.threadId===i().getState().id&&s(u)}):r.on(a,s)}});return p.jsx(xt,{api:n,children:t})},xh=({index:e,children:t})=>{const r=pe(),n=It({message:yt({source:"thread",query:{type:"index",index:e},get:()=>r.thread().message({index:e})}),composer:yt({source:"message",query:{},get:()=>r.thread().message({index:e}).composer}),on(a,s){const i=()=>r.thread().message({index:e}),{event:o,scope:l}=jt(a);return!Ct("composer",l)&&!Ct("message",l)?r.on(a,s):r.on({scope:"thread",event:o},u=>{u.messageId===i().getState().id&&s(u)})}});return p.jsx(xt,{api:n,children:t})},wh=({index:e,children:t})=>{const r=pe(),n=It({part:yt({source:"message",query:{type:"index",index:e},get:()=>r.message().part({index:e})})});return p.jsx(xt,{api:n,children:t})},vh=({index:e,children:t})=>{const r=pe(),n=It({attachment:yt({source:"message",query:{type:"index",index:e},get:()=>r.message().attachment({index:e})})});return p.jsx(xt,{api:n,children:t})},kh=({index:e,children:t})=>{const r=pe(),n=It({attachment:yt({source:"composer",query:{type:"index",index:e},get:()=>r.composer().attachment({index:e})})});return p.jsx(xt,{api:n,children:t})},Sh=ye(({text:e,isRunning:t})=>{const r=ce(()=>({type:"text",text:e,status:t?{type:"running"}:{type:"complete"}}),[e,t]);return Ze({getState:()=>r,addToolResult:()=>{throw new Error("Not supported")},resumeToolCall:()=>{throw new Error("Not supported")}})}),_h=({text:e,isRunning:t=!1,children:r})=>{const n=Jn(fi(Sh({text:e,isRunning:t}))),a=It({part:yt({source:"root",query:{},get:()=>n.getState().api}),subscribe:n.subscribe,flushSync:n.flushSync});return p.jsx(xt,{api:a,children:r})},Pi=(e,t)=>{var r,n;return t===void 0?((r=e.status)==null?void 0:r.type)==="requires-action"&&e.status.reason==="tool-calls"&&e.content.every(a=>a.type!=="tool-call"||!!a.result):((n=e.status)==null?void 0:n.type)==="requires-action"&&e.status.reason==="tool-calls"&&e.content.every(a=>a.type!=="tool-call"||!!a.result||!t.includes(a.toolName))},ta=class extends Error{constructor(t,r){super(r);T(this,"name","AbortError");T(this,"detach");this.detach=t}},Th=class extends md{constructor(t,r){super(t);T(this,"capabilities",{switchToBranch:!0,switchBranchDuringRun:!0,edit:!0,reload:!0,cancel:!0,unstable_copy:!0,speech:!1,attachments:!1,feedback:!1});T(this,"abortController",null);T(this,"isDisabled",!1);T(this,"_isLoading",!1);T(this,"_suggestions",[]);T(this,"_suggestionsController",null);T(this,"_options");T(this,"_lastRunConfig",{});T(this,"_loadPromise");this.__internal_setOptions(r)}get isLoading(){return this._isLoading}get suggestions(){return this._suggestions}get adapters(){return this._options.adapters}get extras(){}__internal_setOptions(t){var i,o,l;if(this._options===t)return;this._options=t;let r=!1;const n=((i=t.adapters)==null?void 0:i.speech)!==void 0;this.capabilities.speech!==n&&(this.capabilities.speech=n,r=!0);const a=((o=t.adapters)==null?void 0:o.attachments)!==void 0;this.capabilities.attachments!==a&&(this.capabilities.attachments=a,r=!0);const s=((l=t.adapters)==null?void 0:l.feedback)!==void 0;this.capabilities.feedback!==s&&(this.capabilities.feedback=s,r=!0),r&&this._notifySubscribers()}__internal_load(){var r,n;if(this._loadPromise)return this._loadPromise;const t=(n=(r=this.adapters.history)==null?void 0:r.load())!=null?n:Promise.resolve(null);return this._isLoading=!0,this._notifySubscribers(),this._loadPromise=t.then(a=>{var i,o;if(!a)return;this.repository.import(a),this._notifySubscribers();const s=(o=(i=this.adapters.history)==null?void 0:i.resume)==null?void 0:o.bind(this.adapters.history);a.unstable_resume&&s&&this.startRun({parentId:this.repository.headId,sourceId:this.repository.headId,runConfig:this._lastRunConfig},s)}).finally(()=>{this._isLoading=!1,this._notifySubscribers()}),this._loadPromise}append(t){return M(this,null,function*(){var a,s,i;this.ensureInitialized();const r=lr(t,_t(),{type:"complete",reason:"unknown"});this.repository.addOrUpdateMessage(t.parentId,r),(a=this._options.adapters.history)==null||a.append(m({parentId:t.parentId,message:r},t.runConfig!==void 0&&{runConfig:t.runConfig})),((s=t.startRun)!=null?s:t.role==="user")?yield this.startRun({parentId:r.id,sourceId:t.sourceId,runConfig:(i=t.runConfig)!=null?i:{}}):(this.repository.resetHead(r.id),this._notifySubscribers())})}resumeRun(n){var a=n,{stream:t}=a,r=H(a,["stream"]);if(!t)throw new Error("You must pass a stream parameter to resume runs.");return this.startRun(r,t)}unstable_loadExternalState(){throw new Error("Runtime does not support importing external states.")}startRun(a,s){return M(this,arguments,function*({parentId:t,runConfig:r},n){var u,d,c;this.ensureInitialized();let o={id:_t(),role:"assistant",status:{type:"running"},content:[],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],custom:{}},createdAt:new Date};this._notifyEventSubscribers("run-start");try{this._suggestions=[],(u=this._suggestionsController)==null||u.abort(),this._suggestionsController=null,this._notifySubscribers();do o=yield this.performRoundtrip(t,o,r,n),n=void 0;while(Pi(o,this._options.unstable_humanToolNames))}finally{this._notifyEventSubscribers("run-end")}this._suggestionsController=new AbortController;const l=this._suggestionsController.signal;if(this.adapters.suggestion&&((d=o.status)==null?void 0:d.type)!=="requires-action"){const x=(c=this.adapters.suggestion)==null?void 0:c.generate({messages:this.messages});if(Symbol.asyncIterator in x)try{for(var f=Ft(x),h,g,w;h=!(g=yield f.next()).done;h=!1){const y=g.value;if(l.aborted)break;this._suggestions=y,this._notifySubscribers()}}catch(g){w=[g]}finally{try{h&&(g=f.return)&&(yield g.call(f))}finally{if(w)throw w[0]}}else{const y=yield x;if(l.aborted)return;this._suggestions=y,this._notifySubscribers()}}})}performRoundtrip(t,r,n,a){return M(this,null,function*(){var g,w,x,y,E,_,O,z,C,D;const s=t?this.repository.getMessages(t):[];(g=this.abortController)==null||g.abort(),this.abortController=new AbortController;const i=r.content,o=(w=r.metadata)==null?void 0:w.unstable_annotations,l=(x=r.metadata)==null?void 0:x.unstable_data,u=(y=r.metadata)==null?void 0:y.steps,d=(E=r.metadata)==null?void 0:E.custom,c=N=>{var ie,v,Y,we,k,Se;const K=(ie=N.metadata)==null?void 0:ie.steps,B=K?[...u!=null?u:[],...K]:void 0,P=(v=N.metadata)==null?void 0:v.unstable_annotations,q=(Y=N.metadata)==null?void 0:Y.unstable_data,J=P?[...o!=null?o:[],...P]:void 0,ue=q?[...l!=null?l:[],...q]:void 0;r=m(I(m(m({},r),N.content?{content:[...i,...(we=N.content)!=null?we:[]]}:void 0),{status:(k=N.status)!=null?k:r.status}),N.metadata?{metadata:m(m(m(m(m(m({},r.metadata),N.metadata.unstable_state?{unstable_state:N.metadata.unstable_state}:void 0),J?{unstable_annotations:J}:void 0),ue?{unstable_data:ue}:void 0),B?{steps:B}:void 0),(Se=N.metadata)!=null&&Se.custom?{custom:m(m({},d!=null?d:{}),N.metadata.custom)}:void 0)}:void 0),this.repository.addOrUpdateMessage(t,r),this._notifySubscribers()},f=(_=this._options.maxSteps)!=null?_:2;if(((C=(z=(O=r.metadata)==null?void 0:O.steps)==null?void 0:z.length)!=null?C:0)>=f)return c({status:{type:"incomplete",reason:"tool-calls"}}),r;c({status:{type:"running"}}),this.repository.resetHead(r.id),this._notifySubscribers();try{this._lastRunConfig=n!=null?n:{};const N=this.getModelContext();a=a!=null?a:this.adapters.chatModel.run.bind(this.adapters.chatModel);const K=this.abortController.signal,B=a({messages:s,runConfig:this._lastRunConfig,abortSignal:K,context:N,config:N,unstable_assistantMessageId:r.id,unstable_getMessage(){return r}});if(Symbol.asyncIterator in B)try{for(var U=Ft(B),V,R,S;V=!(R=yield U.next()).done;V=!1){const P=R.value;if(K.aborted){c({status:{type:"incomplete",reason:"cancelled"}});break}c(P)}}catch(R){S=[R]}finally{try{V&&(R=U.return)&&(yield R.call(U))}finally{if(S)throw S[0]}}else c(yield B);r.status.type==="running"&&c({status:{type:"complete",reason:"unknown"}})}catch(N){if(N instanceof ta)c({status:{type:"incomplete",reason:"cancelled"}});else throw c({status:{type:"incomplete",reason:"error",error:N instanceof Error?N.message:`[${typeof N}] ${new String(N).toString()}`}}),N}finally{this.abortController=null,(r.status.type==="complete"||r.status.type==="incomplete")&&(yield(D=this._options.adapters.history)==null?void 0:D.append({parentId:t,message:r,runConfig:this._lastRunConfig}))}return r})}detach(){var r;const t=new ta(!0);(r=this.abortController)==null||r.abort(t),this.abortController=null}cancelRun(){var r;const t=new ta(!1);(r=this.abortController)==null||r.abort(t),this.abortController=null}addToolResult({messageId:t,toolCallId:r,result:n,isError:a,artifact:s}){const i=this.repository.getMessage(t),{parentId:o}=i;let{message:l}=i;if(l.role!=="assistant")throw new Error("Tried to add tool result to non-assistant message");let u=!1,d=!1;const c=l.content.map(f=>f.type!=="tool-call"||f.toolCallId!==r?f:(d=!0,f.result||(u=!0),I(m({},f),{result:n,artifact:s,isError:a})));if(!d)throw new Error("Tried to add tool result to non-existing tool call");l=I(m({},l),{content:c}),this.repository.addOrUpdateMessage(o,l),u&&Pi(l,this._options.unstable_humanToolNames)&&this.performRoundtrip(o,l,this._lastRunConfig)}resumeToolCall(t){throw new Error("Local runtime does not support resuming tool calls.")}},Ni=Object.freeze([]),ra="__DEFAULT_ID__",Ch=Object.freeze({[ra]:{id:ra,remoteId:void 0,externalId:void 0,status:"regular",title:void 0}}),Ih=class extends ir{constructor(t){super();T(this,"_mainThread");this._mainThread=t()}get isLoading(){return!1}getMainThreadRuntimeCore(){return this._mainThread}get newThreadId(){throw new Error("Method not implemented.")}get threadIds(){throw Ni}get archivedThreadIds(){throw Ni}get mainThreadId(){return ra}get threadData(){return Ch}getThreadRuntimeCore(){throw new Error("Method not implemented.")}getLoadThreadsPromise(){throw new Error("Method not implemented.")}getItemById(t){if(t===this.mainThreadId)return{status:"regular",id:this.mainThreadId,remoteId:this.mainThreadId,externalId:void 0,title:void 0,isMain:!0};throw new Error("Method not implemented")}switchToThread(){return M(this,null,function*(){throw new Error("Method not implemented.")})}switchToNewThread(){throw new Error("Method not implemented.")}rename(){throw new Error("Method not implemented.")}archive(){throw new Error("Method not implemented.")}detach(){throw new Error("Method not implemented.")}unarchive(){throw new Error("Method not implemented.")}delete(){throw new Error("Method not implemented.")}initialize(t){return Promise.resolve({remoteId:t,externalId:void 0})}generateTitle(){throw new Error("Method not implemented.")}},Eh=class extends zn{constructor(t,r){super();T(this,"threads");T(this,"Provider");T(this,"_options");this._options=t,this.threads=new Ih(()=>new Th(this._contextProvider,this._options)),r&&this.threads.getMainThreadRuntimeCore().import(Un.fromArray(r))}},Li=e=>{try{const r=e.split(".")[1];if(!r)throw new Error("Invalid JWT format");let n=r.replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4!==0;)n+="=";const a=atob(n),i=JSON.parse(a).exp;if(!i||typeof i!="number")throw new Error('JWT does not contain a valid "exp" field');return i*1e3}catch(t){throw new Error(`Unable to determine the token expiry: ${t}`)}},Di=(zu=class{constructor(e){T(this,"strategy","jwt");T(this,"cachedToken",null);T(this,"tokenExpiry",null);nr(this,Ar);ar(this,Ar,e)}getAuthHeaders(){return M(this,null,function*(){const e=Date.now();if(this.cachedToken&&this.tokenExpiry&&this.tokenExpiry-e>30*1e3)return{Authorization:`Bearer ${this.cachedToken}`};const t=yield We(this,Ar).call(this);return t?(this.cachedToken=t,this.tokenExpiry=Li(t),{Authorization:`Bearer ${t}`}):!1})}readAuthHeaders(e){const t=e.get("Authorization");if(!t)return;const[r,n]=t.split(" ");if(r!=="Bearer"||!n)throw new Error("Invalid auth header received");this.cachedToken=n,this.tokenExpiry=Li(n)}},Ar=new WeakMap,zu),Ah=(Bu=class{constructor(e,t,r){T(this,"strategy","api-key");nr(this,Mr);nr(this,Pr);nr(this,Nr);ar(this,Mr,e),ar(this,Pr,t),ar(this,Nr,r)}getAuthHeaders(){return M(this,null,function*(){return{Authorization:`Bearer ${We(this,Mr)}`,"Aui-User-Id":We(this,Pr),"Aui-Workspace-Id":We(this,Nr)}})}readAuthHeaders(){}},Mr=new WeakMap,Pr=new WeakMap,Nr=new WeakMap,Bu),tn="aui:refresh_token",Mh=class{constructor(e){T(this,"strategy","anon");T(this,"baseUrl");T(this,"jwtStrategy");this.baseUrl=e,this.jwtStrategy=new Di(()=>M(this,null,function*(){const t=Date.now(),r=localStorage.getItem(tn),n=r?JSON.parse(r):void 0;if(n)if(new Date(n.expires_at).getTime()-t>30*1e3){const u=yield fetch(`${this.baseUrl}/v1/auth/tokens/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:n.token})});if(u.ok){const d=yield u.json(),{access_token:c,refresh_token:f}=d;return f&&localStorage.setItem(tn,JSON.stringify(f)),c}}else localStorage.removeItem(tn);const a=yield fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:"POST"});if(!a.ok)return null;const s=yield a.json(),{access_token:i,refresh_token:o}=s;return!i||!o?null:(localStorage.setItem(tn,JSON.stringify(o)),i)}))}getAuthHeaders(){return M(this,null,function*(){return this.jwtStrategy.getAuthHeaders()})}readAuthHeaders(e){this.jwtStrategy.readAuthHeaders(e)}},Ph=class extends Error{constructor(e){super(e),this.name="APIError"}},Nh=class{constructor(e){T(this,"_auth");T(this,"_baseUrl");if("authToken"in e)this._baseUrl=e.baseUrl,this._auth=new Di(e.authToken);else if("apiKey"in e)this._baseUrl="https://backend.assistant-api.com",this._auth=new Ah(e.apiKey,e.userId,e.workspaceId);else if("anonymous"in e)this._baseUrl=e.baseUrl,this._auth=new Mh(e.baseUrl);else throw new Error("Invalid configuration: Must provide authToken, apiKey, or anonymous configuration")}initializeAuth(){return M(this,null,function*(){return!!this._auth.getAuthHeaders()})}makeRawRequest(r){return M(this,arguments,function*(e,t={}){var l;const n=yield this._auth.getAuthHeaders();if(!n)throw new Error("Authorization failed");const a=I(m(m({},n),t.headers),{"Content-Type":"application/json"}),s=new URLSearchParams;if(t.query)for(const[u,d]of Object.entries(t.query))d!==!1&&(d===!0?s.set(u,"true"):s.set(u,d.toString()));const i=new URL(`${this._baseUrl}/v1${e}`);i.search=s.toString();const o=yield fetch(i,{method:(l=t.method)!=null?l:"GET",headers:a,body:t.body?JSON.stringify(t.body):null});if(this._auth.readAuthHeaders(o.headers),!o.ok){const u=yield o.text();try{const d=JSON.parse(u);throw new Ph(d.message)}catch(d){throw new Error(`Request failed with status ${o.status}, ${u}`)}}return o})}makeRequest(r){return M(this,arguments,function*(e,t={}){return(yield this.makeRawRequest(e,t)).json()})}},Lh=class{constructor(e){this.cloud=e}create(){return M(this,null,function*(){return this.cloud.makeRequest("/auth/tokens",{method:"POST"})})}},Dh=class{constructor(e){this.cloud=e}__internal_getAssistantOptions(e){return{api:`${this.cloud._baseUrl}/v1/runs/stream`,headers:()=>M(this,null,function*(){const t=yield this.cloud._auth.getAuthHeaders();if(!t)throw new Error("Authorization failed");return I(m({},t),{Accept:"text/plain"})}),body:{assistant_id:e,response_format:"vercel-ai-data-stream/v1",thread_id:"unstable_todo"}}}stream(e){return M(this,null,function*(){const t=yield this.cloud.makeRawRequest("/runs/stream",{method:"POST",headers:{Accept:"text/plain"},body:e});return jn.fromResponse(t,new Vc)})}},Oh=class{constructor(e){this.cloud=e}list(e,t){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{query:t})})}create(e,t){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{method:"POST",body:t})})}},Fh=class{constructor(e){T(this,"messages");this.cloud=e,this.messages=new Oh(e)}list(e){return M(this,null,function*(){return this.cloud.makeRequest("/threads",{query:e})})}get(e){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`)})}create(e){return M(this,null,function*(){return this.cloud.makeRequest("/threads",{method:"POST",body:e})})}update(e,t){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"PUT",body:t})})}delete(e){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"DELETE"})})}},zh=class{constructor(e){this.cloud=e}pdfToImages(e){return M(this,null,function*(){return this.cloud.makeRequest("/files/pdf-to-images",{method:"POST",body:e})})}generatePresignedUploadUrl(e){return M(this,null,function*(){return this.cloud.makeRequest("/files/attachments/generate-presigned-upload-url",{method:"POST",body:e})})}},Bh=class{constructor(e){T(this,"threads");T(this,"auth");T(this,"runs");T(this,"files");const t=new Nh(e);this.threads=new Fh(t),this.auth={tokens:new Lh(t)},this.runs=new Dh(t),this.files=new zh(t)}};function na(e,t=0){return t>100?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?!Number.isNaN(e)&&Number.isFinite(e):Array.isArray(e)?e.every(r=>na(r,t+1)):typeof e=="object"?Object.entries(e).every(([r,n])=>typeof r=="string"&&na(n,t+1)):!1}var Rh=e=>{var t;return m({role:e.role,content:e.content.map(r=>{const n=r.type;switch(n){case"text":return{type:"text",text:r.text};case"reasoning":return{type:"reasoning",text:r.text};case"source":return m({type:"source",sourceType:r.sourceType,id:r.id,url:r.url},r.title?{title:r.title}:void 0);case"tool-call":return na(r.result)||console.warn(`tool-call result is not JSON! ${JSON.stringify(r)}`),m(m(m({type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName},JSON.stringify(r.args)===r.argsText?{args:r.args}:{argsText:r.argsText}),r.result?{result:r.result}:{}),r.isError?{isError:!0}:{});default:{const a=n;throw new Error(`Message part type not supported by aui/v0: ${a}`)}}}),metadata:e.metadata},e.status?{status:((t=e.status)==null?void 0:t.type)==="running"?{type:"incomplete",reason:"cancelled"}:e.status}:void 0)},jh=e=>{const t=e.content,r=lr(m({id:e.id,createdAt:e.created_at},t),e.id,{type:"complete",reason:"unknown"});return{parentId:e.parent_id,message:r}},aa=new WeakMap,$h=class{constructor(e,t){this.parent=e,this.formatAdapter=t}append(e){return M(this,null,function*(){const t=this.formatAdapter.encode(e),r=this.formatAdapter.getId(e.message);return this.parent._appendWithFormat(e.parentId,r,this.formatAdapter.format,t)})}load(){return M(this,null,function*(){return this.parent._loadWithFormat(this.formatAdapter.format,e=>this.formatAdapter.decode(e))})}},Uh=class{constructor(e,t){this.cloudRef=e,this.store=t}get _getIdForLocalId(){return aa.has(this.store.threadListItem())||aa.set(this.store.threadListItem(),{}),aa.get(this.store.threadListItem())}withFormat(e){return new $h(this,e)}append(r){return M(this,arguments,function*({parentId:e,message:t}){var s;const{remoteId:n}=yield this.store.threadListItem().initialize(),a=this.cloudRef.current.threads.messages.create(n,{parent_id:e?(s=yield this._getIdForLocalId[e])!=null?s:e:null,format:"aui/v0",content:Rh(t)}).then(({message_id:i})=>(this._getIdForLocalId[t.id]=i,i));return this._getIdForLocalId[t.id]=a,a.then(()=>{})})}load(){return M(this,null,function*(){const e=this.store.threadListItem().getState().remoteId;if(!e)return{messages:[]};const{messages:t}=yield this.cloudRef.current.threads.messages.list(e,{format:"aui/v0"});return{messages:t.filter(n=>n.format==="aui/v0").map(jh).reverse()}})}_appendWithFormat(e,t,r,n){return M(this,null,function*(){var i;const{remoteId:a}=yield this.store.threadListItem().initialize(),s=this.cloudRef.current.threads.messages.create(a,{parent_id:e?(i=yield this._getIdForLocalId[e])!=null?i:e:null,format:r,content:n}).then(({message_id:o})=>(this._getIdForLocalId[t]=o,o));return this._getIdForLocalId[t]=s,s.then(()=>{})})}_loadWithFormat(e,t){return M(this,null,function*(){const r=this.store.threadListItem().getState().remoteId;if(!r)return{messages:[]};const{messages:n}=yield this.cloudRef.current.threads.messages.list(r,{format:e});return{messages:n.filter(a=>a.format===e).map(a=>t({id:a.id,parent_id:a.parent_id,format:a.format,content:a.content})).reverse()}})}},Hh=e=>{const t=pe(),[r]=b.useState(()=>new Uh(e,t));return r},Oi=typeof process!="undefined"&&((Ru=process==null?void 0:process.env)==null?void 0:Ru.NEXT_PUBLIC_ASSISTANT_BASE_URL),sa=Oi?new Bh({baseUrl:Oi,anonymous:!0}):void 0,qh=e=>{var a;const t=b.useRef(e);b.useEffect(()=>{t.current=e},[e]);const r=b.useCallback(function({children:i}){var c;const o=Hh({get current(){var f;return(f=t.current.cloud)!=null?f:sa}}),l=(c=t.current.cloud)!=null?c:sa,u=b.useMemo(()=>new hd(l),[l]),d=b.useMemo(()=>({history:o,attachments:u}),[o,u]);return p.jsx(Vn,{adapters:d,children:i})},[]),n=(a=e.cloud)!=null?a:sa;return n?{list:()=>M(null,null,function*(){const{threads:s}=yield n.threads.list();return{threads:s.map(i=>{var o;return{status:i.is_archived?"archived":"regular",remoteId:i.id,title:i.title,externalId:(o=i.external_id)!=null?o:void 0}})}}),initialize:()=>M(null,null,function*(){var u,d;const i=yield(d=(u=e.create)==null?void 0:u.call(e))!=null?d:Promise.resolve(),o=i?i.externalId:void 0,{thread_id:l}=yield n.threads.create({last_message_at:new Date,external_id:o});return{externalId:o,remoteId:l}}),rename:(s,i)=>M(null,null,function*(){return n.threads.update(s,{title:i})}),archive:s=>M(null,null,function*(){return n.threads.update(s,{is_archived:!0})}),unarchive:s=>M(null,null,function*(){return n.threads.update(s,{is_archived:!1})}),delete:s=>M(null,null,function*(){var i;return yield(i=e.delete)==null?void 0:i.call(e,s),n.threads.delete(s)}),generateTitle:(s,i)=>M(null,null,function*(){return n.runs.stream({thread_id:s,assistant_id:"system/thread_title",messages:i})}),fetch:s=>M(null,null,function*(){var o;const i=yield n.threads.get(s);return{status:i.is_archived?"archived":"regular",remoteId:i.id,title:i.title,externalId:(o=i.external_id)!=null?o:void 0}}),unstable_Provider:r}:new bd},Vh=(e,n)=>{var a=n,{initialMessages:t}=a,r=H(a,["initialMessages"]);var u;const d=(u=fd())!=null?u:{},{modelContext:s}=d,i=H(d,["modelContext"]),o=b.useMemo(()=>I(m({},r),{adapters:I(m(m({},i),r.adapters),{chatModel:e})}),[e,r,i]),[l]=b.useState(()=>new Eh(o,t));return b.useEffect(()=>()=>{l.threads.getMainThreadRuntimeCore().detach()},[l]),b.useEffect(()=>{l.threads.getMainThreadRuntimeCore().__internal_setOptions(o),l.threads.getMainThreadRuntimeCore().__internal_load()},[l,o]),b.useEffect(()=>{if(s)return l.registerModelContextProvider(s)},[s,l]),b.useMemo(()=>new ia(l),[l])},Fi=(e,n={})=>{var a=n,{cloud:t}=a,r=H(a,["cloud"]);const s=qh({cloud:t});return $i({runtimeHook:function(){return Vh(e,r)},adapter:s,allowNesting:!0})},ia=class{constructor(e){T(this,"threads");T(this,"_thread");this._core=e,this.threads=new cd(e.threads),this._thread=this.threads.main,this.__internal_bindMethods()}get threadList(){return this.threads}__internal_bindMethods(){this.switchToNewThread=this.switchToNewThread.bind(this),this.switchToThread=this.switchToThread.bind(this),this.registerModelContextProvider=this.registerModelContextProvider.bind(this),this.registerModelConfigProvider=this.registerModelConfigProvider.bind(this),this.reset=this.reset.bind(this)}get thread(){return this._thread}switchToNewThread(){return this._core.threads.switchToNewThread()}switchToThread(e){return this._core.threads.switchToThread(e)}registerModelContextProvider(e){return this._core.registerModelContextProvider(e)}registerModelConfigProvider(e){return this.registerModelContextProvider(e)}reset({initialMessages:e}={}){return this._core.threads.getMainThreadRuntimeCore().import(Un.fromArray(e!=null?e:[]))}},Wh=e=>{const o=e,{cloud:t,initialMessages:r,maxSteps:n,adapters:a,unstable_humanToolNames:s}=o,i=H(o,["cloud","initialMessages","maxSteps","adapters","unstable_humanToolNames"]);return{localRuntimeOptions:{cloud:t,initialMessages:r,maxSteps:n,adapters:a,unstable_humanToolNames:s},otherOptions:i}};function At(e){const t=Z.useRef(e);return Z.useEffect(()=>{t.current=e}),Z.useMemo(()=>(...r)=>{var n;return(n=t.current)==null?void 0:n.call(t,...r)},[])}var zi=b.createContext(null),Jh=e=>({useSmoothStatus:Ht(()=>e)}),Kh=({children:e})=>{const t=Bi({optional:!0}),r=pe(),[n]=b.useState(()=>Jh(r.part().getState().status));return t?e:p.jsx(zi.Provider,{value:n,children:e})},Yh=e=>{const t=b.forwardRef((r,n)=>p.jsx(Kh,{children:p.jsx(e,I(m({},r),{ref:n}))}));return t.displayName=e.displayName,t};function Bi(e){const t=b.useContext(zi);if(!(e!=null&&e.optional)&&!t)throw new Error("This component must be used within a SmoothContextProvider.");return t}var{useSmoothStatus:Gh,useSmoothStatusStore:Xh}=wi(Bi,"useSmoothStatus"),Qh=class{constructor(e,t){T(this,"animationFrameId",null);T(this,"lastUpdateTime",Date.now());T(this,"targetText","");T(this,"animate",()=>{const e=Date.now();let r=e-this.lastUpdateTime;const n=this.targetText.length-this.currentText.length,a=Math.min(5,250/n);let s=0;for(;r>=a&&s<n;)s++,r-=a;s!==n?this.animationFrameId=requestAnimationFrame(this.animate):this.animationFrameId=null,s!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+s),this.lastUpdateTime=e-r,this.setText(this.currentText))});this.currentText=e,this.setText=t}start(){this.animationFrameId===null&&(this.lastUpdateTime=Date.now(),this.animate())}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}},oa=Object.freeze({type:"running"}),Ri=(e,t=!1)=>{const{text:r}=e,n=ee(({message:d})=>d.id),a=b.useRef(n),[s,i]=b.useState(r),o=Xh({optional:!0}),l=At(d=>{if(i(d),o){const c=s!==d||e.status.type==="running"?oa:e.status;pr(o).setState(c,!0)}});b.useEffect(()=>{if(o){const d=t&&(s!==r||e.status.type==="running")?oa:e.status;pr(o).setState(d,!0)}},[o,t,r,s,e.status]);const[u]=b.useState(new Qh(r,l));return b.useEffect(()=>{if(!t){u.stop();return}if(a.current!==n||!r.startsWith(u.targetText)){a.current=n,l(r),u.currentText=r,u.targetText=r,u.stop();return}u.targetText=r,u.start()},[l,u,n,t,r]),b.useEffect(()=>()=>{u.stop()},[u]),b.useMemo(()=>t?{type:"text",text:s,status:r===s?e.status:oa}:e,[t,s,e,r])};const Zh=Object.freeze(Object.defineProperty({__proto__:null,AssistantRuntimeImpl:ia,BaseAssistantRuntimeCore:zn,CompositeContextProvider:Fn,DefaultThreadComposerRuntimeCore:Cs,MessageRepository:$s,ThreadRuntimeImpl:ti,fromThreadMessageLike:lr,generateId:_t,getAutoStatus:Es,splitLocalRuntimeOptions:Wh,useSmooth:Ri,useSmoothStatus:Gh,useToolInvocations:yd,withSmoothContextProvider:Yh},Symbol.toStringTag,{value:"Module"}));var ef=class extends ir{constructor(t){super();T(this,"useRuntimeHook");T(this,"instances",new Map);T(this,"useAliveThreadsKeysChanged",Ht(()=>({})));T(this,"_InnerActiveThreadProvider",({threadId:t})=>{const{useRuntime:r}=this.useRuntimeHook(),n=r(),a=n.thread.__internal_threadBinding,s=b.useCallback(()=>{const l=this.instances.get(t);if(!l)throw new Error("Thread not found. This is a bug in assistant-ui.");l.runtime=a.getState(),this._notifySubscribers()},[t,a]),i=b.useRef(!1);i.current||s(),b.useEffect(()=>(i.current=!0,s(),a.outerSubscribe(s)),[a,s]);const o=pe();return b.useEffect(()=>n.threads.main.unstable_on("initialize",()=>{if(o.threadListItem().getState().status==="new"){o.threadListItem().initialize();const u=n.thread.unstable_on("run-end",()=>{u(),o.threadListItem().generateTitle()})}}),[n,o]),null});T(this,"_OuterActiveThreadProvider",b.memo(({threadId:t,provider:r})=>p.jsx(bh,{id:t,children:p.jsx(r,{children:p.jsx(this._InnerActiveThreadProvider,{threadId:t})})})));T(this,"__internal_RenderThreadRuntimes",({provider:t})=>(this.useAliveThreadsKeysChanged(),Array.from(this.instances.keys()).map(r=>p.jsx(this._OuterActiveThreadProvider,{threadId:r,provider:t},r))));this.useRuntimeHook=Ht(()=>({useRuntime:t}))}startThreadRuntime(t){return this.instances.has(t)||(this.instances.set(t,{}),this.useAliveThreadsKeysChanged.setState({},!0)),new Promise((r,n)=>{const a=()=>{const i=this.instances.get(t);if(!i)s(),n(new Error("Thread was deleted before runtime was started"));else if(i.runtime)s(),r(i.runtime);else return},s=this.subscribe(a);a()})}getThreadRuntimeCore(t){const r=this.instances.get(t);if(r)return r.runtime}stopThreadRuntime(t){this.instances.delete(t),this.useAliveThreadsKeysChanged.setState({},!0)}setRuntimeHook(t){this.useRuntimeHook.getState().useRuntime!==t&&this.useRuntimeHook.setState({useRuntime:t},!0)}},ve=new Error("This is the empty thread, a placeholder for the main thread. You cannot perform any actions on this thread instance. This error is probably because you tried to call a thread method in your render function. Call the method inside a `useEffect` hook instead."),tf={getMessageById(){},getBranches(){return[]},switchToBranch(){throw ve},append(){throw ve},startRun(){throw ve},resumeRun(){throw ve},cancelRun(){throw ve},addToolResult(){throw ve},resumeToolCall(){throw ve},speak(){throw ve},stopSpeaking(){throw ve},submitFeedback(){throw ve},getModelContext(){return{}},unstable_loadExternalState(){throw ve},composer:{attachments:[],attachmentAccept:"*",addAttachment(){return M(this,null,function*(){throw ve})},removeAttachment(){return M(this,null,function*(){throw ve})},isEditing:!0,canCancel:!1,isEmpty:!0,text:"",setText(){throw ve},role:"user",setRole(){throw ve},runConfig:{},setRunConfig(){throw ve},reset(){return M(this,null,function*(){})},clearAttachments(){return M(this,null,function*(){})},send(){throw ve},cancel(){},subscribe(){return()=>{}},unstable_on(){return()=>{}}},getEditComposer(){},beginEdit(){throw ve},speech:void 0,capabilities:{switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,attachments:!1,feedback:!1},isDisabled:!1,isLoading:!1,messages:[],state:null,suggestions:[],extras:void 0,subscribe(){return()=>{}},import(){throw ve},export(){return{messages:[]}},reset(){throw ve},unstable_on(){return()=>{}}},ji=(e,t,r)=>r.reduce((n,a)=>{var s;return(s=a==null?void 0:a(n,t))!=null?s:n},e),rf=class extends ir{constructor(t){super();T(this,"_pendingTransforms",[]);T(this,"_baseValue");T(this,"_cachedValue");this._baseValue=t,this._cachedValue=t}_updateState(){this._cachedValue=this._pendingTransforms.reduce((t,r)=>ji(t,r.task,[r.loading,r.optimistic]),this._baseValue),this._notifySubscribers()}get baseValue(){return this._baseValue}get value(){return this._cachedValue}update(t){this._baseValue=t,this._updateState()}optimisticUpdate(t){return M(this,null,function*(){const r=t.execute(),n=I(m({},t),{task:r});try{this._pendingTransforms.push(n),this._updateState();const a=yield r;return this._baseValue=ji(this._baseValue,a,[t.optimistic,t.then]),a}finally{const a=this._pendingTransforms.indexOf(n);a>-1&&this._pendingTransforms.splice(a,1),this._updateState()}})}};function Xv(e){return e}var rn=(e,t)=>{const r=e.threadIdMap[t];if(r!==void 0)return e.threadData[r]},nn=(e,t,r)=>{const n=rn(e,t);if(!n)return e;const{id:a,remoteId:s,status:i}=n;if(i===r)return e;const o=m({},e);switch(i){case"new":o.newThreadId=void 0;break;case"regular":o.threadIds=o.threadIds.filter(l=>l!==a);break;case"archived":o.archivedThreadIds=o.archivedThreadIds.filter(l=>l!==a);break;default:{const l=i;throw new Error(`Unsupported state: ${l}`)}}switch(r){case"regular":o.threadIds=[a,...o.threadIds];break;case"archived":o.archivedThreadIds=[a,...o.archivedThreadIds];break;case"deleted":o.threadData=Object.fromEntries(Object.entries(o.threadData).filter(([l])=>l!==a)),o.threadIdMap=Object.fromEntries(Object.entries(o.threadIdMap).filter(([l])=>l!==a&&l!==s));break;default:{const l=r;throw new Error(`Unsupported state: ${l}`)}}return r!=="deleted"&&(o.threadData=I(m({},o.threadData),{[a]:I(m({},n),{status:r})})),o},nf=class extends ir{constructor(t,r){super();T(this,"_options");T(this,"_hookManager");T(this,"_loadThreadsPromise");T(this,"_mainThreadId");T(this,"_state",new rf({isLoading:!1,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}}));T(this,"useProvider");T(this,"initialize",t=>M(this,null,function*(){if(this._state.value.newThreadId!==t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status==="new")throw new Error("Unexpected new state");return r.initializeTask}return this._state.optimisticUpdate({execute:()=>this._options.adapter.initialize(t),optimistic:r=>nn(r,t,"regular"),loading:(r,n)=>{const a=t;return I(m({},r),{threadData:I(m({},r.threadData),{[a]:I(m({},r.threadData[a]),{initializeTask:n})})})},then:(r,{remoteId:n,externalId:a})=>{const s=rn(r,t);if(!s)return r;const i=t;return I(m({},r),{threadIdMap:I(m({},r.threadIdMap),{[n]:i}),threadData:I(m({},r.threadData),{[i]:I(m({},s),{initializeTask:Promise.resolve({remoteId:n,externalId:a}),remoteId:n,externalId:a})})})}})}));T(this,"generateTitle",t=>M(this,null,function*(){var l;const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status==="new")throw new Error("Thread is not yet initialized");const{remoteId:n}=yield r.initializeTask,a=this._hookManager.getThreadRuntimeCore(r.id);if(!a)return;const s=a.messages,i=yield this._options.adapter.generateTitle(n,s),o=Wc.fromAssistantStream(i);try{for(var u=Ft(o),d,c,f;d=!(c=yield u.next()).done;d=!1){const h=c.value;const g=(l=h.parts.filter(x=>x.type==="text")[0])==null?void 0:l.text,w=this._state.baseValue;this._state.update(I(m({},w),{threadData:I(m({},w.threadData),{[r.id]:I(m({},r),{title:g})})}))}}catch(c){f=[c]}finally{try{d&&(c=u.return)&&(yield c.call(u))}finally{if(f)throw f[0]}}}));T(this,"useBoundIds",Ht(()=>[]));T(this,"__internal_RenderComponent",()=>{const t=b.useId();b.useEffect(()=>(this.useBoundIds.setState(s=>[...s,t],!0),()=>{this.useBoundIds.setState(s=>s.filter(i=>i!==t),!0)}),[t]);const r=this.useBoundIds(),{Provider:n}=this.useProvider(),a={modelContext:this.contextProvider};return(r.length===0||r[0]===t)&&p.jsx(Vn,{adapters:a,children:p.jsx(this._hookManager.__internal_RenderThreadRuntimes,{provider:n})})});this.contextProvider=r,this._state.subscribe(()=>this._notifySubscribers()),this._hookManager=new ef(t.runtimeHook),this.useProvider=Ht(()=>{var n;return{Provider:(n=t.adapter.unstable_Provider)!=null?n:b.Fragment}}),this.__internal_setOptions(t),this.switchToNewThread()}get threadData(){return this._state.value.threadData}getLoadThreadsPromise(){return this._loadThreadsPromise||(this._loadThreadsPromise=this._state.optimisticUpdate({execute:()=>this._options.adapter.list(),loading:t=>I(m({},t),{isLoading:!0}),then:(t,r)=>{const n=[],a=[],s={},i={};for(const o of r.threads){switch(o.status){case"regular":n.push(o.remoteId);break;case"archived":a.push(o.remoteId);break;default:{const u=o.status;throw new Error(`Unsupported state: ${u}`)}}const l=o.remoteId;s[o.remoteId]=l,i[l]={id:o.remoteId,remoteId:o.remoteId,externalId:o.externalId,status:o.status,title:o.title,initializeTask:Promise.resolve({remoteId:o.remoteId,externalId:o.externalId})}}return I(m({},t),{threadIds:n,archivedThreadIds:a,threadIdMap:m(m({},t.threadIdMap),s),threadData:m(m({},t.threadData),i)})}}).then(()=>{})),this._loadThreadsPromise}__internal_setOptions(t){var n;if(this._options===t)return;this._options=t;const r=(n=t.adapter.unstable_Provider)!=null?n:b.Fragment;r!==this.useProvider.getState().Provider&&this.useProvider.setState({Provider:r},!0),this._hookManager.setRuntimeHook(t.runtimeHook)}__internal_load(){this.getLoadThreadsPromise()}get isLoading(){return this._state.value.isLoading}get threadIds(){return this._state.value.threadIds}get archivedThreadIds(){return this._state.value.archivedThreadIds}get newThreadId(){return this._state.value.newThreadId}get mainThreadId(){return this._mainThreadId}getMainThreadRuntimeCore(){const t=this._hookManager.getThreadRuntimeCore(this._mainThreadId);return t||tf}getThreadRuntimeCore(t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");const n=this._hookManager.getThreadRuntimeCore(r.id);if(!n)throw new Error("Thread not found");return n}getItemById(t){return rn(this._state.value,t)}switchToThread(t){return M(this,null,function*(){let r=this.getItemById(t);if(!r){const a=yield this._options.adapter.fetch(t),s=this._state.value,i=a.remoteId,o=I(m({},s.threadData),{[i]:{id:i,initializeTask:Promise.resolve({remoteId:a.remoteId,externalId:a.externalId}),remoteId:a.remoteId,externalId:a.externalId,status:a.status,title:a.title}}),l=I(m({},s.threadIdMap),{[a.remoteId]:i}),u=a.status==="regular"?[...s.threadIds,a.remoteId]:s.threadIds,d=a.status==="archived"?[...s.archivedThreadIds,a.remoteId]:s.archivedThreadIds;this._state.update(I(m({},s),{threadIds:u,archivedThreadIds:d,threadIdMap:l,threadData:o})),r=this.getItemById(t)}if(!r)throw new Error("Thread not found");if(this._mainThreadId===r.id)return;const n=this._hookManager.startThreadRuntime(r.id);this.mainThreadId!==void 0?yield n:n.then(()=>this._notifySubscribers()),r.status==="archived"&&(yield this.unarchive(r.id)),this._mainThreadId=r.id,this._notifySubscribers()})}switchToNewThread(){return M(this,null,function*(){for(;this._state.baseValue.newThreadId!==void 0&&this._state.value.newThreadId===void 0;)yield this._state.waitForUpdate();const t=this._state.value;let r=this._state.value.newThreadId;if(r===void 0){do r=`__LOCALID_${_t()}`;while(t.threadIdMap[r]);const n=r;this._state.update(I(m({},t),{newThreadId:r,threadIdMap:I(m({},t.threadIdMap),{[r]:n}),threadData:I(m({},t.threadData),{[n]:{status:"new",id:r,remoteId:void 0,externalId:void 0,title:void 0}})}))}return this.switchToThread(r)})}rename(t,r){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status==="new")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:()=>M(this,null,function*(){const{remoteId:a}=yield n.initializeTask;return this._options.adapter.rename(a,r)}),optimistic:a=>{const s=rn(a,t);return s?I(m({},a),{threadData:I(m({},a.threadData),{[s.id]:I(m({},s),{title:r})})}):a}})}_ensureThreadIsNotMain(t){return M(this,null,function*(){if(t===this.newThreadId)throw new Error("Cannot ensure new thread is not main");t===this._mainThreadId&&(yield this.switchToNewThread())})}archive(t){return M(this,null,function*(){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular")throw new Error("Thread is not yet initialized or already archived");return this._state.optimisticUpdate({execute:()=>M(this,null,function*(){yield this._ensureThreadIsNotMain(r.id);const{remoteId:n}=yield r.initializeTask;return this._options.adapter.archive(n)}),optimistic:n=>nn(n,r.id,"archived")})})}unarchive(t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="archived")throw new Error("Thread is not archived");return this._state.optimisticUpdate({execute:()=>M(this,null,function*(){try{const{remoteId:n}=yield r.initializeTask;return yield this._options.adapter.unarchive(n)}catch(n){throw yield this._ensureThreadIsNotMain(r.id),n}}),optimistic:n=>nn(n,r.id,"regular")})}delete(t){return M(this,null,function*(){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular"&&r.status!=="archived")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:()=>M(this,null,function*(){yield this._ensureThreadIsNotMain(r.id);const{remoteId:n}=yield r.initializeTask;return yield this._options.adapter.delete(n)}),optimistic:n=>nn(n,r.id,"deleted")})})}detach(t){return M(this,null,function*(){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular"&&r.status!=="archived")throw new Error("Thread is not yet initialized");yield this._ensureThreadIsNotMain(r.id),this._hookManager.stopThreadRuntime(r.id)})}},af=class extends zn{constructor(t){super();T(this,"threads");this.threads=new nf(t,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}},sf=e=>{const[t]=b.useState(()=>new af(e));return b.useEffect(()=>{t.threads.__internal_setOptions(e),t.threads.__internal_load()},[t,e]),b.useMemo(()=>new ia(t),[t])},$i=e=>{if(Zr().threadListItem.source!==null){if(!e.allowNesting)throw new Error("useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. Set allowNesting: true to allow nesting (the inner runtime will become a no-op).");return e.runtimeHook()}return sf(e)},of=Symbol.for("react.lazy"),an=Z[" use ".trim().toString()];function lf(e){return typeof e=="object"&&e!==null&&"then"in e}function Ui(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===of&&"_payload"in e&&lf(e._payload)}function Hi(e){const t=uf(e),r=Z.forwardRef((n,a)=>{let u=n,{children:s}=u,i=H(u,["children"]);Ui(s)&&typeof an=="function"&&(s=an(s._payload));const o=Z.Children.toArray(s),l=o.find(df);if(l){const d=l.props.children,c=o.map(f=>f===l?Z.Children.count(d)>1?Z.Children.only(null):Z.isValidElement(d)?d.props.children:null:f);return p.jsx(t,I(m({},i),{ref:a,children:Z.isValidElement(d)?Z.cloneElement(d,void 0,c):null}))}return p.jsx(t,I(m({},i),{ref:a,children:s}))});return r.displayName=`${e}.Slot`,r}var la=Hi("Slot");function uf(e){const t=Z.forwardRef((r,n)=>{let i=r,{children:a}=i,s=H(i,["children"]);if(Ui(a)&&typeof an=="function"&&(a=an(a._payload)),Z.isValidElement(a)){const o=ff(a),l=hf(s,a.props);return a.type!==Z.Fragment&&(l.ref=n?hi(n,o):o),Z.cloneElement(a,l)}return Z.Children.count(a)>1?Z.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var cf=Symbol("radix.slottable");function df(e){return Z.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===cf}function hf(e,t){const r=m({},t);for(const n in t){const a=e[n],s=t[n];/^on[A-Z]/.test(n)?a&&s?r[n]=(...o)=>{const l=s(...o);return a(...o),l}:a&&(r[n]=a):n==="style"?r[n]=m(m({},a),s):n==="className"&&(r[n]=[a,s].filter(Boolean).join(" "))}return m(m({},e),r)}function ff(e){var n,a;let t=(n=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:n.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=(a=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:a.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var pf=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ut=pf.reduce((e,t)=>{const r=Hi(`Primitive.${t}`),n=Z.forwardRef((a,s)=>{const u=a,{asChild:i}=u,o=H(u,["asChild"]),l=i?r:t;return typeof window!="undefined"&&(window[Symbol.for("radix-ui")]=!0),p.jsx(l,I(m({},o),{ref:s}))});return n.displayName=`Primitive.${t}`,I(m({},e),{[t]:n})},{});function qt(e,t,{checkForDefaultPrevented:r=!0}={}){return function(a){if(e==null||e(a),r===!1||!a.defaultPrevented)return t==null?void 0:t(a)}}var sn=(e,t,r=[])=>{const n=b.forwardRef((a,s)=>{var u;const i={},o={};Object.keys(a).forEach(d=>{r.includes(d)?i[d]=a[d]:o[d]=a[d]});const l=(u=t(i))!=null?u:void 0;return p.jsx(ut.button,I(m({type:"button"},o),{ref:s,disabled:o.disabled||!l,onClick:qt(o.onClick,l)}))});return n.displayName=e,n};function mf(e,t=globalThis==null?void 0:globalThis.document){const r=At(e);Z.useEffect(()=>{const n=a=>{a.key==="Escape"&&r(a)};return t.addEventListener("keydown",n,{capture:!0}),()=>t.removeEventListener("keydown",n,{capture:!0})},[r,t])}var gf=()=>{const e=pe();return b.useCallback(()=>{e.attachment().remove()},[e])},yf=sn("AttachmentPrimitive.Remove",gf),mr=e=>{const t=b.useRef(void 0);return b.useCallback(n=>{t.current&&t.current(),n&&(t.current=e(n))},[e])},qi=(e,t)=>{const r=b.useCallback(n=>{if(!e)return;const a=e(),s=()=>{const o=t?t(n):n.offsetHeight;a.setHeight(o)},i=new ResizeObserver(s);return i.observe(n),s(),()=>{i.disconnect(),a.unregister()}},[e,t]);return mr(r)},Vi=b.createContext(!1),Wi=(e,t)=>{const r=e.match(/^([\d.]+)(em|px|rem)$/);if(!r)return 0;const n=parseFloat(r[1]),a=r[2];if(a==="px")return n;if(a==="em"){const s=parseFloat(getComputedStyle(t).fontSize)||16;return n*s}if(a==="rem"){const s=parseFloat(getComputedStyle(document.documentElement).fontSize)||16;return n*s}return 0},Ji=({children:e,fillClampThreshold:t="10em",fillClampOffset:r="6em"})=>{const n=ee(({message:l})=>l.isLast&&l.index>=2),a=Zn({optional:!0}),s=b.useContext(Vi),i=b.useCallback(l=>{if(!a||s)return;const u=()=>{const d=a.getState();if(d.turnAnchor==="top"&&n){const{viewport:c,inset:f,userMessage:h}=d.height,g=Wi(t,l),w=Wi(r,l),x=h<=g?h:w,y=Math.max(0,c-f-x);l.style.minHeight=`${y}px`,l.style.flexShrink="0",l.style.transition="min-height 0s"}else l.style.minHeight="",l.style.flexShrink="",l.style.transition=""};return u(),a.subscribe(u)},[a,n,s,t,r]),o=mr(i);return p.jsx(Vi.Provider,{value:!0,children:p.jsx(la,{ref:o,children:e})})};Ji.displayName="ThreadPrimitive.ViewportSlack";var bf=()=>{const e=pe(),t=ee(()=>e.message()),r=b.useCallback(n=>{const a=()=>{t.setIsHovering(!0)},s=()=>{t.setIsHovering(!1)};return n.addEventListener("mouseenter",a),n.addEventListener("mouseleave",s),n.matches(":hover")&&t.setIsHovering(!0),()=>{n.removeEventListener("mouseenter",a),n.removeEventListener("mouseleave",s),t.setIsHovering(!1)}},[t]);return mr(r)},xf=()=>{const e=en(a=>a.turnAnchor),t=en(a=>a.registerUserMessageHeight),r=ee(({thread:a,message:s})=>{var i;return e==="top"&&s.role==="user"&&s.index===a.messages.length-2&&((i=a.messages.at(-1))==null?void 0:i.role)==="assistant"}),n=b.useCallback(a=>a.offsetHeight,[]);return qi(r?t:null,n)},ua=b.forwardRef((e,t)=>{const r=bf(),n=xf(),a=Qr(t,r,n);return p.jsx(Ji,{children:p.jsx(ut.div,I(m({},e),{ref:a}))})});ua.displayName="MessagePrimitive.Root";var Ki=()=>ee(({part:t})=>{if(t.type!=="text"&&t.type!=="reasoning")throw new Error("MessagePartText can only be used inside text or reasoning message parts.");return t}),Yi=b.forwardRef((a,n)=>{var s=a,{smooth:e=!0,component:t="span"}=s,r=H(s,["smooth","component"]);const{text:i,status:o}=Ri(Ki(),e);return p.jsx(t,I(m({"data-status":o.type},r),{ref:n,children:i}))});Yi.displayName="MessagePartPrimitive.Text";var wf=()=>ee(({part:t})=>{if(t.type!=="image")throw new Error("MessagePartImage can only be used inside image message parts.");return t}),Gi=b.forwardRef((e,t)=>{const{image:r}=wf();return p.jsx(ut.img,I(m({src:r},e),{ref:t}))});Gi.displayName="MessagePartPrimitive.Image";var Xi=({children:e})=>ee(({part:r})=>r.status.type==="running")?e:null;Xi.displayName="MessagePartPrimitive.InProgress";const Qi=e=>Symbol.iterator in e,Zi=e=>"entries"in e,eo=(e,t)=>{const r=e instanceof Map?e:new Map(e.entries()),n=t instanceof Map?t:new Map(t.entries());if(r.size!==n.size)return!1;for(const[a,s]of r)if(!n.has(a)||!Object.is(s,n.get(a)))return!1;return!0},vf=(e,t)=>{const r=e[Symbol.iterator](),n=t[Symbol.iterator]();let a=r.next(),s=n.next();for(;!a.done&&!s.done;){if(!Object.is(a.value,s.value))return!1;a=r.next(),s=n.next()}return!!a.done&&!!s.done};function kf(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:Qi(e)&&Qi(t)?Zi(e)&&Zi(t)?eo(e,t):vf(e,t):eo({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Sf(e){const t=b.useRef(void 0);return r=>{const n=e(r);return kf(t.current,n)?t.current:t.current=n}}var to=e=>{let t=-1;return{startGroup:r=>{t===-1&&(t=r)},endGroup:(r,n)=>{t!==-1&&(n.push({type:e,startIndex:t,endIndex:r}),t=-1)},finalize:(r,n)=>{t!==-1&&n.push({type:e,startIndex:t,endIndex:r})}}},_f=e=>{const t=[],r=to("toolGroup"),n=to("reasoningGroup");for(let a=0;a<e.length;a++){const s=e[a];s==="tool-call"?(n.endGroup(a-1,t),r.startGroup(a)):s==="reasoning"?(r.endGroup(a-1,t),n.startGroup(a)):(r.endGroup(a-1,t),n.endGroup(a-1,t),t.push({type:"single",index:a}))}return r.finalize(e.length-1,t),n.finalize(e.length-1,t),t},Tf=()=>{const e=ee(Sf(t=>t.message.parts.map(r=>r.type)));return b.useMemo(()=>e.length===0?[]:_f(e),[e])},Cf=r=>{var n=r,{Fallback:e}=n,t=H(n,["Fallback"]);const a=ee(({tools:s})=>{var o,l;const i=(o=s.tools[t.toolName])!=null?o:e;return Array.isArray(i)?(l=i[0])!=null?l:e:i});return a?p.jsx(a,m({},t)):null},ct={Text:()=>p.jsxs("p",{style:{whiteSpace:"pre-line"},children:[p.jsx(Yi,{}),p.jsx(Xi,{children:p.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>p.jsx(Gi,{}),File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},If=({components:{Text:e=ct.Text,Reasoning:t=ct.Reasoning,Image:r=ct.Image,Source:n=ct.Source,File:a=ct.File,Unstable_Audio:s=ct.Unstable_Audio,tools:i={}}={}})=>{var d,c,f;const o=pe(),l=ee(({part:h})=>h),u=l.type;if(u==="tool-call"){const h=o.part().addToolResult,g=o.part().resumeToolCall;if("Override"in i)return p.jsx(i.Override,I(m({},l),{addResult:h,resume:g}));const w=(c=(d=i.by_name)==null?void 0:d[l.toolName])!=null?c:i.Fallback;return p.jsx(Cf,I(m({},l),{Fallback:w,addResult:h,resume:g}))}if(((f=l.status)==null?void 0:f.type)==="requires-action")throw new Error("Encountered unexpected requires-action status");switch(u){case"text":return p.jsx(e,m({},l));case"reasoning":return p.jsx(t,m({},l));case"source":return p.jsx(n,m({},l));case"image":return p.jsx(r,m({},l));case"file":return p.jsx(a,m({},l));case"audio":return p.jsx(s,m({},l));case"data":return null;default:const h=u;throw new Error(`Unknown message part type: ${h}`)}},on=b.memo(({index:e,components:t})=>p.jsx(wh,{index:e,children:p.jsx(If,{components:t})}),(e,t)=>{var r,n,a,s,i,o,l,u,d,c,f,h,g,w,x,y,E,_;return e.index===t.index&&((r=e.components)==null?void 0:r.Text)===((n=t.components)==null?void 0:n.Text)&&((a=e.components)==null?void 0:a.Reasoning)===((s=t.components)==null?void 0:s.Reasoning)&&((i=e.components)==null?void 0:i.Source)===((o=t.components)==null?void 0:o.Source)&&((l=e.components)==null?void 0:l.Image)===((u=t.components)==null?void 0:u.Image)&&((d=e.components)==null?void 0:d.File)===((c=t.components)==null?void 0:c.File)&&((f=e.components)==null?void 0:f.Unstable_Audio)===((h=t.components)==null?void 0:h.Unstable_Audio)&&((g=e.components)==null?void 0:g.tools)===((w=t.components)==null?void 0:w.tools)&&((x=e.components)==null?void 0:x.ToolGroup)===((y=t.components)==null?void 0:y.ToolGroup)&&((E=e.components)==null?void 0:E.ReasoningGroup)===((_=t.components)==null?void 0:_.ReasoningGroup)});on.displayName="MessagePrimitive.PartByIndex";var Ef=({status:e,component:t})=>p.jsx(_h,{text:"",isRunning:e.type==="running",children:p.jsx(t,{type:"text",text:"",status:e})}),Af=Object.freeze({type:"complete"}),Mf=({components:e})=>{var r;const t=ee(n=>{var a;return(a=n.message.status)!=null?a:Af});return e!=null&&e.Empty?p.jsx(e.Empty,{status:t}):p.jsx(Ef,{status:t,component:(r=e==null?void 0:e.Text)!=null?r:ct.Text})},Pf=b.memo(Mf,(e,t)=>{var r,n,a,s;return((r=e.components)==null?void 0:r.Empty)===((n=t.components)==null?void 0:n.Empty)&&((a=e.components)==null?void 0:a.Text)===((s=t.components)==null?void 0:s.Text)}),ca=({components:e})=>{const t=ee(({message:a})=>a.parts.length),r=Tf(),n=b.useMemo(()=>t===0?p.jsx(Pf,{components:e}):r.map(a=>{var s,i;if(a.type==="single")return p.jsx(on,{index:a.index,components:e},a.index);if(a.type==="toolGroup"){const o=(s=e==null?void 0:e.ToolGroup)!=null?s:ct.ToolGroup;return p.jsx(o,{startIndex:a.startIndex,endIndex:a.endIndex,children:Array.from({length:a.endIndex-a.startIndex+1},(l,u)=>p.jsx(on,{index:a.startIndex+u,components:e},u))},`tool-${a.startIndex}`)}else{const o=(i=e==null?void 0:e.ReasoningGroup)!=null?i:ct.ReasoningGroup;return p.jsx(o,{startIndex:a.startIndex,endIndex:a.endIndex,children:Array.from({length:a.endIndex-a.startIndex+1},(l,u)=>p.jsx(on,{index:a.startIndex+u,components:e},u))},`reasoning-${a.startIndex}`)}}),[r,e,t]);return p.jsx(p.Fragment,{children:n})};ca.displayName="MessagePrimitive.Parts";var Nf=(e,t)=>{var n,a,s;const r=t.type;switch(r){case"image":return(n=e==null?void 0:e.Image)!=null?n:e==null?void 0:e.Attachment;case"document":return(a=e==null?void 0:e.Document)!=null?a:e==null?void 0:e.Attachment;case"file":return(s=e==null?void 0:e.File)!=null?s:e==null?void 0:e.Attachment;default:const i=r;throw new Error(`Unknown attachment type: ${i}`)}},Lf=({components:e})=>{const t=ee(({attachment:n})=>n);if(!t)return null;const r=Nf(e,t);return r?p.jsx(r,{}):null},ro=b.memo(({index:e,components:t})=>p.jsx(vh,{index:e,children:p.jsx(Lf,{components:t})}),(e,t)=>{var r,n,a,s,i,o,l,u;return e.index===t.index&&((r=e.components)==null?void 0:r.Image)===((n=t.components)==null?void 0:n.Image)&&((a=e.components)==null?void 0:a.Document)===((s=t.components)==null?void 0:s.Document)&&((i=e.components)==null?void 0:i.File)===((o=t.components)==null?void 0:o.File)&&((l=e.components)==null?void 0:l.Attachment)===((u=t.components)==null?void 0:u.Attachment)});ro.displayName="MessagePrimitive.AttachmentByIndex";var no=({components:e})=>{const t=ee(({message:n})=>n.role!=="user"?0:n.attachments.length);return b.useMemo(()=>Array.from({length:t},(n,a)=>p.jsx(ro,{index:a,components:e},a)),[t,e])};no.displayName="MessagePrimitive.Attachments";var ao=()=>{const e=pe(),t=ee(n=>n.thread.isRunning||!n.composer.isEditing||n.composer.isEmpty),r=b.useCallback(()=>{e.composer().send()},[e]);return t?null:r},Df=sn("ComposerPrimitive.Send",ao),so=b.forwardRef((n,r)=>{var a=n,{onSubmit:e}=a,t=H(a,["onSubmit"]);const s=ao(),i=o=>{o.preventDefault(),s&&s()};return p.jsx(ut.form,I(m({},t),{ref:r,onSubmit:qt(e,i)}))});so.displayName="ComposerPrimitive.Root";function da(){return da=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},da.apply(null,arguments)}function Of(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}var Ff=b.useLayoutEffect,zf=function(t){var r=b.useRef(t);return Ff(function(){r.current=t}),r},io=function(t,r){if(typeof t=="function"){t(r);return}t.current=r},Bf=function(t,r){var n=b.useRef();return b.useCallback(function(a){t.current=a,n.current&&io(n.current,null),n.current=r,r&&io(r,a)},[r])},oo={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},Rf=function(t){Object.keys(oo).forEach(function(r){t.style.setProperty(r,oo[r],"important")})},lo=Rf,Oe=null,uo=function(t,r){var n=t.scrollHeight;return r.sizingStyle.boxSizing==="border-box"?n+r.borderSize:n-r.paddingSize};function jf(e,t,r,n){r===void 0&&(r=1),n===void 0&&(n=1/0),Oe||(Oe=document.createElement("textarea"),Oe.setAttribute("tabindex","-1"),Oe.setAttribute("aria-hidden","true"),lo(Oe)),Oe.parentNode===null&&document.body.appendChild(Oe);var a=e.paddingSize,s=e.borderSize,i=e.sizingStyle,o=i.boxSizing;Object.keys(i).forEach(function(f){var h=f;Oe.style[h]=i[h]}),lo(Oe),Oe.value=t;var l=uo(Oe,e);Oe.value=t,l=uo(Oe,e),Oe.value="x";var u=Oe.scrollHeight-a,d=u*r;o==="border-box"&&(d=d+a+s),l=Math.max(d,l);var c=u*n;return o==="border-box"&&(c=c+a+s),l=Math.min(c,l),[l,u]}var co=function(){},$f=function(t,r){return t.reduce(function(n,a){return n[a]=r[a],n},{})},Uf=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],Hf=!!document.documentElement.currentStyle,qf=function(t){var r=window.getComputedStyle(t);if(r===null)return null;var n=$f(Uf,r),a=n.boxSizing;if(a==="")return null;Hf&&a==="border-box"&&(n.width=parseFloat(n.width)+parseFloat(n.borderRightWidth)+parseFloat(n.borderLeftWidth)+parseFloat(n.paddingRight)+parseFloat(n.paddingLeft)+"px");var s=parseFloat(n.paddingBottom)+parseFloat(n.paddingTop),i=parseFloat(n.borderBottomWidth)+parseFloat(n.borderTopWidth);return{sizingStyle:n,paddingSize:s,borderSize:i}},Vf=qf;function ha(e,t,r){var n=zf(r);Z.useLayoutEffect(function(){var a=function(i){return n.current(i)};if(e)return e.addEventListener(t,a),function(){return e.removeEventListener(t,a)}},[])}var Wf=function(t,r){ha(document.body,"reset",function(n){t.current.form===n.target&&r(n)})},Jf=function(t){ha(window,"resize",t)},Kf=function(t){ha(document.fonts,"loadingdone",t)},Yf=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],Gf=function(t,r){var n=t.cacheMeasurements,a=t.maxRows,s=t.minRows,i=t.onChange,o=i===void 0?co:i,l=t.onHeightChange,u=l===void 0?co:l,d=Of(t,Yf),c=d.value!==void 0,f=Z.useRef(null),h=Bf(f,r),g=Z.useRef(0),w=Z.useRef(),x=function(){var _=f.current,O=n&&w.current?w.current:Vf(_);if(O){w.current=O;var z=jf(O,_.value||_.placeholder||"x",s,a),C=z[0],U=z[1];g.current!==C&&(g.current=C,_.style.setProperty("height",C+"px","important"),u(C,{rowHeight:U}))}},y=function(_){c||x(),o(_)};return Z.useLayoutEffect(x),Wf(f,function(){if(!c){var E=f.current.value;requestAnimationFrame(function(){var _=f.current;_&&E!==_.value&&x()})}}),Jf(x),Kf(x),Z.createElement("textarea",da({},d,{onChange:y,ref:h}))},Xf=Z.forwardRef(Gf),ho=e=>{const t=At(e),r=en(n=>n.onScrollToBottom);b.useEffect(()=>r(t),[r,t])},fo=b.forwardRef((g,h)=>{var w=g,{autoFocus:e=!1,asChild:t,disabled:r,onChange:n,onKeyDown:a,onPaste:s,submitOnEnter:i=!0,cancelOnEscape:o=!0,unstable_focusOnRunStart:l=!0,unstable_focusOnScrollToBottom:u=!0,unstable_focusOnThreadSwitched:d=!0,addAttachmentOnPaste:c=!0}=w,f=H(w,["autoFocus","asChild","disabled","onChange","onKeyDown","onPaste","submitOnEnter","cancelOnEscape","unstable_focusOnRunStart","unstable_focusOnScrollToBottom","unstable_focusOnThreadSwitched","addAttachmentOnPaste"]);const x=pe(),y=ee(({composer:S})=>S.isEditing?S.text:""),E=t?la:Xf,_=ee(({thread:S})=>S.isDisabled)||r,O=b.useRef(null),z=Qr(h,O);mf(S=>{var N;if(!o||!((N=O.current)!=null&&N.contains(S.target)))return;const D=x.composer();D.getState().canCancel&&(D.cancel(),S.preventDefault())});const C=S=>{var D,N;_||!i||S.nativeEvent.isComposing||S.key==="Enter"&&S.shiftKey===!1&&(x.thread().getState().isRunning||(S.preventDefault(),(N=(D=O.current)==null?void 0:D.closest("form"))==null||N.requestSubmit()))},U=S=>M(null,null,function*(){var K;if(!c)return;const D=x.thread().getState().capabilities,N=Array.from(((K=S.clipboardData)==null?void 0:K.files)||[]);if(D.attachments&&N.length>0)try{S.preventDefault(),yield Promise.all(N.map(B=>x.composer().addAttachment(B)))}catch(B){console.error("Error adding attachment:",B)}}),V=e&&!_,R=b.useCallback(()=>{const S=O.current;!S||!V||(S.focus({preventScroll:!0}),S.setSelectionRange(S.value.length,S.value.length))},[V]);return b.useEffect(()=>R(),[R]),ho(()=>{x.composer().getState().type==="thread"&&u&&R()}),b.useEffect(()=>{if(!(x.composer().getState().type!=="thread"||!l))return x.on("thread.run-start",R)},[l,R,x]),b.useEffect(()=>{if(!(x.composer().getState().type!=="thread"||!d))return x.on("thread-list-item.switched-to",R)},[d,R,x]),p.jsx(E,I(m({name:"input",value:y},f),{ref:z,disabled:_,onChange:qt(n,S=>{x.composer().getState().isEditing&&(x.composer().setText(S.target.value),x.flushSync())}),onKeyDown:qt(a,C),onPaste:qt(s,U)}))});fo.displayName="ComposerPrimitive.Input";var Qf=({multiple:e=!0}={})=>{const t=ee(({composer:a})=>!a.isEditing),r=pe(),n=b.useCallback(()=>{const a=document.createElement("input");a.type="file",a.multiple=e,a.hidden=!0;const s=r.composer().getState().attachmentAccept;s!=="*"&&(a.accept=s),document.body.appendChild(a),a.onchange=i=>{const o=i.target.files;if(o){for(const l of o)r.composer().addAttachment(l);document.body.removeChild(a)}},a.oncancel=()=>{(!a.files||a.files.length===0)&&document.body.removeChild(a)},a.click()},[r,e]);return t?null:n},Zf=sn("ComposerPrimitive.AddAttachment",Qf,["multiple"]),ep=(e,t)=>{var n,a,s;const r=t.type;switch(r){case"image":return(n=e==null?void 0:e.Image)!=null?n:e==null?void 0:e.Attachment;case"document":return(a=e==null?void 0:e.Document)!=null?a:e==null?void 0:e.Attachment;case"file":return(s=e==null?void 0:e.File)!=null?s:e==null?void 0:e.Attachment;default:const i=r;throw new Error(`Unknown attachment type: ${i}`)}},tp=({components:e})=>{const t=ee(({attachment:n})=>n);if(!t)return null;const r=ep(e,t);return r?p.jsx(r,{}):null},po=b.memo(({index:e,components:t})=>p.jsx(kh,{index:e,children:p.jsx(tp,{components:t})}),(e,t)=>{var r,n,a,s,i,o,l,u;return e.index===t.index&&((r=e.components)==null?void 0:r.Image)===((n=t.components)==null?void 0:n.Image)&&((a=e.components)==null?void 0:a.Document)===((s=t.components)==null?void 0:s.Document)&&((i=e.components)==null?void 0:i.File)===((o=t.components)==null?void 0:o.File)&&((l=e.components)==null?void 0:l.Attachment)===((u=t.components)==null?void 0:u.Attachment)});po.displayName="ComposerPrimitive.AttachmentByIndex";var mo=({components:e})=>{const t=ee(n=>n.composer.attachments.length);return b.useMemo(()=>Array.from({length:t},(n,a)=>p.jsx(po,{index:a,components:e},a)),[t,e])};mo.displayName="ComposerPrimitive.Attachments";var go=b.forwardRef((s,a)=>{var i=s,{disabled:e,asChild:t=!1,children:r}=i,n=H(i,["disabled","asChild","children"]);const[o,l]=b.useState(!1),u=pe(),d=b.useCallback(x=>{e||(x.preventDefault(),l(!0))},[e]),c=b.useCallback(x=>{e||(x.preventDefault(),o||l(!0))},[e,o]),f=b.useCallback(x=>{if(e)return;x.preventDefault();const y=x.relatedTarget;y&&x.currentTarget.contains(y)||l(!1)},[e]),h=b.useCallback(x=>M(null,null,function*(){if(!e){x.preventDefault(),l(!1);for(const y of x.dataTransfer.files)try{yield u.composer().addAttachment(y)}catch(E){console.error("Failed to add attachment:",E)}}}),[e,u]),g={onDragEnterCapture:d,onDragOverCapture:c,onDragLeaveCapture:f,onDropCapture:h},w=t?la:"div";return p.jsx(w,I(m(m(I(m({},o?{"data-dragging":"true"}:null),{ref:a}),g),n),{children:r}))});go.displayName="ComposerPrimitive.AttachmentDropzone";var yo=b.forwardRef((e,t)=>p.jsx(ut.div,I(m({},e),{ref:t})));yo.displayName="ThreadPrimitive.Root";var bo=({children:e})=>ee(({thread:r})=>r.messages.length===0&&!r.isLoading)?e:null;bo.displayName="ThreadPrimitive.Empty";var rp=e=>{const t=At(e),r=b.useCallback(n=>{const a=new ResizeObserver(()=>{t()}),s=new MutationObserver(()=>{t()});return a.observe(n),s.observe(n,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{a.disconnect(),s.disconnect()}},[t]);return mr(r)},np=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:r=!0,scrollToBottomOnThreadSwitch:n=!0})=>{const a=b.useRef(null),s=Zn();e===void 0&&(e=s.getState().turnAnchor!=="top");const i=b.useRef(0),o=b.useRef(null),l=b.useCallback(h=>{const g=a.current;g&&(o.current=h,g.scrollTo({top:g.scrollHeight,behavior:h}))},[]),u=()=>{const h=a.current;if(!h)return;const g=s.getState().isAtBottom,w=Math.abs(h.scrollHeight-h.scrollTop-h.clientHeight)<1||h.scrollHeight<=h.clientHeight;!w&&i.current<h.scrollTop||(w&&(o.current=null),(w||o.current===null)&&w!==g&&pr(s).setState({isAtBottom:w})),i.current=h.scrollTop},d=rp(()=>{const h=o.current;h?l(h):e&&s.getState().isAtBottom&&l("instant"),u()}),c=mr(h=>(h.addEventListener("scroll",u),()=>{h.removeEventListener("scroll",u)}));return ho(({behavior:h})=>{l(h)}),Qn("thread.run-start",()=>{t&&(o.current="auto",requestAnimationFrame(()=>{l("auto")}))}),Qn("thread.initialize",()=>{r&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Qn("thread-list-item.switched-to",()=>{n&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Qr(d,c,a)},ap=()=>{const e=en(r=>r.registerViewport),t=b.useCallback(r=>r.clientHeight,[]);return qi(e,t)},xo=b.forwardRef((o,i)=>{var l=o,{autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:r,scrollToBottomOnThreadSwitch:n,children:a}=l,s=H(l,["autoScroll","scrollToBottomOnRunStart","scrollToBottomOnInitialize","scrollToBottomOnThreadSwitch","children"]);const u=np({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:r,scrollToBottomOnThreadSwitch:n}),d=ap(),c=Qr(i,u,d);return p.jsx(ut.div,I(m({},s),{ref:c,children:a}))});xo.displayName="ThreadPrimitive.ViewportScrollable";var wo=b.forwardRef((n,r)=>{var a=n,{turnAnchor:e}=a,t=H(a,["turnAnchor"]);return p.jsx(Ai,{options:{turnAnchor:e},children:p.jsx(xo,I(m({},t),{ref:r}))})});wo.displayName="ThreadPrimitive.Viewport";var vo=(e,t)=>e.Message===t.Message&&e.EditComposer===t.EditComposer&&e.UserEditComposer===t.UserEditComposer&&e.AssistantEditComposer===t.AssistantEditComposer&&e.SystemEditComposer===t.SystemEditComposer&&e.UserMessage===t.UserMessage&&e.AssistantMessage===t.AssistantMessage&&e.SystemMessage===t.SystemMessage,sp=()=>null,ip=(e,t,r)=>{var n,a,s,i,o,l,u,d,c,f,h,g;switch(t){case"user":return r?(s=(a=(n=e.UserEditComposer)!=null?n:e.EditComposer)!=null?a:e.UserMessage)!=null?s:e.Message:(i=e.UserMessage)!=null?i:e.Message;case"assistant":return r?(u=(l=(o=e.AssistantEditComposer)!=null?o:e.EditComposer)!=null?l:e.AssistantMessage)!=null?u:e.Message:(d=e.AssistantMessage)!=null?d:e.Message;case"system":return r?(h=(f=(c=e.SystemEditComposer)!=null?c:e.EditComposer)!=null?f:e.SystemMessage)!=null?h:e.Message:(g=e.SystemMessage)!=null?g:sp;default:const w=t;throw new Error(`Unknown message role: ${w}`)}},op=({components:e})=>{const t=ee(({message:a})=>a.role),r=ee(({message:a})=>a.composer.isEditing),n=ip(e,t,r);return p.jsx(n,{})},ko=b.memo(({index:e,components:t})=>p.jsx(xh,{index:e,children:p.jsx(op,{components:t})}),(e,t)=>e.index===t.index&&vo(e.components,t.components));ko.displayName="ThreadPrimitive.MessageByIndex";var So=({components:e})=>{const t=ee(({thread:n})=>n.messages.length);return b.useMemo(()=>t===0?null:Array.from({length:t},(n,a)=>p.jsx(ko,{index:a,components:e},a)),[t,e])};So.displayName="ThreadPrimitive.Messages";var lp=b.memo(So,(e,t)=>vo(e.components,t.components)),fa=b.forwardRef((a,n)=>{var s=a,{onClick:e,disabled:t}=s,r=H(s,["onClick","disabled"]);const i=ee(({threads:l})=>l.newThreadId===l.mainThreadId),o=pe();return p.jsx(ut.button,I(m(m({type:"button"},i?{"data-active":"true","aria-current":"true"}:null),r),{ref:n,disabled:t,onClick:qt(e,()=>{o.threads().switchToNewThread()})}))});fa.displayName="ThreadListPrimitive.New";var _o=b.memo(({index:e,archived:t=!1,components:r})=>{const n=r.ThreadListItem;return p.jsx(yh,{index:e,archived:t,children:p.jsx(n,{})})},(e,t)=>e.index===t.index&&e.archived===t.archived&&e.components.ThreadListItem===t.components.ThreadListItem);_o.displayName="ThreadListPrimitive.ItemByIndex";var To=({archived:e=!1,components:t})=>{const r=ee(({threads:a})=>e?a.archivedThreadIds.length:a.threadIds.length);return b.useMemo(()=>Array.from({length:r},(a,s)=>p.jsx(_o,{index:s,archived:e,components:t},s)),[r,e,t])};To.displayName="ThreadListPrimitive.Items";var pa=b.forwardRef((e,t)=>p.jsx(ut.div,I(m({},e),{ref:t})));pa.displayName="ThreadListPrimitive.Root";var ma=b.forwardRef((e,t)=>{const r=ee(({threads:n,threadListItem:a})=>n.mainThreadId===a.id);return p.jsx(ut.div,I(m(m({},r?{"data-active":"true","aria-current":"true"}:null),e),{ref:t}))});ma.displayName="ThreadListItemPrimitive.Root";var up=()=>{const e=pe();return b.useCallback(()=>{e.threadListItem().switchTo()},[e])},Co=sn("ThreadListItemPrimitive.Trigger",up);function cp(){if(typeof crypto!="undefined"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto!="undefined"&&crypto.getRandomValues){const e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`}class Io{constructor(t,r,n=!1){T(this,"baseUrl");T(this,"sessionToken",null);T(this,"isProxyMode",!1);this.baseUrl=t.replace(/\/$/,""),this.isProxyMode=n,r&&(this.sessionToken=r)}setSessionToken(t){this.sessionToken=t}getUrl(t){if(this.isProxyMode){const r=`${this.baseUrl}${t.replace("/v1","")}`;return r.startsWith("/")||r.startsWith("./"),r}return`${this.baseUrl}${t}`}createOrContinueChat(t,r){return M(this,null,function*(){const n=this.getUrl("/v1/chats"),s={"Content-Type":"application/json",Accept:"text/event-stream","Accept-Encoding":"identity","Cache-Control":"no-cache","X-Accel-Buffering":"no","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(s.Authorization=`Bearer ${this.sessionToken}`);const i=I(m({},t),{stream:!0}),o=yield fetch(n,{method:"POST",headers:s,body:JSON.stringify(i),signal:r,cache:"no-store"});if(!o.ok){const l=yield o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}if(!o.body)throw new Error("Response body is null");return o.body})}getChat(t){return M(this,null,function*(){const r=this.getUrl(`/v1/chats/${t}`),n={"Content-Type":"application/json"};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const a=yield fetch(r,{method:"GET",headers:n});if(!a.ok){const s=yield a.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${a.status} ${a.statusText}`)}return a.json()})}listChats(t){return M(this,null,function*(){const r=this.getUrl("/v1/chats"),n=r.startsWith("/")||r.startsWith("./")?new URL(r,window.location.origin):new URL(r);t!=null&&t.limit&&n.searchParams.set("limit",t.limit.toString()),t!=null&&t.cursor&&n.searchParams.set("cursor",t.cursor),t!=null&&t["expand[]"]&&t["expand[]"].forEach(i=>{n.searchParams.append("expand[]",i)});const a={"Content-Type":"application/json"};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const s=yield fetch(n.toString(),{method:"GET",headers:a});if(!s.ok){const i=yield s.json().catch(()=>({}));throw new Error(i.detail||i.message||`API error: ${s.status} ${s.statusText}`)}return s.json()})}generateIdempotencyKey(){return cp()}updateChat(t,r){return M(this,null,function*(){const n=`/v1/chats/${t}`,a=this.getUrl(n),s=a.startsWith("/")||a.startsWith("./")?new URL(a,window.location.origin):new URL(a),o={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(s.toString(),{method:"PATCH",headers:o,body:JSON.stringify(r)});if(!l.ok){const d=yield l.text();let c={};try{c=JSON.parse(d)}catch(f){c={detail:d}}throw new Error(c.detail||c.message||`API error: ${l.status} ${l.statusText}`)}if(l.status===204)return{};const u=yield l.text();if(!u)return{};try{return JSON.parse(u)}catch(d){return{}}})}deleteChat(t){return M(this,null,function*(){const r=`/v1/chats/${t}`,n=this.getUrl(r),a=n.startsWith("/")||n.startsWith("./")?new URL(n,window.location.origin):new URL(n),i={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const o=yield fetch(a.toString(),{method:"DELETE",headers:i});if(!o.ok){const l=yield o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}})}generateChatTitle(t,r){return M(this,null,function*(){const n=`/v1/chats/${t}/title`,a=this.getUrl(n),s=a.startsWith("/")||a.startsWith("./")?new URL(a,window.location.origin):new URL(a),o={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(s.toString(),{method:"POST",headers:o,body:r?JSON.stringify(r):void 0});if(!l.ok){const u=yield l.json().catch(()=>({}));throw new Error(u.detail||u.message||`API error: ${l.status} ${l.statusText}`)}return l.json()})}listModels(t){return M(this,null,function*(){const r=this.getUrl("/v1/models"),n=r.startsWith("/")||r.startsWith("./")?new URL(r,window.location.origin):new URL(r);t!=null&&t.limit&&n.searchParams.set("limit",t.limit.toString()),t!=null&&t.cursor&&n.searchParams.set("cursor",t.cursor),t!=null&&t["expand[]"]&&t["expand[]"].forEach(i=>{n.searchParams.append("expand[]",i)});const a={"Content-Type":"application/json"};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const s=yield fetch(n.toString(),{method:"GET",headers:a});if(!s.ok){const i=yield s.json().catch(()=>({}));throw new Error(i.detail||i.message||`API error: ${s.status} ${s.statusText}`)}return s.json()})}getModel(t){return M(this,null,function*(){const r=this.getUrl(`/v1/models/${t}`),n={"Content-Type":"application/json"};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const a=yield fetch(r,{method:"GET",headers:n});if(!a.ok){const s=yield a.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${a.status} ${a.statusText}`)}return a.json()})}uploadFile(t,r,n){return M(this,null,function*(){const a=this.getUrl("/v1/files"),s=this.generateIdempotencyKey(),i=new FormData;i.append("file",t),r&&i.append("resource_type",r),n&&i.append("resource_id",n);const o={"Idempotency-Key":s};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(a,{method:"POST",headers:o,body:i});if(!l.ok){const u=yield l.json().catch(()=>({}));throw new Error(u.detail||u.message||`API error: ${l.status} ${l.statusText}`)}return l.json()})}}function dp(e,t){return Or(this,null,function*(){const r=e.getReader(),n=new TextDecoder;let a="";try{for(;;){if(t!=null&&t.aborted){r.cancel();break}const{done:s,value:i}=yield new Ae(r.read());if(s)break;a+=n.decode(i,{stream:!0});const o=a.split(`
|
|
6
6
|
|
|
7
|
-
`);i=o.pop()||"";for(const l of o)if(l.startsWith("data: ")){const u=l.slice(6);if(u.trim()==="[DONE]"){yield{done:!0};continue}try{yield JSON.parse(u)}catch(d){}}}}finally{r.releaseLock()}})}function up(e){return e.map(t=>{let r="";if(typeof t.content=="string")r=t.content;else if(Array.isArray(t.content)){const n=t.content.find(i=>i.type==="text");n&&typeof n=="object"&&"text"in n&&(r=n.text)}return{role:t.role,content:r}})}function cp(e){return m(m({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 Vt=new Map,sn=new Map;let Wt;function li(e,t){const r=Vt.get(e);if(r)return r;if(t)for(const n of t){const i=sn.get(n.id);if(i)return Vt.set(e,i),i}return e}function dp(e,t){return{list(){return M(this,null,function*(){const n=[];let a,s=0;do{const l=yield e.listChats({limit:50,cursor:a}),u=l.items||[];Array.isArray(u)&&u.length>0&&n.push(...u),a=l.nextCursor||void 0,s++}while(a&&s<50);return{threads:n.map(l=>{const u=l.id;return!u||l.deletedAt?null:{status:"regular",remoteId:u,title:l.title||"New Chat",createdAt:l.createdAt?new Date(l.createdAt):new Date,updatedAt:l.updatedAt?new Date(l.updatedAt):new Date}}).filter(l=>l!==null)}})},initialize(n){return M(this,null,function*(){return{remoteId:Vt.get(n)||n,externalId:void 0}})},rename(n,i){return M(this,null,function*(){const a=li(n);yield e.updateChat(a,{title:i})})},archive(n){return M(this,null,function*(){})},unarchive(n){return M(this,null,function*(){})},delete(n){return M(this,null,function*(){const i=li(n);yield e.deleteChat(i)})},generateTitle(n,i){return M(this,null,function*(){var o;const a=li(n,i);let s;try{s=(yield e.generateChatTitle(a)).title}catch(l){console.error("[generateTitle] API call failed, falling back to first message",l);const u=i.find(c=>c.role==="user"),d=(o=u==null?void 0:u.content)==null?void 0:o.filter(c=>c.type==="text").map(c=>c.text).join(" ").trim();s=d?d.length>60?d.slice(0,57)+"...":d:void 0}return Da(l=>{const u=l.addTextPart();s&&u.append(s),u.close(),l.close()})})},fetch(n){return M(this,null,function*(){try{const i=yield e.getChat(n);return{status:"regular",remoteId:i.id||n,title:i.title||"Chat",createdAt:i.createdAt?new Date(i.createdAt):new Date,updatedAt:i.updatedAt?new Date(i.updatedAt):new Date}}catch(i){return{status:"regular",remoteId:n,createdAt:new Date,updatedAt:new Date}}})},updateRemoteId(n,i){Vt.set(n,i),t==null||t(n,i)},unstable_Provider:({children:n})=>{const i=vs(),a=i==null?void 0:i.remoteId;y.useEffect(()=>{a&&(Wt=a)},[a]);const s=y.useMemo(()=>({load(){return M(this,null,function*(){if(!a)return{messages:[]};try{const u=yield e.getChat(a);if(!u.messages||u.messages.length===0)return{messages:[]};const d=u.messages.map(f=>cp(f)),c=d.map((f,h)=>({message:f,parentId:h>0?d[h-1].id:null}));for(const f of d)sn.set(f.id,a);return{messages:c}}catch(u){return{messages:[]}}})},append(u){return M(this,null,function*(){})}}),[a,e]),o=y.useMemo(()=>({history:s}),[s]);return p.jsx(jn,{adapters:o,children:n})}}}class hp{constructor(){T(this,"messageMetadata",new Map);T(this,"currentMessageId",null);T(this,"listeners",new Set)}setCurrentMessage(t){this.currentMessageId=t}update(t){if(!this.currentMessageId)return;const r=this.messageMetadata.get(this.currentMessageId)||{},n=t.sources;n&&n.length>0&&(this.messageMetadata.set(this.currentMessageId,I(m({},r),{sources:n})),this.notify())}get(){return this.currentMessageId?this.messageMetadata.get(this.currentMessageId)||{}:{}}getForMessage(t){return this.messageMetadata.get(t)||{}}getCurrentMessageId(){return this.currentMessageId}clear(){this.currentMessageId=null}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}notify(){this.listeners.forEach(t=>t())}}const xt=new hp,To=new Map,ui=[];let on=[];function Co(e,t,r=50,n=800){ui.push({question:e,response:t,streamingSpeed:r,initialDelay:n})}function Io(e,t){const{modelId:r,systemPrompt:n,ephemeral:i,enableReasoning:a,onChatCreated:s,onUserMessage:o,onThreadIdUpdate:l,onBeforeRequest:u,mockResponseOnBlocked:d}=t;let c;return{run(h){return Dr(this,null,function*(){var ue,se,v,Y,xe;const{messages:g,abortSignal:x}=h,b=ui.shift();if(b){o==null||o();const j=(ue=b.initialDelay)!=null?ue:800;if(j>0&&(yield new Ae(new Promise(ne=>setTimeout(ne,j)))),x!=null&&x.aborted)throw new Error("Request aborted");const re=b.response.split(" ");let le="";const oe=b.streamingSpeed||50,Ee=`premade-${Date.now()}`;i&&(s==null||s(Ee));for(let ne=0;ne<re.length;ne++){if(x!=null&&x.aborted)throw new Error("Request aborted");le+=(ne===0?"":" ")+re[ne],yield{content:[{type:"text",text:le}]},yield new Ae(new Promise(we=>setTimeout(we,oe+Math.random()*(oe*.5))))}yield{content:[{type:"text",text:le}]},on.push({role:"user",content:b.question},{role:"assistant",content:b.response});return}let w;for(const j of g){const re=sn.get(j.id);if(re){w=re;break}}if(!w&&g.length>0){const j=g.find(re=>re.role==="user");if(j){const le=(typeof j.content=="string"?j.content:Array.isArray(j.content)&&((se=j.content.find(oe=>oe.type==="text"))==null?void 0:se.text)||"").substring(0,50);w=To.get(le)}}!w&&c&&(w=c),o==null||o();let E=g,_=-1;for(let j=g.length-1;j>=0;j--)if(g[j].role==="assistant"){_=j;break}(w||_>=0)&&_>=0&&(E=g.slice(_+1));const O=up(E);if(on.length>0&&!w){const j=on.map(re=>({role:re.role,content:re.content}));O.unshift(...j),on=[]}const z=[];let C;for(let j=E.length-1;j>=0;j--)if(E[j].role==="user"){C=E[j];break}if(C&&"attachments"in C){const j=C.attachments;if(j&&j.length>0){for(const re of j)if(re.file)try{const le=yield new Ae(e.uploadFile(re.file));z.push(le.id)}catch(le){}}}const U={messages:O,chatId:w||null,systemPrompt:n,ephemeral:i,enableReasoning:a,stream:!0};if(r&&r.trim()!==""&&(U.modelId=r),z.length>0&&(U.fileIds=z),u&&!(yield new Ae(u()))){if(d){const re=typeof d=="function"?d():d,le=g.filter(we=>we.role==="user"),oe=le.length>0?le[le.length-1]:void 0;let Ee="Message";if(oe){if(typeof oe.content=="string")Ee=oe.content;else if(Array.isArray(oe.content)){const we=oe.content.find(ot=>ot.type==="text");Ee=(we==null?void 0:we.text)||"Message"}}Co(Ee,re,40,400);const ne=ui.shift();if(ne){o==null||o();const we=(v=ne.initialDelay)!=null?v:400;if(we>0&&(yield new Ae(new Promise(ft=>setTimeout(ft,we)))),x!=null&&x.aborted)throw new Error("Request aborted");const ot=ne.response.split(" ");let lt="";const ht=ne.streamingSpeed||40,St=`mock-${Date.now()}`;i&&(s==null||s(St));for(let ft=0;ft<ot.length;ft++){if(x!=null&&x.aborted)throw new Error("Request aborted");lt+=(ft===0?"":" ")+ot[ft],yield{content:[{type:"text",text:lt}]},yield new Ae(new Promise(G=>setTimeout(G,ht+Math.random()*(ht*.3))))}yield{content:[{type:"text",text:lt}]};return}}throw new Error("Request blocked")}const V=yield new Ae(e.createOrContinueChat(U,x));let R="",S="",D;const N=[];let K=0,B=!1;const P=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;xt.clear(),xt.setCurrentMessage(P);const q=()=>{N.length!==K&&(K=N.length,xt.update({sources:N.length>0?[...N]:void 0}))},J=()=>{q();const j=[];return S&&j.push({type:"reasoning",text:S}),R&&j.push({type:"text",text:R}),j.length===0&&j.push({type:"text",text:""}),{content:j}};try{for(var k=Ft(lp(V,x)),Se,Ye,_e;Se=!(Ye=yield new Ae(k.next())).done;Se=!1){const j=Ye.value;if(x!=null&&x.aborted)throw new Error("Request aborted");const re=j.id||j.chatId||j.messageId;if(re&&!D){D=re,c=re,s==null||s(re);for(const ne of g)sn.set(ne.id,re);if(g.length>0){const ne=g.find(we=>we.role==="user");if(ne){const ot=(typeof ne.content=="string"?ne.content:Array.isArray(ne.content)&&((Y=ne.content.find(lt=>lt.type==="text"))==null?void 0:Y.text)||"").substring(0,50);To.set(ot,re)}}Wt&&!Vt.has(Wt)&&Vt.set(Wt,re),l&&Wt&&l(Wt,re)}const le=j.sources;if(le&&Array.isArray(le)&&le.length>0)for(const ne of le)N.some(we=>we.sourceId===ne.sourceId)||N.push({sourceId:ne.sourceId,filename:ne.filename||"Unknown",score:(xe=ne.score)!=null?xe:1,chunkId:ne.chunkId,datasetId:ne.datasetId});const oe=j.reasoning;if(oe&&oe.length>0&&(S+=oe,yield J()),j.type)switch(j.type){case"source-document":j.sourceId&&N.push({sourceId:j.sourceId,filename:j.title||"Unknown",score:1});continue;case"reasoning-start":continue;case"reasoning-delta":j.delta&&(S+=j.delta),(R||S)&&(yield J());continue;case"reasoning-end":(R||S)&&(yield J());continue;case"text-delta":j.delta&&(S&&!B&&!R&&(B=!0,yield new Ae(new Promise(ne=>setTimeout(ne,400)))),R+=j.delta),R&&(yield J());continue;case"error":throw new Error(j.errorText||"Stream error");case"text-start":case"text-end":case"start":case"start-step":case"finish-step":case"finish":continue}const Ee=j.delta;if(Ee!=null&&(S&&!B&&!R&&(B=!0,yield new Ae(new Promise(ne=>setTimeout(ne,400)))),R+=Ee),j.content&&(R+=j.content),j.message&&(R+=j.message.content||""),j.finished){(R||S||N.length>0)&&(yield J());break}(R||S||N.length>0)&&(yield J())}}catch(Ye){_e=[Ye]}finally{try{Se&&(Ye=k.return)&&(yield new Ae(Ye.call(k)))}finally{if(_e)throw _e[0]}}(R||S||N.length>0)&&(yield J())})}}}class mr extends Error{constructor(t,r,n){super(t),this.code=r,this.file=n,this.name="AttachmentValidationError"}}const fp=["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"],pp=[".pdf",".doc",".docx",".xls",".xlsx",".txt",".md",".csv",".json",".jpg",".jpeg",".png",".gif",".webp",".svg"],mp=10*1024*1024;function Eo(e){if(e===0)return"0 Bytes";const t=1024,r=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,n)).toFixed(2))+" "+r[n]}function gp(e){return e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")).toLowerCase():""}function yp(e,t){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(t.toLowerCase()):!0}function bp(){return typeof crypto!="undefined"&&crypto.randomUUID?"attachment-"+crypto.randomUUID():"attachment-"+Date.now()+"-"+Math.random().toString(36).slice(2,11)}function Ao(e={}){const{validation:t={},supportsVision:r=!0,onValidationError:n,onAttachmentAdded:i,onAttachmentRemoved:a}=e,{maxFileSizeBytes:s=mp,allowedMimeTypes:o=fp,allowedExtensions:l=pp,validateContentType:u=!0}=t,d=l.join(",");function c(h){if(h.size>s){const x=new mr('File "'+h.name+'" is too large ('+Eo(h.size)+"). Maximum size is "+Eo(s)+".","FILE_TOO_LARGE",h);throw n==null||n(x),x}if(!r&&h.type.startsWith("image/")){const x=new mr("The current model does not support image inputs. Please select a model with vision capabilities to attach images.","VISION_NOT_SUPPORTED",h);throw n==null||n(x),x}const g=gp(h.name);if(g&&!l.some(x=>x.toLowerCase()===g)){const x=new mr('File type "'+g+'" is not allowed. Allowed types: '+l.join(", "),"INVALID_TYPE",h);throw n==null||n(x),x}if(h.type&&!o.some(x=>{if(x.endsWith("/*")){const b=x.slice(0,-1);return h.type.startsWith(b)}return h.type===x})){const x=new mr('File type "'+h.type+'" is not allowed.',"INVALID_TYPE",h);throw n==null||n(x),x}if(u&&h.type&&g&&!yp(h.type,g)){const x=new mr('File extension "'+g+'" does not match content type "'+h.type+'".',"VALIDATION_FAILED",h);throw n==null||n(x),x}}return{accept:d,add(g){return M(this,arguments,function*({file:h}){c(h);let x="file";h.type.startsWith("image/")?x="image":(h.type.includes("pdf")||h.type.includes("document")||h.type.includes("text")||h.name.endsWith(".pdf")||h.name.endsWith(".docx")||h.name.endsWith(".txt")||h.name.endsWith(".md")||h.name.endsWith(".csv")||h.name.endsWith(".json"))&&(x="document");const b={id:bp(),type:x,name:h.name,contentType:h.type,file:h,status:{type:"requires-action",reason:"composer-send"}};return i==null||i(b),b})},remove(h){return M(this,null,function*(){a==null||a(h.id)})},send(h){return M(this,null,function*(){if(h.type==="image"&&h.file){const g=yield new Promise((x,b)=>{const w=new FileReader;w.onload=()=>x(w.result),w.onerror=()=>b(new Error("Failed to read file")),w.readAsDataURL(h.file)});return I(m({},h),{status:{type:"complete"},content:[{type:"image",image:g}]})}return I(m({},h),{status:{type:"complete"},content:[]})})}}}class wp{constructor(){T(this,"current",null);T(this,"listeners",new Set);T(this,"getSnapshot",()=>this.current);T(this,"subscribe",t=>(this.listeners.add(t),()=>this.listeners.delete(t)))}push(t,r){this.current={message:t,code:r,timestamp:Date.now()},this.notify()}clear(){this.current&&(this.current=null,this.notify())}notify(){this.listeners.forEach(t=>t())}}const Jt=new wp;function xp({children:e,baseUrl:t,sessionToken:r,isProxyMode:n=!1,mode:i="multiChat",modelId:a,onModelChange:s,ephemeral:o=!1,systemPrompt:l,enableReasoning:u=!1,initialThreadId:d,onError:c,onChatCreated:f,onUserMessage:h,onThreadIdUpdate:g,onChatsLoaded:x,enableAttachments:b=!1,supportsVision:w=!0,onBeforeRequest:E,mockResponseOnBlocked:_}){const O=y.useMemo(()=>new _o(t,r||void 0,n),[t,r,n]),[z,C]=y.useState(a||null);y.useEffect(()=>{a&&C(a)},[a]);const U=y.useCallback(S=>{f==null||f(S)},[f]),V=y.useCallback((S,D)=>{g==null||g(S,D)},[g]),R=y.useMemo(()=>Io(O,{modelId:z||void 0,systemPrompt:l,ephemeral:o,enableReasoning:u,onChatCreated:U,onUserMessage:h,onBeforeRequest:E,mockResponseOnBlocked:_}),[O,z,l,o,u,U,h,E,_]);return i==="singleChat"?p.jsx(vp,{modelAdapter:R,enableAttachments:b,supportsVision:w,children:e}):p.jsx(kp,{client:O,modelAdapterOptions:{modelId:z||void 0,systemPrompt:l,ephemeral:o,enableReasoning:u,onChatCreated:U,onUserMessage:h,onBeforeRequest:E,mockResponseOnBlocked:_},initialThreadId:d,onChatsLoaded:x,onThreadIdUpdate:V,onError:c,enableAttachments:b,supportsVision:w,children:e})}function vp({modelAdapter:e,enableAttachments:t,supportsVision:r=!0,children:n}){const i=y.useMemo(()=>t?Ao({supportsVision:r,onValidationError:s=>{Jt.push(s.message,s.code)}}):void 0,[t,r]),a=Ps(e,{adapters:m({},i&&{attachments:i})});return p.jsx(Ts,{runtime:a,children:n})}function kp({client:e,modelAdapterOptions:t,initialThreadId:r,onChatsLoaded:n,onThreadIdUpdate:i,onError:a,enableAttachments:s,supportsVision:o,children:l}){const u=y.useMemo(()=>dp(e,(b,w)=>{i==null||i(b,w)}),[e,i]),d=y.useCallback((b,w)=>{u.updateRemoteId&&u.updateRemoteId(b,w),i==null||i(b,w)},[u,i]),c=y.useMemo(()=>I(m({},u),{list(){return M(this,null,function*(){const w=yield u.list();return n==null||n(),w})}}),[u,n]);y.useEffect(()=>{window.__cuadraThreadListAdapter=c,window.__cuadraThreadListRuntime=null},[c]);const f=y.useMemo(()=>Io(e,I(m({},t),{onThreadIdUpdate:d})),[e,t,d]),h=y.useMemo(()=>s?Ao({supportsVision:o,onValidationError:b=>{Jt.push(b.message,b.code)}}):void 0,[s,o]),g=y.useCallback(()=>Ps(f,{adapters:m({},h&&{attachments:h})}),[f,h]),x=Fs({adapter:c,runtimeHook:g});return y.useEffect(()=>{window.__cuadraThreadListRuntime=x},[x]),p.jsx(Ts,{runtime:x,children:l})}function Jv(){}function Kv(){}function Sp(e,t){const r={};return(e[e.length-1]===""?[...e,""]:e).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}const _p=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Tp=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Cp={};function Mo(e,t){return(Cp.jsx?Tp:_p).test(e)}const Ip=/[ \t\n\f\r]/g;function Ep(e){return typeof e=="object"?e.type==="text"?Po(e.value):!1:Po(e)}function Po(e){return e.replace(Ip,"")===""}class gr{constructor(t,r,n){this.normal=r,this.property=t,n&&(this.space=n)}}gr.prototype.normal={},gr.prototype.property={},gr.prototype.space=void 0;function No(e,t){const r={},n={};for(const i of e)Object.assign(r,i.property),Object.assign(n,i.normal);return new gr(r,n,t)}function ci(e){return e.toLowerCase()}class Re{constructor(t,r){this.attribute=r,this.property=t}}Re.prototype.attribute="",Re.prototype.booleanish=!1,Re.prototype.boolean=!1,Re.prototype.commaOrSpaceSeparated=!1,Re.prototype.commaSeparated=!1,Re.prototype.defined=!1,Re.prototype.mustUseProperty=!1,Re.prototype.number=!1,Re.prototype.overloadedBoolean=!1,Re.prototype.property="",Re.prototype.spaceSeparated=!1,Re.prototype.space=void 0;let Ap=0;const Q=Mt(),ke=Mt(),di=Mt(),L=Mt(),fe=Mt(),Kt=Mt(),He=Mt();function Mt(){return Ru(2,++Ap)}const hi=Object.freeze(Object.defineProperty({__proto__:null,boolean:Q,booleanish:ke,commaOrSpaceSeparated:He,commaSeparated:Kt,number:L,overloadedBoolean:di,spaceSeparated:fe},Symbol.toStringTag,{value:"Module"})),fi=Object.keys(hi);class pi extends Re{constructor(t,r,n,i){let a=-1;if(super(t,r),Lo(this,"space",i),typeof n=="number")for(;++a<fi.length;){const s=fi[a];Lo(this,fi[a],(n&hi[s])===hi[s])}}}pi.prototype.defined=!0;function Lo(e,t,r){r&&(e[t]=r)}function Yt(e){const t={},r={};for(const[n,i]of Object.entries(e.properties)){const a=new pi(n,e.transform(e.attributes||{},n),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(n)&&(a.mustUseProperty=!0),t[n]=a,r[ci(n)]=n,r[ci(a.attribute)]=n}return new gr(t,r,e.space)}const Do=Yt({properties:{ariaActiveDescendant:null,ariaAtomic:ke,ariaAutoComplete:null,ariaBusy:ke,ariaChecked:ke,ariaColCount:L,ariaColIndex:L,ariaColSpan:L,ariaControls:fe,ariaCurrent:null,ariaDescribedBy:fe,ariaDetails:null,ariaDisabled:ke,ariaDropEffect:fe,ariaErrorMessage:null,ariaExpanded:ke,ariaFlowTo:fe,ariaGrabbed:ke,ariaHasPopup:null,ariaHidden:ke,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:fe,ariaLevel:L,ariaLive:null,ariaModal:ke,ariaMultiLine:ke,ariaMultiSelectable:ke,ariaOrientation:null,ariaOwns:fe,ariaPlaceholder:null,ariaPosInSet:L,ariaPressed:ke,ariaReadOnly:ke,ariaRelevant:null,ariaRequired:ke,ariaRoleDescription:fe,ariaRowCount:L,ariaRowIndex:L,ariaRowSpan:L,ariaSelected:ke,ariaSetSize:L,ariaSort:null,ariaValueMax:L,ariaValueMin:L,ariaValueNow:L,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function Oo(e,t){return t in e?e[t]:t}function Fo(e,t){return Oo(e,t.toLowerCase())}const Mp=Yt({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Kt,acceptCharset:fe,accessKey:fe,action:null,allow:null,allowFullScreen:Q,allowPaymentRequest:Q,allowUserMedia:Q,alt:null,as:null,async:Q,autoCapitalize:null,autoComplete:fe,autoFocus:Q,autoPlay:Q,blocking:fe,capture:null,charSet:null,checked:Q,cite:null,className:fe,cols:L,colSpan:null,content:null,contentEditable:ke,controls:Q,controlsList:fe,coords:L|Kt,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Q,defer:Q,dir:null,dirName:null,disabled:Q,download:di,draggable:ke,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Q,formTarget:null,headers:fe,height:L,hidden:di,high:L,href:null,hrefLang:null,htmlFor:fe,httpEquiv:fe,id:null,imageSizes:null,imageSrcSet:null,inert:Q,inputMode:null,integrity:null,is:null,isMap:Q,itemId:null,itemProp:fe,itemRef:fe,itemScope:Q,itemType:fe,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Q,low:L,manifest:null,max:null,maxLength:L,media:null,method:null,min:null,minLength:L,multiple:Q,muted:Q,name:null,nonce:null,noModule:Q,noValidate:Q,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:Q,optimum:L,pattern:null,ping:fe,placeholder:null,playsInline:Q,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Q,referrerPolicy:null,rel:fe,required:Q,reversed:Q,rows:L,rowSpan:L,sandbox:fe,scope:null,scoped:Q,seamless:Q,selected:Q,shadowRootClonable:Q,shadowRootDelegatesFocus:Q,shadowRootMode:null,shape:null,size:L,sizes:null,slot:null,span:L,spellCheck:ke,src:null,srcDoc:null,srcLang:null,srcSet:null,start:L,step:null,style:null,tabIndex:L,target:null,title:null,translate:null,type:null,typeMustMatch:Q,useMap:null,value:ke,width:L,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:fe,axis:null,background:null,bgColor:null,border:L,borderColor:null,bottomMargin:L,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Q,declare:Q,event:null,face:null,frame:null,frameBorder:null,hSpace:L,leftMargin:L,link:null,longDesc:null,lowSrc:null,marginHeight:L,marginWidth:L,noResize:Q,noHref:Q,noShade:Q,noWrap:Q,object:null,profile:null,prompt:null,rev:null,rightMargin:L,rules:null,scheme:null,scrolling:ke,standby:null,summary:null,text:null,topMargin:L,valueType:null,version:null,vAlign:null,vLink:null,vSpace:L,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Q,disableRemotePlayback:Q,prefix:null,property:null,results:L,security:null,unselectable:null},space:"html",transform:Fo}),Pp=Yt({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:He,accentHeight:L,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:L,amplitude:L,arabicForm:null,ascent:L,attributeName:null,attributeType:null,azimuth:L,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:L,by:null,calcMode:null,capHeight:L,className:fe,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:L,diffuseConstant:L,direction:null,display:null,dur:null,divisor:L,dominantBaseline:null,download:Q,dx:null,dy:null,edgeMode:null,editable:null,elevation:L,enableBackground:null,end:null,event:null,exponent:L,externalResourcesRequired:null,fill:null,fillOpacity:L,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Kt,g2:Kt,glyphName:Kt,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:L,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:L,horizOriginX:L,horizOriginY:L,id:null,ideographic:L,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:L,k:L,k1:L,k2:L,k3:L,k4:L,kernelMatrix:He,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:L,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:L,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:L,overlineThickness:L,paintOrder:null,panose1:null,path:null,pathLength:L,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:fe,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:L,pointsAtY:L,pointsAtZ:L,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:He,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:He,rev:He,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:He,requiredFeatures:He,requiredFonts:He,requiredFormats:He,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:L,specularExponent:L,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:L,strikethroughThickness:L,string:null,stroke:null,strokeDashArray:He,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:L,strokeOpacity:L,strokeWidth:null,style:null,surfaceScale:L,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:He,tabIndex:L,tableValues:null,target:null,targetX:L,targetY:L,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:He,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:L,underlineThickness:L,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:L,values:null,vAlphabetic:L,vMathematical:L,vectorEffect:null,vHanging:L,vIdeographic:L,version:null,vertAdvY:L,vertOriginX:L,vertOriginY:L,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:L,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Oo}),zo=Yt({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),Bo=Yt({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Fo}),Ro=Yt({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),Np={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},Lp=/[A-Z]/g,jo=/-[a-z]/g,Dp=/^data[-\w.:]+$/i;function Op(e,t){const r=ci(t);let n=t,i=Re;if(r in e.normal)return e.property[e.normal[r]];if(r.length>4&&r.slice(0,4)==="data"&&Dp.test(t)){if(t.charAt(4)==="-"){const a=t.slice(5).replace(jo,zp);n="data"+a.charAt(0).toUpperCase()+a.slice(1)}else{const a=t.slice(4);if(!jo.test(a)){let s=a.replace(Lp,Fp);s.charAt(0)!=="-"&&(s="-"+s),t="data"+s}}i=pi}return new i(n,t)}function Fp(e){return"-"+e.toLowerCase()}function zp(e){return e.charAt(1).toUpperCase()}const Bp=No([Do,Mp,zo,Bo,Ro],"html"),mi=No([Do,Pp,zo,Bo,Ro],"svg");function Rp(e){return e.join(" ").trim()}var Gt={},gi,$o;function jp(){if($o)return gi;$o=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,r=/^\s*/,n=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,i=/^:\s*/,a=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,s=/^[;\s]*/,o=/^\s+|\s+$/g,l=`
|
|
8
|
-
`,u="/",d="*",c="",f="comment",h="declaration";function g(b,w){if(typeof b!="string")throw new TypeError("First argument must be a string");if(!b)return[];w=w||{};var E=1,_=1;function O(B){var P=B.match(t);P&&(E+=P.length);var q=B.lastIndexOf(l);_=~q?B.length-q:_+B.length}function z(){var B={line:E,column:_};return function(P){return P.position=new C(B),R(),P}}function C(B){this.start=B,this.end={line:E,column:_},this.source=w.source}C.prototype.content=b;function U(B){var P=new Error(w.source+":"+E+":"+_+": "+B);if(P.reason=B,P.filename=w.source,P.line=E,P.column=_,P.source=b,!w.silent)throw P}function V(B){var P=B.exec(b);if(P){var q=P[0];return O(q),b=b.slice(q.length),P}}function R(){V(r)}function S(B){var P;for(B=B||[];P=D();)P!==!1&&B.push(P);return B}function D(){var B=z();if(!(u!=b.charAt(0)||d!=b.charAt(1))){for(var P=2;c!=b.charAt(P)&&(d!=b.charAt(P)||u!=b.charAt(P+1));)++P;if(P+=2,c===b.charAt(P-1))return U("End of comment missing");var q=b.slice(2,P-2);return _+=2,O(q),b=b.slice(P),_+=2,B({type:f,comment:q})}}function N(){var B=z(),P=V(n);if(P){if(D(),!V(i))return U("property missing ':'");var q=V(a),J=B({type:h,property:x(P[0].replace(e,c)),value:q?x(q[0].replace(e,c)):c});return V(s),J}}function K(){var B=[];S(B);for(var P;P=N();)P!==!1&&(B.push(P),S(B));return B}return R(),K()}function x(b){return b?b.replace(o,c):c}return gi=g,gi}var Uo;function $p(){if(Uo)return Gt;Uo=1;var e=Gt&&Gt.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.default=r;const t=e(jp());function r(n,i){let a=null;if(!n||typeof n!="string")return a;const s=(0,t.default)(n),o=typeof i=="function";return s.forEach(l=>{if(l.type!=="declaration")return;const{property:u,value:d}=l;o?i(u,d,l):d&&(a=a||{},a[u]=d)}),a}return Gt}var yr={},Ho;function Up(){if(Ho)return yr;Ho=1,Object.defineProperty(yr,"__esModule",{value:!0}),yr.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,r=/^[^-]+$/,n=/^-(webkit|moz|ms|o|khtml)-/,i=/^-(ms)-/,a=function(u){return!u||r.test(u)||e.test(u)},s=function(u,d){return d.toUpperCase()},o=function(u,d){return"".concat(d,"-")},l=function(u,d){return d===void 0&&(d={}),a(u)?u:(u=u.toLowerCase(),d.reactCompat?u=u.replace(i,o):u=u.replace(n,o),u.replace(t,s))};return yr.camelCase=l,yr}var br,qo;function Hp(){if(qo)return br;qo=1;var e=br&&br.__importDefault||function(i){return i&&i.__esModule?i:{default:i}},t=e($p()),r=Up();function n(i,a){var s={};return!i||typeof i!="string"||(0,t.default)(i,function(o,l){o&&l&&(s[(0,r.camelCase)(o,a)]=l)}),s}return n.default=n,br=n,br}var qp=Hp();const Vp=Fr(qp),Vo=Wo("end"),yi=Wo("start");function Wo(e){return t;function t(r){const n=r&&r.position&&r.position[e]||{};if(typeof n.line=="number"&&n.line>0&&typeof n.column=="number"&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset=="number"&&n.offset>-1?n.offset:void 0}}}function Wp(e){const t=yi(e),r=Vo(e);if(t&&r)return{start:t,end:r}}function wr(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Jo(e.position):"start"in e||"end"in e?Jo(e):"line"in e||"column"in e?bi(e):""}function bi(e){return Ko(e&&e.line)+":"+Ko(e&&e.column)}function Jo(e){return bi(e&&e.start)+"-"+bi(e&&e.end)}function Ko(e){return e&&typeof e=="number"?e:1}class Pe extends Error{constructor(t,r,n){super(),typeof r=="string"&&(n=r,r=void 0);let i="",a={},s=!1;if(r&&("line"in r&&"column"in r?a={place:r}:"start"in r&&"end"in r?a={place:r}:"type"in r?a={ancestors:[r],place:r.position}:a=m({},r)),typeof t=="string"?i=t:!a.cause&&t&&(s=!0,i=t.message,a.cause=t),!a.ruleId&&!a.source&&typeof n=="string"){const l=n.indexOf(":");l===-1?a.ruleId=n:(a.source=n.slice(0,l),a.ruleId=n.slice(l+1))}if(!a.place&&a.ancestors&&a.ancestors){const l=a.ancestors[a.ancestors.length-1];l&&(a.place=l.position)}const o=a.place&&"start"in a.place?a.place.start:a.place;this.ancestors=a.ancestors||void 0,this.cause=a.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file="",this.message=i,this.line=o?o.line:void 0,this.name=wr(a.place)||"1:1",this.place=a.place||void 0,this.reason=this.message,this.ruleId=a.ruleId||void 0,this.source=a.source||void 0,this.stack=s&&a.cause&&typeof a.cause.stack=="string"?a.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Pe.prototype.file="",Pe.prototype.name="",Pe.prototype.reason="",Pe.prototype.message="",Pe.prototype.stack="",Pe.prototype.column=void 0,Pe.prototype.line=void 0,Pe.prototype.ancestors=void 0,Pe.prototype.cause=void 0,Pe.prototype.fatal=void 0,Pe.prototype.place=void 0,Pe.prototype.ruleId=void 0,Pe.prototype.source=void 0;const wi={}.hasOwnProperty,Jp=new Map,Kp=/[A-Z]/g,Yp=new Set(["table","tbody","thead","tfoot","tr"]),Gp=new Set(["td","th"]),Yo="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Xp(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const r=t.filePath||void 0;let n;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");n=am(r,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");n=im(r,t.jsx,t.jsxs)}const i={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:n,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:r,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?mi:Bp,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},a=Go(i,e,void 0);return a&&typeof a!="string"?a:i.create(e,i.Fragment,{children:a||void 0},void 0)}function Go(e,t,r){if(t.type==="element")return Qp(e,t,r);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return Zp(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return tm(e,t,r);if(t.type==="mdxjsEsm")return em(e,t);if(t.type==="root")return rm(e,t,r);if(t.type==="text")return nm(e,t)}function Qp(e,t,r){const n=e.schema;let i=n;t.tagName.toLowerCase()==="svg"&&n.space==="html"&&(i=mi,e.schema=i),e.ancestors.push(t);const a=Qo(e,t.tagName,!1),s=sm(e,t);let o=vi(e,t);return Yp.has(t.tagName)&&(o=o.filter(function(l){return typeof l=="string"?!Ep(l):!0})),Xo(e,s,a,t),xi(s,o),e.ancestors.pop(),e.schema=n,e.create(t,a,s,r)}function Zp(e,t){if(t.data&&t.data.estree&&e.evaluater){const n=t.data.estree.body[0];return n.type,e.evaluater.evaluateExpression(n.expression)}xr(e,t.position)}function em(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);xr(e,t.position)}function tm(e,t,r){const n=e.schema;let i=n;t.name==="svg"&&n.space==="html"&&(i=mi,e.schema=i),e.ancestors.push(t);const a=t.name===null?e.Fragment:Qo(e,t.name,!0),s=om(e,t),o=vi(e,t);return Xo(e,s,a,t),xi(s,o),e.ancestors.pop(),e.schema=n,e.create(t,a,s,r)}function rm(e,t,r){const n={};return xi(n,vi(e,t)),e.create(t,e.Fragment,n,r)}function nm(e,t){return t.value}function Xo(e,t,r,n){typeof r!="string"&&r!==e.Fragment&&e.passNode&&(t.node=n)}function xi(e,t){if(t.length>0){const r=t.length>1?t:t[0];r&&(e.children=r)}}function im(e,t,r){return n;function n(i,a,s,o){const u=Array.isArray(s.children)?r:t;return o?u(a,s,o):u(a,s)}}function am(e,t){return r;function r(n,i,a,s){const o=Array.isArray(a.children),l=yi(n);return t(i,a,s,o,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function sm(e,t){const r={};let n,i;for(i in t.properties)if(i!=="children"&&wi.call(t.properties,i)){const a=lm(e,i,t.properties[i]);if(a){const[s,o]=a;e.tableCellAlignToStyle&&s==="align"&&typeof o=="string"&&Gp.has(t.tagName)?n=o:r[s]=o}}if(n){const a=r.style||(r.style={});a[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=n}return r}function om(e,t){const r={};for(const n of t.attributes)if(n.type==="mdxJsxExpressionAttribute")if(n.data&&n.data.estree&&e.evaluater){const a=n.data.estree.body[0];a.type;const s=a.expression;s.type;const o=s.properties[0];o.type,Object.assign(r,e.evaluater.evaluateExpression(o.argument))}else xr(e,t.position);else{const i=n.name;let a;if(n.value&&typeof n.value=="object")if(n.value.data&&n.value.data.estree&&e.evaluater){const o=n.value.data.estree.body[0];o.type,a=e.evaluater.evaluateExpression(o.expression)}else xr(e,t.position);else a=n.value===null?!0:n.value;r[i]=a}return r}function vi(e,t){const r=[];let n=-1;const i=e.passKeys?new Map:Jp;for(;++n<t.children.length;){const a=t.children[n];let s;if(e.passKeys){const l=a.type==="element"?a.tagName:a.type==="mdxJsxFlowElement"||a.type==="mdxJsxTextElement"?a.name:void 0;if(l){const u=i.get(l)||0;s=l+"-"+u,i.set(l,u+1)}}const o=Go(e,a,s);o!==void 0&&r.push(o)}return r}function lm(e,t,r){const n=Op(e.schema,t);if(!(r==null||typeof r=="number"&&Number.isNaN(r))){if(Array.isArray(r)&&(r=n.commaSeparated?Sp(r):Rp(r)),n.property==="style"){let i=typeof r=="object"?r:um(e,String(r));return e.stylePropertyNameCase==="css"&&(i=cm(i)),["style",i]}return[e.elementAttributeNameCase==="react"&&n.space?Np[n.property]||n.property:n.attribute,r]}}function um(e,t){try{return Vp(t,{reactCompat:!0})}catch(r){if(e.ignoreInvalidStyle)return{};const n=r,i=new Pe("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:n,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw i.file=e.filePath||void 0,i.url=Yo+"#cannot-parse-style-attribute",i}}function Qo(e,t,r){let n;if(!r)n={type:"Literal",value:t};else if(t.includes(".")){const i=t.split(".");let a=-1,s;for(;++a<i.length;){const o=Mo(i[a])?{type:"Identifier",name:i[a]}:{type:"Literal",value:i[a]};s=s?{type:"MemberExpression",object:s,property:o,computed:!!(a&&o.type==="Literal"),optional:!1}:o}n=s}else n=Mo(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(n.type==="Literal"){const i=n.value;return wi.call(e.components,i)?e.components[i]:i}if(e.evaluater)return e.evaluater.evaluateExpression(n);xr(e)}function xr(e,t){const r=new Pe("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=Yo+"#cannot-handle-mdx-estrees-without-createevaluater",r}function cm(e){const t={};let r;for(r in e)wi.call(e,r)&&(t[dm(r)]=e[r]);return t}function dm(e){let t=e.replace(Kp,hm);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function hm(e){return"-"+e.toLowerCase()}const ki={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},fm={};function Si(e,t){const r=fm,n=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,i=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return Zo(e,n,i)}function Zo(e,t,r){if(pm(e)){if("value"in e)return e.type==="html"&&!r?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return el(e.children,t,r)}return Array.isArray(e)?el(e,t,r):""}function el(e,t,r){const n=[];let i=-1;for(;++i<e.length;)n[i]=Zo(e[i],t,r);return n.join("")}function pm(e){return!!(e&&typeof e=="object")}const tl=document.createElement("i");function _i(e){const t="&"+e+";";tl.innerHTML=t;const r=tl.textContent;return r.charCodeAt(r.length-1)===59&&e!=="semi"||r===t?!1:r}function qe(e,t,r,n){const i=e.length;let a=0,s;if(t<0?t=-t>i?0:i+t:t=t>i?i:t,r=r>0?r:0,n.length<1e4)s=Array.from(n),s.unshift(t,r),e.splice(...s);else for(r&&e.splice(t,r);a<n.length;)s=n.slice(a,a+1e4),s.unshift(t,0),e.splice(...s),a+=1e4,t+=1e4}function Je(e,t){return e.length>0?(qe(e,e.length,0,t),e):t}const rl={}.hasOwnProperty;function nl(e){const t={};let r=-1;for(;++r<e.length;)mm(t,e[r]);return t}function mm(e,t){let r;for(r in t){const i=(rl.call(e,r)?e[r]:void 0)||(e[r]={}),a=t[r];let s;if(a)for(s in a){rl.call(i,s)||(i[s]=[]);const o=a[s];gm(i[s],Array.isArray(o)?o:o?[o]:[])}}}function gm(e,t){let r=-1;const n=[];for(;++r<t.length;)(t[r].add==="after"?e:n).push(t[r]);qe(e,0,0,n)}function il(e,t){const r=Number.parseInt(e,t);return r<9||r===11||r>13&&r<32||r>126&&r<160||r>55295&&r<57344||r>64975&&r<65008||(r&65535)===65535||(r&65535)===65534||r>1114111?"�":String.fromCodePoint(r)}function et(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Fe=vt(/[A-Za-z]/),Ne=vt(/[\dA-Za-z]/),ym=vt(/[#-'*+\--9=?A-Z^-~]/);function ln(e){return e!==null&&(e<32||e===127)}const Ti=vt(/\d/),bm=vt(/[\dA-Fa-f]/),wm=vt(/[!-/:-@[-`{-~]/);function W(e){return e!==null&&e<-2}function de(e){return e!==null&&(e<0||e===32)}function te(e){return e===-2||e===-1||e===32}const un=vt(new RegExp("\\p{P}|\\p{S}","u")),Pt=vt(/\s/);function vt(e){return t;function t(r){return r!==null&&r>-1&&e.test(String.fromCharCode(r))}}function Xt(e){const t=[];let r=-1,n=0,i=0;for(;++r<e.length;){const a=e.charCodeAt(r);let s="";if(a===37&&Ne(e.charCodeAt(r+1))&&Ne(e.charCodeAt(r+2)))i=2;else if(a<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(a))||(s=String.fromCharCode(a));else if(a>55295&&a<57344){const o=e.charCodeAt(r+1);a<56320&&o>56319&&o<57344?(s=String.fromCharCode(a,o),i=1):s="�"}else s=String.fromCharCode(a);s&&(t.push(e.slice(n,r),encodeURIComponent(s)),n=r+i+1,s=""),i&&(r+=i,i=0)}return t.join("")+e.slice(n)}function ae(e,t,r,n){const i=n?n-1:Number.POSITIVE_INFINITY;let a=0;return s;function s(l){return te(l)?(e.enter(r),o(l)):t(l)}function o(l){return te(l)&&a++<i?(e.consume(l),o):(e.exit(r),t(l))}}const xm={tokenize:vm};function vm(e){const t=e.attempt(this.parser.constructs.contentInitial,n,i);let r;return t;function n(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),ae(e,t,"linePrefix")}function i(o){return e.enter("paragraph"),a(o)}function a(o){const l=e.enter("chunkText",{contentType:"text",previous:r});return r&&(r.next=l),r=l,s(o)}function s(o){if(o===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(o);return}return W(o)?(e.consume(o),e.exit("chunkText"),a):(e.consume(o),s)}}const km={tokenize:Sm},al={tokenize:_m};function Sm(e){const t=this,r=[];let n=0,i,a,s;return o;function o(_){if(n<r.length){const O=r[n];return t.containerState=O[1],e.attempt(O[0].continuation,l,u)(_)}return u(_)}function l(_){if(n++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,i&&E();const O=t.events.length;let z=O,C;for(;z--;)if(t.events[z][0]==="exit"&&t.events[z][1].type==="chunkFlow"){C=t.events[z][1].end;break}w(n);let U=O;for(;U<t.events.length;)t.events[U][1].end=m({},C),U++;return qe(t.events,z+1,0,t.events.slice(O)),t.events.length=U,u(_)}return o(_)}function u(_){if(n===r.length){if(!i)return f(_);if(i.currentConstruct&&i.currentConstruct.concrete)return g(_);t.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(al,d,c)(_)}function d(_){return i&&E(),w(n),f(_)}function c(_){return t.parser.lazy[t.now().line]=n!==r.length,s=t.now().offset,g(_)}function f(_){return t.containerState={},e.attempt(al,h,g)(_)}function h(_){return n++,r.push([t.currentConstruct,t.containerState]),f(_)}function g(_){if(_===null){i&&E(),w(0),e.consume(_);return}return i=i||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:i,contentType:"flow",previous:a}),x(_)}function x(_){if(_===null){b(e.exit("chunkFlow"),!0),w(0),e.consume(_);return}return W(_)?(e.consume(_),b(e.exit("chunkFlow")),n=0,t.interrupt=void 0,o):(e.consume(_),x)}function b(_,O){const z=t.sliceStream(_);if(O&&z.push(null),_.previous=a,a&&(a.next=_),a=_,i.defineSkip(_.start),i.write(z),t.parser.lazy[_.start.line]){let C=i.events.length;for(;C--;)if(i.events[C][1].start.offset<s&&(!i.events[C][1].end||i.events[C][1].end.offset>s))return;const U=t.events.length;let V=U,R,S;for(;V--;)if(t.events[V][0]==="exit"&&t.events[V][1].type==="chunkFlow"){if(R){S=t.events[V][1].end;break}R=!0}for(w(n),C=U;C<t.events.length;)t.events[C][1].end=m({},S),C++;qe(t.events,V+1,0,t.events.slice(U)),t.events.length=C}}function w(_){let O=r.length;for(;O-- >_;){const z=r[O];t.containerState=z[1],z[0].exit.call(t,e)}r.length=_}function E(){i.write([null]),a=void 0,i=void 0,t.containerState._closeFlow=void 0}}function _m(e,t,r){return ae(e,e.attempt(this.parser.constructs.document,t,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Qt(e){if(e===null||de(e)||Pt(e))return 1;if(un(e))return 2}function cn(e,t,r){const n=[];let i=-1;for(;++i<e.length;){const a=e[i].resolveAll;a&&!n.includes(a)&&(t=a(t,r),n.push(a))}return t}const Ci={name:"attention",resolveAll:Tm,tokenize:Cm};function Tm(e,t){let r=-1,n,i,a,s,o,l,u,d;for(;++r<e.length;)if(e[r][0]==="enter"&&e[r][1].type==="attentionSequence"&&e[r][1]._close){for(n=r;n--;)if(e[n][0]==="exit"&&e[n][1].type==="attentionSequence"&&e[n][1]._open&&t.sliceSerialize(e[n][1]).charCodeAt(0)===t.sliceSerialize(e[r][1]).charCodeAt(0)){if((e[n][1]._close||e[r][1]._open)&&(e[r][1].end.offset-e[r][1].start.offset)%3&&!((e[n][1].end.offset-e[n][1].start.offset+e[r][1].end.offset-e[r][1].start.offset)%3))continue;l=e[n][1].end.offset-e[n][1].start.offset>1&&e[r][1].end.offset-e[r][1].start.offset>1?2:1;const c=m({},e[n][1].end),f=m({},e[r][1].start);sl(c,-l),sl(f,l),s={type:l>1?"strongSequence":"emphasisSequence",start:c,end:m({},e[n][1].end)},o={type:l>1?"strongSequence":"emphasisSequence",start:m({},e[r][1].start),end:f},a={type:l>1?"strongText":"emphasisText",start:m({},e[n][1].end),end:m({},e[r][1].start)},i={type:l>1?"strong":"emphasis",start:m({},s.start),end:m({},o.end)},e[n][1].end=m({},s.start),e[r][1].start=m({},o.end),u=[],e[n][1].end.offset-e[n][1].start.offset&&(u=Je(u,[["enter",e[n][1],t],["exit",e[n][1],t]])),u=Je(u,[["enter",i,t],["enter",s,t],["exit",s,t],["enter",a,t]]),u=Je(u,cn(t.parser.constructs.insideSpan.null,e.slice(n+1,r),t)),u=Je(u,[["exit",a,t],["enter",o,t],["exit",o,t],["exit",i,t]]),e[r][1].end.offset-e[r][1].start.offset?(d=2,u=Je(u,[["enter",e[r][1],t],["exit",e[r][1],t]])):d=0,qe(e,n-1,r-n+3,u),r=n+u.length-d-2;break}}for(r=-1;++r<e.length;)e[r][1].type==="attentionSequence"&&(e[r][1].type="data");return e}function Cm(e,t){const r=this.parser.constructs.attentionMarkers.null,n=this.previous,i=Qt(n);let a;return s;function s(l){return a=l,e.enter("attentionSequence"),o(l)}function o(l){if(l===a)return e.consume(l),o;const u=e.exit("attentionSequence"),d=Qt(l),c=!d||d===2&&i||r.includes(l),f=!i||i===2&&d||r.includes(n);return u._open=!!(a===42?c:c&&(i||!f)),u._close=!!(a===42?f:f&&(d||!c)),t(l)}}function sl(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const Im={name:"autolink",tokenize:Em};function Em(e,t,r){let n=0;return i;function i(h){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),a}function a(h){return Fe(h)?(e.consume(h),s):h===64?r(h):u(h)}function s(h){return h===43||h===45||h===46||Ne(h)?(n=1,o(h)):u(h)}function o(h){return h===58?(e.consume(h),n=0,l):(h===43||h===45||h===46||Ne(h))&&n++<32?(e.consume(h),o):(n=0,u(h))}function l(h){return h===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):h===null||h===32||h===60||ln(h)?r(h):(e.consume(h),l)}function u(h){return h===64?(e.consume(h),d):ym(h)?(e.consume(h),u):r(h)}function d(h){return Ne(h)?c(h):r(h)}function c(h){return h===46?(e.consume(h),n=0,d):h===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):f(h)}function f(h){if((h===45||Ne(h))&&n++<63){const g=h===45?f:c;return e.consume(h),g}return r(h)}}const vr={partial:!0,tokenize:Am};function Am(e,t,r){return n;function n(a){return te(a)?ae(e,i,"linePrefix")(a):i(a)}function i(a){return a===null||W(a)?t(a):r(a)}}const ol={continuation:{tokenize:Pm},exit:Nm,name:"blockQuote",tokenize:Mm};function Mm(e,t,r){const n=this;return i;function i(s){if(s===62){const o=n.containerState;return o.open||(e.enter("blockQuote",{_container:!0}),o.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(s),e.exit("blockQuoteMarker"),a}return r(s)}function a(s){return te(s)?(e.enter("blockQuotePrefixWhitespace"),e.consume(s),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(s))}}function Pm(e,t,r){const n=this;return i;function i(s){return te(s)?ae(e,a,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(s):a(s)}function a(s){return e.attempt(ol,t,r)(s)}}function Nm(e){e.exit("blockQuote")}const ll={name:"characterEscape",tokenize:Lm};function Lm(e,t,r){return n;function n(a){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(a),e.exit("escapeMarker"),i}function i(a){return wm(a)?(e.enter("characterEscapeValue"),e.consume(a),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):r(a)}}const ul={name:"characterReference",tokenize:Dm};function Dm(e,t,r){const n=this;let i=0,a,s;return o;function o(c){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(c),e.exit("characterReferenceMarker"),l}function l(c){return c===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(c),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),a=31,s=Ne,d(c))}function u(c){return c===88||c===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(c),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),a=6,s=bm,d):(e.enter("characterReferenceValue"),a=7,s=Ti,d(c))}function d(c){if(c===59&&i){const f=e.exit("characterReferenceValue");return s===Ne&&!_i(n.sliceSerialize(f))?r(c):(e.enter("characterReferenceMarker"),e.consume(c),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return s(c)&&i++<a?(e.consume(c),d):r(c)}}const cl={partial:!0,tokenize:Fm},dl={concrete:!0,name:"codeFenced",tokenize:Om};function Om(e,t,r){const n=this,i={partial:!0,tokenize:z};let a=0,s=0,o;return l;function l(C){return u(C)}function u(C){const U=n.events[n.events.length-1];return a=U&&U[1].type==="linePrefix"?U[2].sliceSerialize(U[1],!0).length:0,o=C,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),d(C)}function d(C){return C===o?(s++,e.consume(C),d):s<3?r(C):(e.exit("codeFencedFenceSequence"),te(C)?ae(e,c,"whitespace")(C):c(C))}function c(C){return C===null||W(C)?(e.exit("codeFencedFence"),n.interrupt?t(C):e.check(cl,x,O)(C)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(C))}function f(C){return C===null||W(C)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),c(C)):te(C)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),ae(e,h,"whitespace")(C)):C===96&&C===o?r(C):(e.consume(C),f)}function h(C){return C===null||W(C)?c(C):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(C))}function g(C){return C===null||W(C)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),c(C)):C===96&&C===o?r(C):(e.consume(C),g)}function x(C){return e.attempt(i,O,b)(C)}function b(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),w}function w(C){return a>0&&te(C)?ae(e,E,"linePrefix",a+1)(C):E(C)}function E(C){return C===null||W(C)?e.check(cl,x,O)(C):(e.enter("codeFlowValue"),_(C))}function _(C){return C===null||W(C)?(e.exit("codeFlowValue"),E(C)):(e.consume(C),_)}function O(C){return e.exit("codeFenced"),t(C)}function z(C,U,V){let R=0;return S;function S(P){return C.enter("lineEnding"),C.consume(P),C.exit("lineEnding"),D}function D(P){return C.enter("codeFencedFence"),te(P)?ae(C,N,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):N(P)}function N(P){return P===o?(C.enter("codeFencedFenceSequence"),K(P)):V(P)}function K(P){return P===o?(R++,C.consume(P),K):R>=s?(C.exit("codeFencedFenceSequence"),te(P)?ae(C,B,"whitespace")(P):B(P)):V(P)}function B(P){return P===null||W(P)?(C.exit("codeFencedFence"),U(P)):V(P)}}}function Fm(e,t,r){const n=this;return i;function i(s){return s===null?r(s):(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),a)}function a(s){return n.parser.lazy[n.now().line]?r(s):t(s)}}const Ii={name:"codeIndented",tokenize:Bm},zm={partial:!0,tokenize:Rm};function Bm(e,t,r){const n=this;return i;function i(u){return e.enter("codeIndented"),ae(e,a,"linePrefix",5)(u)}function a(u){const d=n.events[n.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?s(u):r(u)}function s(u){return u===null?l(u):W(u)?e.attempt(zm,s,l)(u):(e.enter("codeFlowValue"),o(u))}function o(u){return u===null||W(u)?(e.exit("codeFlowValue"),s(u)):(e.consume(u),o)}function l(u){return e.exit("codeIndented"),t(u)}}function Rm(e,t,r){const n=this;return i;function i(s){return n.parser.lazy[n.now().line]?r(s):W(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),i):ae(e,a,"linePrefix",5)(s)}function a(s){const o=n.events[n.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(s):W(s)?i(s):r(s)}}const jm={name:"codeText",previous:Um,resolve:$m,tokenize:Hm};function $m(e){let t=e.length-4,r=3,n,i;if((e[r][1].type==="lineEnding"||e[r][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(n=r;++n<t;)if(e[n][1].type==="codeTextData"){e[r][1].type="codeTextPadding",e[t][1].type="codeTextPadding",r+=2,t-=2;break}}for(n=r-1,t++;++n<=t;)i===void 0?n!==t&&e[n][1].type!=="lineEnding"&&(i=n):(n===t||e[n][1].type==="lineEnding")&&(e[i][1].type="codeTextData",n!==i+2&&(e[i][1].end=e[n-1][1].end,e.splice(i+2,n-i-2),t-=n-i-2,n=i+2),i=void 0);return e}function Um(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Hm(e,t,r){let n=0,i,a;return s;function s(c){return e.enter("codeText"),e.enter("codeTextSequence"),o(c)}function o(c){return c===96?(e.consume(c),n++,o):(e.exit("codeTextSequence"),l(c))}function l(c){return c===null?r(c):c===32?(e.enter("space"),e.consume(c),e.exit("space"),l):c===96?(a=e.enter("codeTextSequence"),i=0,d(c)):W(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),l):(e.enter("codeTextData"),u(c))}function u(c){return c===null||c===32||c===96||W(c)?(e.exit("codeTextData"),l(c)):(e.consume(c),u)}function d(c){return c===96?(e.consume(c),i++,d):i===n?(e.exit("codeTextSequence"),e.exit("codeText"),t(c)):(a.type="codeTextData",u(c))}}class qm{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,r){const n=r==null?Number.POSITIVE_INFINITY:r;return n<this.left.length?this.left.slice(t,n):t>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(t,r,n){const i=r||0;this.setCursor(Math.trunc(t));const a=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return n&&kr(this.left,n),a.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),kr(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),kr(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const r=this.left.splice(t,Number.POSITIVE_INFINITY);kr(this.right,r.reverse())}else{const r=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);kr(this.left,r.reverse())}}}function kr(e,t){let r=0;if(t.length<1e4)e.push(...t);else for(;r<t.length;)e.push(...t.slice(r,r+1e4)),r+=1e4}function hl(e){const t={};let r=-1,n,i,a,s,o,l,u;const d=new qm(e);for(;++r<d.length;){for(;r in t;)r=t[r];if(n=d.get(r),r&&n[1].type==="chunkFlow"&&d.get(r-1)[1].type==="listItemPrefix"&&(l=n[1]._tokenizer.events,a=0,a<l.length&&l[a][1].type==="lineEndingBlank"&&(a+=2),a<l.length&&l[a][1].type==="content"))for(;++a<l.length&&l[a][1].type!=="content";)l[a][1].type==="chunkText"&&(l[a][1]._isInFirstContentOfListItem=!0,a++);if(n[0]==="enter")n[1].contentType&&(Object.assign(t,Vm(d,r)),r=t[r],u=!0);else if(n[1]._container){for(a=r,i=void 0;a--;)if(s=d.get(a),s[1].type==="lineEnding"||s[1].type==="lineEndingBlank")s[0]==="enter"&&(i&&(d.get(i)[1].type="lineEndingBlank"),s[1].type="lineEnding",i=a);else if(!(s[1].type==="linePrefix"||s[1].type==="listItemIndent"))break;i&&(n[1].end=m({},d.get(i)[1].start),o=d.slice(i,r),o.unshift(n),d.splice(i,r-i+1,o))}}return qe(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!u}function Vm(e,t){const r=e.get(t)[1],n=e.get(t)[2];let i=t-1;const a=[];let s=r._tokenizer;s||(s=n.parser[r.contentType](r.start),r._contentTypeTextTrailing&&(s._contentTypeTextTrailing=!0));const o=s.events,l=[],u={};let d,c,f=-1,h=r,g=0,x=0;const b=[x];for(;h;){for(;e.get(++i)[1]!==h;);a.push(i),h._tokenizer||(d=n.sliceStream(h),h.next||d.push(null),c&&s.defineSkip(h.start),h._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=!0),s.write(d),h._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=void 0)),c=h,h=h.next}for(h=r;++f<o.length;)o[f][0]==="exit"&&o[f-1][0]==="enter"&&o[f][1].type===o[f-1][1].type&&o[f][1].start.line!==o[f][1].end.line&&(x=f+1,b.push(x),h._tokenizer=void 0,h.previous=void 0,h=h.next);for(s.events=[],h?(h._tokenizer=void 0,h.previous=void 0):b.pop(),f=b.length;f--;){const w=o.slice(b[f],b[f+1]),E=a.pop();l.push([E,E+w.length-1]),e.splice(E,2,w)}for(l.reverse(),f=-1;++f<l.length;)u[g+l[f][0]]=g+l[f][1],g+=l[f][1]-l[f][0]-1;return u}const Wm={resolve:Km,tokenize:Ym},Jm={partial:!0,tokenize:Gm};function Km(e){return hl(e),e}function Ym(e,t){let r;return n;function n(o){return e.enter("content"),r=e.enter("chunkContent",{contentType:"content"}),i(o)}function i(o){return o===null?a(o):W(o)?e.check(Jm,s,a)(o):(e.consume(o),i)}function a(o){return e.exit("chunkContent"),e.exit("content"),t(o)}function s(o){return e.consume(o),e.exit("chunkContent"),r.next=e.enter("chunkContent",{contentType:"content",previous:r}),r=r.next,i}}function Gm(e,t,r){const n=this;return i;function i(s){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),ae(e,a,"linePrefix")}function a(s){if(s===null||W(s))return r(s);const o=n.events[n.events.length-1];return!n.parser.constructs.disable.null.includes("codeIndented")&&o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(s):e.interrupt(n.parser.constructs.flow,r,t)(s)}}function fl(e,t,r,n,i,a,s,o,l){const u=l||Number.POSITIVE_INFINITY;let d=0;return c;function c(w){return w===60?(e.enter(n),e.enter(i),e.enter(a),e.consume(w),e.exit(a),f):w===null||w===32||w===41||ln(w)?r(w):(e.enter(n),e.enter(s),e.enter(o),e.enter("chunkString",{contentType:"string"}),x(w))}function f(w){return w===62?(e.enter(a),e.consume(w),e.exit(a),e.exit(i),e.exit(n),t):(e.enter(o),e.enter("chunkString",{contentType:"string"}),h(w))}function h(w){return w===62?(e.exit("chunkString"),e.exit(o),f(w)):w===null||w===60||W(w)?r(w):(e.consume(w),w===92?g:h)}function g(w){return w===60||w===62||w===92?(e.consume(w),h):h(w)}function x(w){return!d&&(w===null||w===41||de(w))?(e.exit("chunkString"),e.exit(o),e.exit(s),e.exit(n),t(w)):d<u&&w===40?(e.consume(w),d++,x):w===41?(e.consume(w),d--,x):w===null||w===32||w===40||ln(w)?r(w):(e.consume(w),w===92?b:x)}function b(w){return w===40||w===41||w===92?(e.consume(w),x):x(w)}}function pl(e,t,r,n,i,a){const s=this;let o=0,l;return u;function u(h){return e.enter(n),e.enter(i),e.consume(h),e.exit(i),e.enter(a),d}function d(h){return o>999||h===null||h===91||h===93&&!l||h===94&&!o&&"_hiddenFootnoteSupport"in s.parser.constructs?r(h):h===93?(e.exit(a),e.enter(i),e.consume(h),e.exit(i),e.exit(n),t):W(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),c(h))}function c(h){return h===null||h===91||h===93||W(h)||o++>999?(e.exit("chunkString"),d(h)):(e.consume(h),l||(l=!te(h)),h===92?f:c)}function f(h){return h===91||h===92||h===93?(e.consume(h),o++,c):c(h)}}function ml(e,t,r,n,i,a){let s;return o;function o(f){return f===34||f===39||f===40?(e.enter(n),e.enter(i),e.consume(f),e.exit(i),s=f===40?41:f,l):r(f)}function l(f){return f===s?(e.enter(i),e.consume(f),e.exit(i),e.exit(n),t):(e.enter(a),u(f))}function u(f){return f===s?(e.exit(a),l(s)):f===null?r(f):W(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),ae(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(f))}function d(f){return f===s||f===null||W(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?c:d)}function c(f){return f===s||f===92?(e.consume(f),d):d(f)}}function Sr(e,t){let r;return n;function n(i){return W(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),r=!0,n):te(i)?ae(e,n,r?"linePrefix":"lineSuffix")(i):t(i)}}const Xm={name:"definition",tokenize:Zm},Qm={partial:!0,tokenize:eg};function Zm(e,t,r){const n=this;let i;return a;function a(h){return e.enter("definition"),s(h)}function s(h){return pl.call(n,e,o,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(h)}function o(h){return i=et(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)),h===58?(e.enter("definitionMarker"),e.consume(h),e.exit("definitionMarker"),l):r(h)}function l(h){return de(h)?Sr(e,u)(h):u(h)}function u(h){return fl(e,d,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(h)}function d(h){return e.attempt(Qm,c,c)(h)}function c(h){return te(h)?ae(e,f,"whitespace")(h):f(h)}function f(h){return h===null||W(h)?(e.exit("definition"),n.parser.defined.push(i),t(h)):r(h)}}function eg(e,t,r){return n;function n(o){return de(o)?Sr(e,i)(o):r(o)}function i(o){return ml(e,a,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function a(o){return te(o)?ae(e,s,"whitespace")(o):s(o)}function s(o){return o===null||W(o)?t(o):r(o)}}const tg={name:"hardBreakEscape",tokenize:rg};function rg(e,t,r){return n;function n(a){return e.enter("hardBreakEscape"),e.consume(a),i}function i(a){return W(a)?(e.exit("hardBreakEscape"),t(a)):r(a)}}const ng={name:"headingAtx",resolve:ig,tokenize:ag};function ig(e,t){let r=e.length-2,n=3,i,a;return e[n][1].type==="whitespace"&&(n+=2),r-2>n&&e[r][1].type==="whitespace"&&(r-=2),e[r][1].type==="atxHeadingSequence"&&(n===r-1||r-4>n&&e[r-2][1].type==="whitespace")&&(r-=n+1===r?2:4),r>n&&(i={type:"atxHeadingText",start:e[n][1].start,end:e[r][1].end},a={type:"chunkText",start:e[n][1].start,end:e[r][1].end,contentType:"text"},qe(e,n,r-n+1,[["enter",i,t],["enter",a,t],["exit",a,t],["exit",i,t]])),e}function ag(e,t,r){let n=0;return i;function i(d){return e.enter("atxHeading"),a(d)}function a(d){return e.enter("atxHeadingSequence"),s(d)}function s(d){return d===35&&n++<6?(e.consume(d),s):d===null||de(d)?(e.exit("atxHeadingSequence"),o(d)):r(d)}function o(d){return d===35?(e.enter("atxHeadingSequence"),l(d)):d===null||W(d)?(e.exit("atxHeading"),t(d)):te(d)?ae(e,o,"whitespace")(d):(e.enter("atxHeadingText"),u(d))}function l(d){return d===35?(e.consume(d),l):(e.exit("atxHeadingSequence"),o(d))}function u(d){return d===null||d===35||de(d)?(e.exit("atxHeadingText"),o(d)):(e.consume(d),u)}}const sg=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],gl=["pre","script","style","textarea"],og={concrete:!0,name:"htmlFlow",resolveTo:cg,tokenize:dg},lg={partial:!0,tokenize:fg},ug={partial:!0,tokenize:hg};function cg(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function dg(e,t,r){const n=this;let i,a,s,o,l;return u;function u(k){return d(k)}function d(k){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(k),c}function c(k){return k===33?(e.consume(k),f):k===47?(e.consume(k),a=!0,x):k===63?(e.consume(k),i=3,n.interrupt?t:v):Fe(k)?(e.consume(k),s=String.fromCharCode(k),b):r(k)}function f(k){return k===45?(e.consume(k),i=2,h):k===91?(e.consume(k),i=5,o=0,g):Fe(k)?(e.consume(k),i=4,n.interrupt?t:v):r(k)}function h(k){return k===45?(e.consume(k),n.interrupt?t:v):r(k)}function g(k){const Se="CDATA[";return k===Se.charCodeAt(o++)?(e.consume(k),o===Se.length?n.interrupt?t:N:g):r(k)}function x(k){return Fe(k)?(e.consume(k),s=String.fromCharCode(k),b):r(k)}function b(k){if(k===null||k===47||k===62||de(k)){const Se=k===47,Ye=s.toLowerCase();return!Se&&!a&&gl.includes(Ye)?(i=1,n.interrupt?t(k):N(k)):sg.includes(s.toLowerCase())?(i=6,Se?(e.consume(k),w):n.interrupt?t(k):N(k)):(i=7,n.interrupt&&!n.parser.lazy[n.now().line]?r(k):a?E(k):_(k))}return k===45||Ne(k)?(e.consume(k),s+=String.fromCharCode(k),b):r(k)}function w(k){return k===62?(e.consume(k),n.interrupt?t:N):r(k)}function E(k){return te(k)?(e.consume(k),E):S(k)}function _(k){return k===47?(e.consume(k),S):k===58||k===95||Fe(k)?(e.consume(k),O):te(k)?(e.consume(k),_):S(k)}function O(k){return k===45||k===46||k===58||k===95||Ne(k)?(e.consume(k),O):z(k)}function z(k){return k===61?(e.consume(k),C):te(k)?(e.consume(k),z):_(k)}function C(k){return k===null||k===60||k===61||k===62||k===96?r(k):k===34||k===39?(e.consume(k),l=k,U):te(k)?(e.consume(k),C):V(k)}function U(k){return k===l?(e.consume(k),l=null,R):k===null||W(k)?r(k):(e.consume(k),U)}function V(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||de(k)?z(k):(e.consume(k),V)}function R(k){return k===47||k===62||te(k)?_(k):r(k)}function S(k){return k===62?(e.consume(k),D):r(k)}function D(k){return k===null||W(k)?N(k):te(k)?(e.consume(k),D):r(k)}function N(k){return k===45&&i===2?(e.consume(k),q):k===60&&i===1?(e.consume(k),J):k===62&&i===4?(e.consume(k),Y):k===63&&i===3?(e.consume(k),v):k===93&&i===5?(e.consume(k),se):W(k)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(lg,xe,K)(k)):k===null||W(k)?(e.exit("htmlFlowData"),K(k)):(e.consume(k),N)}function K(k){return e.check(ug,B,xe)(k)}function B(k){return e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),P}function P(k){return k===null||W(k)?K(k):(e.enter("htmlFlowData"),N(k))}function q(k){return k===45?(e.consume(k),v):N(k)}function J(k){return k===47?(e.consume(k),s="",ue):N(k)}function ue(k){if(k===62){const Se=s.toLowerCase();return gl.includes(Se)?(e.consume(k),Y):N(k)}return Fe(k)&&s.length<8?(e.consume(k),s+=String.fromCharCode(k),ue):N(k)}function se(k){return k===93?(e.consume(k),v):N(k)}function v(k){return k===62?(e.consume(k),Y):k===45&&i===2?(e.consume(k),v):N(k)}function Y(k){return k===null||W(k)?(e.exit("htmlFlowData"),xe(k)):(e.consume(k),Y)}function xe(k){return e.exit("htmlFlow"),t(k)}}function hg(e,t,r){const n=this;return i;function i(s){return W(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),a):r(s)}function a(s){return n.parser.lazy[n.now().line]?r(s):t(s)}}function fg(e,t,r){return n;function n(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(vr,t,r)}}const pg={name:"htmlText",tokenize:mg};function mg(e,t,r){const n=this;let i,a,s;return o;function o(v){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(v),l}function l(v){return v===33?(e.consume(v),u):v===47?(e.consume(v),z):v===63?(e.consume(v),_):Fe(v)?(e.consume(v),V):r(v)}function u(v){return v===45?(e.consume(v),d):v===91?(e.consume(v),a=0,g):Fe(v)?(e.consume(v),E):r(v)}function d(v){return v===45?(e.consume(v),h):r(v)}function c(v){return v===null?r(v):v===45?(e.consume(v),f):W(v)?(s=c,J(v)):(e.consume(v),c)}function f(v){return v===45?(e.consume(v),h):c(v)}function h(v){return v===62?q(v):v===45?f(v):c(v)}function g(v){const Y="CDATA[";return v===Y.charCodeAt(a++)?(e.consume(v),a===Y.length?x:g):r(v)}function x(v){return v===null?r(v):v===93?(e.consume(v),b):W(v)?(s=x,J(v)):(e.consume(v),x)}function b(v){return v===93?(e.consume(v),w):x(v)}function w(v){return v===62?q(v):v===93?(e.consume(v),w):x(v)}function E(v){return v===null||v===62?q(v):W(v)?(s=E,J(v)):(e.consume(v),E)}function _(v){return v===null?r(v):v===63?(e.consume(v),O):W(v)?(s=_,J(v)):(e.consume(v),_)}function O(v){return v===62?q(v):_(v)}function z(v){return Fe(v)?(e.consume(v),C):r(v)}function C(v){return v===45||Ne(v)?(e.consume(v),C):U(v)}function U(v){return W(v)?(s=U,J(v)):te(v)?(e.consume(v),U):q(v)}function V(v){return v===45||Ne(v)?(e.consume(v),V):v===47||v===62||de(v)?R(v):r(v)}function R(v){return v===47?(e.consume(v),q):v===58||v===95||Fe(v)?(e.consume(v),S):W(v)?(s=R,J(v)):te(v)?(e.consume(v),R):q(v)}function S(v){return v===45||v===46||v===58||v===95||Ne(v)?(e.consume(v),S):D(v)}function D(v){return v===61?(e.consume(v),N):W(v)?(s=D,J(v)):te(v)?(e.consume(v),D):R(v)}function N(v){return v===null||v===60||v===61||v===62||v===96?r(v):v===34||v===39?(e.consume(v),i=v,K):W(v)?(s=N,J(v)):te(v)?(e.consume(v),N):(e.consume(v),B)}function K(v){return v===i?(e.consume(v),i=void 0,P):v===null?r(v):W(v)?(s=K,J(v)):(e.consume(v),K)}function B(v){return v===null||v===34||v===39||v===60||v===61||v===96?r(v):v===47||v===62||de(v)?R(v):(e.consume(v),B)}function P(v){return v===47||v===62||de(v)?R(v):r(v)}function q(v){return v===62?(e.consume(v),e.exit("htmlTextData"),e.exit("htmlText"),t):r(v)}function J(v){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),ue}function ue(v){return te(v)?ae(e,se,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(v):se(v)}function se(v){return e.enter("htmlTextData"),s(v)}}const Ei={name:"labelEnd",resolveAll:wg,resolveTo:xg,tokenize:vg},gg={tokenize:kg},yg={tokenize:Sg},bg={tokenize:_g};function wg(e){let t=-1;const r=[];for(;++t<e.length;){const n=e[t][1];if(r.push(e[t]),n.type==="labelImage"||n.type==="labelLink"||n.type==="labelEnd"){const i=n.type==="labelImage"?4:2;n.type="data",t+=i}}return e.length!==r.length&&qe(e,0,e.length,r),e}function xg(e,t){let r=e.length,n=0,i,a,s,o;for(;r--;)if(i=e[r][1],a){if(i.type==="link"||i.type==="labelLink"&&i._inactive)break;e[r][0]==="enter"&&i.type==="labelLink"&&(i._inactive=!0)}else if(s){if(e[r][0]==="enter"&&(i.type==="labelImage"||i.type==="labelLink")&&!i._balanced&&(a=r,i.type!=="labelLink")){n=2;break}}else i.type==="labelEnd"&&(s=r);const l={type:e[a][1].type==="labelLink"?"link":"image",start:m({},e[a][1].start),end:m({},e[e.length-1][1].end)},u={type:"label",start:m({},e[a][1].start),end:m({},e[s][1].end)},d={type:"labelText",start:m({},e[a+n+2][1].end),end:m({},e[s-2][1].start)};return o=[["enter",l,t],["enter",u,t]],o=Je(o,e.slice(a+1,a+n+3)),o=Je(o,[["enter",d,t]]),o=Je(o,cn(t.parser.constructs.insideSpan.null,e.slice(a+n+4,s-3),t)),o=Je(o,[["exit",d,t],e[s-2],e[s-1],["exit",u,t]]),o=Je(o,e.slice(s+1)),o=Je(o,[["exit",l,t]]),qe(e,a,e.length,o),e}function vg(e,t,r){const n=this;let i=n.events.length,a,s;for(;i--;)if((n.events[i][1].type==="labelImage"||n.events[i][1].type==="labelLink")&&!n.events[i][1]._balanced){a=n.events[i][1];break}return o;function o(f){return a?a._inactive?c(f):(s=n.parser.defined.includes(et(n.sliceSerialize({start:a.end,end:n.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelEnd"),l):r(f)}function l(f){return f===40?e.attempt(gg,d,s?d:c)(f):f===91?e.attempt(yg,d,s?u:c)(f):s?d(f):c(f)}function u(f){return e.attempt(bg,d,c)(f)}function d(f){return t(f)}function c(f){return a._balanced=!0,r(f)}}function kg(e,t,r){return n;function n(c){return e.enter("resource"),e.enter("resourceMarker"),e.consume(c),e.exit("resourceMarker"),i}function i(c){return de(c)?Sr(e,a)(c):a(c)}function a(c){return c===41?d(c):fl(e,s,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(c)}function s(c){return de(c)?Sr(e,l)(c):d(c)}function o(c){return r(c)}function l(c){return c===34||c===39||c===40?ml(e,u,r,"resourceTitle","resourceTitleMarker","resourceTitleString")(c):d(c)}function u(c){return de(c)?Sr(e,d)(c):d(c)}function d(c){return c===41?(e.enter("resourceMarker"),e.consume(c),e.exit("resourceMarker"),e.exit("resource"),t):r(c)}}function Sg(e,t,r){const n=this;return i;function i(o){return pl.call(n,e,a,s,"reference","referenceMarker","referenceString")(o)}function a(o){return n.parser.defined.includes(et(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)))?t(o):r(o)}function s(o){return r(o)}}function _g(e,t,r){return n;function n(a){return e.enter("reference"),e.enter("referenceMarker"),e.consume(a),e.exit("referenceMarker"),i}function i(a){return a===93?(e.enter("referenceMarker"),e.consume(a),e.exit("referenceMarker"),e.exit("reference"),t):r(a)}}const Tg={name:"labelStartImage",resolveAll:Ei.resolveAll,tokenize:Cg};function Cg(e,t,r){const n=this;return i;function i(o){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(o),e.exit("labelImageMarker"),a}function a(o){return o===91?(e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelImage"),s):r(o)}function s(o){return o===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(o):t(o)}}const Ig={name:"labelStartLink",resolveAll:Ei.resolveAll,tokenize:Eg};function Eg(e,t,r){const n=this;return i;function i(s){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(s),e.exit("labelMarker"),e.exit("labelLink"),a}function a(s){return s===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(s):t(s)}}const Ai={name:"lineEnding",tokenize:Ag};function Ag(e,t){return r;function r(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),ae(e,t,"linePrefix")}}const dn={name:"thematicBreak",tokenize:Mg};function Mg(e,t,r){let n=0,i;return a;function a(u){return e.enter("thematicBreak"),s(u)}function s(u){return i=u,o(u)}function o(u){return u===i?(e.enter("thematicBreakSequence"),l(u)):n>=3&&(u===null||W(u))?(e.exit("thematicBreak"),t(u)):r(u)}function l(u){return u===i?(e.consume(u),n++,l):(e.exit("thematicBreakSequence"),te(u)?ae(e,o,"whitespace")(u):o(u))}}const je={continuation:{tokenize:Dg},exit:Fg,name:"list",tokenize:Lg},Pg={partial:!0,tokenize:zg},Ng={partial:!0,tokenize:Og};function Lg(e,t,r){const n=this,i=n.events[n.events.length-1];let a=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,s=0;return o;function o(h){const g=n.containerState.type||(h===42||h===43||h===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!n.containerState.marker||h===n.containerState.marker:Ti(h)){if(n.containerState.type||(n.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),h===42||h===45?e.check(dn,r,u)(h):u(h);if(!n.interrupt||h===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),l(h)}return r(h)}function l(h){return Ti(h)&&++s<10?(e.consume(h),l):(!n.interrupt||s<2)&&(n.containerState.marker?h===n.containerState.marker:h===41||h===46)?(e.exit("listItemValue"),u(h)):r(h)}function u(h){return e.enter("listItemMarker"),e.consume(h),e.exit("listItemMarker"),n.containerState.marker=n.containerState.marker||h,e.check(vr,n.interrupt?r:d,e.attempt(Pg,f,c))}function d(h){return n.containerState.initialBlankLine=!0,a++,f(h)}function c(h){return te(h)?(e.enter("listItemPrefixWhitespace"),e.consume(h),e.exit("listItemPrefixWhitespace"),f):r(h)}function f(h){return n.containerState.size=a+n.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(h)}}function Dg(e,t,r){const n=this;return n.containerState._closeFlow=void 0,e.check(vr,i,a);function i(o){return n.containerState.furtherBlankLines=n.containerState.furtherBlankLines||n.containerState.initialBlankLine,ae(e,t,"listItemIndent",n.containerState.size+1)(o)}function a(o){return n.containerState.furtherBlankLines||!te(o)?(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,s(o)):(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,e.attempt(Ng,t,s)(o))}function s(o){return n.containerState._closeFlow=!0,n.interrupt=void 0,ae(e,e.attempt(je,t,r),"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function Og(e,t,r){const n=this;return ae(e,i,"listItemIndent",n.containerState.size+1);function i(a){const s=n.events[n.events.length-1];return s&&s[1].type==="listItemIndent"&&s[2].sliceSerialize(s[1],!0).length===n.containerState.size?t(a):r(a)}}function Fg(e){e.exit(this.containerState.type)}function zg(e,t,r){const n=this;return ae(e,i,"listItemPrefixWhitespace",n.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(a){const s=n.events[n.events.length-1];return!te(a)&&s&&s[1].type==="listItemPrefixWhitespace"?t(a):r(a)}}const yl={name:"setextUnderline",resolveTo:Bg,tokenize:Rg};function Bg(e,t){let r=e.length,n,i,a;for(;r--;)if(e[r][0]==="enter"){if(e[r][1].type==="content"){n=r;break}e[r][1].type==="paragraph"&&(i=r)}else e[r][1].type==="content"&&e.splice(r,1),!a&&e[r][1].type==="definition"&&(a=r);const s={type:"setextHeading",start:m({},e[n][1].start),end:m({},e[e.length-1][1].end)};return e[i][1].type="setextHeadingText",a?(e.splice(i,0,["enter",s,t]),e.splice(a+1,0,["exit",e[n][1],t]),e[n][1].end=m({},e[a][1].end)):e[n][1]=s,e.push(["exit",s,t]),e}function Rg(e,t,r){const n=this;let i;return a;function a(u){let d=n.events.length,c;for(;d--;)if(n.events[d][1].type!=="lineEnding"&&n.events[d][1].type!=="linePrefix"&&n.events[d][1].type!=="content"){c=n.events[d][1].type==="paragraph";break}return!n.parser.lazy[n.now().line]&&(n.interrupt||c)?(e.enter("setextHeadingLine"),i=u,s(u)):r(u)}function s(u){return e.enter("setextHeadingLineSequence"),o(u)}function o(u){return u===i?(e.consume(u),o):(e.exit("setextHeadingLineSequence"),te(u)?ae(e,l,"lineSuffix")(u):l(u))}function l(u){return u===null||W(u)?(e.exit("setextHeadingLine"),t(u)):r(u)}}const jg={tokenize:$g};function $g(e){const t=this,r=e.attempt(vr,n,e.attempt(this.parser.constructs.flowInitial,i,ae(e,e.attempt(this.parser.constructs.flow,i,e.attempt(Wm,i)),"linePrefix")));return r;function n(a){if(a===null){e.consume(a);return}return e.enter("lineEndingBlank"),e.consume(a),e.exit("lineEndingBlank"),t.currentConstruct=void 0,r}function i(a){if(a===null){e.consume(a);return}return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),t.currentConstruct=void 0,r}}const Ug={resolveAll:wl()},Hg=bl("string"),qg=bl("text");function bl(e){return{resolveAll:wl(e==="text"?Vg:void 0),tokenize:t};function t(r){const n=this,i=this.parser.constructs[e],a=r.attempt(i,s,o);return s;function s(d){return u(d)?a(d):o(d)}function o(d){if(d===null){r.consume(d);return}return r.enter("data"),r.consume(d),l}function l(d){return u(d)?(r.exit("data"),a(d)):(r.consume(d),l)}function u(d){if(d===null)return!0;const c=i[d];let f=-1;if(c)for(;++f<c.length;){const h=c[f];if(!h.previous||h.previous.call(n,n.previous))return!0}return!1}}}function wl(e){return t;function t(r,n){let i=-1,a;for(;++i<=r.length;)a===void 0?r[i]&&r[i][1].type==="data"&&(a=i,i++):(!r[i]||r[i][1].type!=="data")&&(i!==a+2&&(r[a][1].end=r[i-1][1].end,r.splice(a+2,i-a-2),i=a+2),a=void 0);return e?e(r,n):r}}function Vg(e,t){let r=0;for(;++r<=e.length;)if((r===e.length||e[r][1].type==="lineEnding")&&e[r-1][1].type==="data"){const n=e[r-1][1],i=t.sliceStream(n);let a=i.length,s=-1,o=0,l;for(;a--;){const u=i[a];if(typeof u=="string"){for(s=u.length;u.charCodeAt(s-1)===32;)o++,s--;if(s)break;s=-1}else if(u===-2)l=!0,o++;else if(u!==-1){a++;break}}if(t._contentTypeTextTrailing&&r===e.length&&(o=0),o){const u={type:r===e.length||l||o<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:a?s:n.start._bufferIndex+s,_index:n.start._index+a,line:n.end.line,column:n.end.column-o,offset:n.end.offset-o},end:m({},n.end)};n.end=m({},u.start),n.start.offset===n.end.offset?Object.assign(n,u):(e.splice(r,0,["enter",u,t],["exit",u,t]),r+=2)}r++}return e}const Wg=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:{null:[42,95]},contentInitial:{91:Xm},disable:{null:[]},document:{42:je,43:je,45:je,48:je,49:je,50:je,51:je,52:je,53:je,54:je,55:je,56:je,57:je,62:ol},flow:{35:ng,42:dn,45:[yl,dn],60:og,61:yl,95:dn,96:dl,126:dl},flowInitial:{[-2]:Ii,[-1]:Ii,32:Ii},insideSpan:{null:[Ci,Ug]},string:{38:ul,92:ll},text:{[-5]:Ai,[-4]:Ai,[-3]:Ai,33:Tg,38:ul,42:Ci,60:[Im,pg],91:Ig,92:[tg,ll],93:Ei,95:Ci,96:jm}},Symbol.toStringTag,{value:"Module"}));function Jg(e,t,r){let n={_bufferIndex:-1,_index:0,line:r&&r.line||1,column:r&&r.column||1,offset:r&&r.offset||0};const i={},a=[];let s=[],o=[];const l={attempt:U(z),check:U(C),consume:E,enter:_,exit:O,interrupt:U(C,{interrupt:!0})},u={code:null,containerState:{},defineSkip:x,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:h,write:c};let d=t.tokenize.call(u,l);return t.resolveAll&&a.push(t),u;function c(D){return s=Je(s,D),b(),s[s.length-1]!==null?[]:(V(t,0),u.events=cn(a,u.events,u),u.events)}function f(D,N){return Yg(h(D),N)}function h(D){return Kg(s,D)}function g(){const{_bufferIndex:D,_index:N,line:K,column:B,offset:P}=n;return{_bufferIndex:D,_index:N,line:K,column:B,offset:P}}function x(D){i[D.line]=D.column,S()}function b(){let D;for(;n._index<s.length;){const N=s[n._index];if(typeof N=="string")for(D=n._index,n._bufferIndex<0&&(n._bufferIndex=0);n._index===D&&n._bufferIndex<N.length;)w(N.charCodeAt(n._bufferIndex));else w(N)}}function w(D){d=d(D)}function E(D){W(D)?(n.line++,n.column=1,n.offset+=D===-3?2:1,S()):D!==-1&&(n.column++,n.offset++),n._bufferIndex<0?n._index++:(n._bufferIndex++,n._bufferIndex===s[n._index].length&&(n._bufferIndex=-1,n._index++)),u.previous=D}function _(D,N){const K=N||{};return K.type=D,K.start=g(),u.events.push(["enter",K,u]),o.push(K),K}function O(D){const N=o.pop();return N.end=g(),u.events.push(["exit",N,u]),N}function z(D,N){V(D,N.from)}function C(D,N){N.restore()}function U(D,N){return K;function K(B,P,q){let J,ue,se,v;return Array.isArray(B)?xe(B):"tokenize"in B?xe([B]):Y(B);function Y(_e){return j;function j(re){const le=re!==null&&_e[re],oe=re!==null&&_e.null,Ee=[...Array.isArray(le)?le:le?[le]:[],...Array.isArray(oe)?oe:oe?[oe]:[]];return xe(Ee)(re)}}function xe(_e){return J=_e,ue=0,_e.length===0?q:k(_e[ue])}function k(_e){return j;function j(re){return v=R(),se=_e,_e.partial||(u.currentConstruct=_e),_e.name&&u.parser.constructs.disable.null.includes(_e.name)?Ye():_e.tokenize.call(N?Object.assign(Object.create(u),N):u,l,Se,Ye)(re)}}function Se(_e){return D(se,v),P}function Ye(_e){return v.restore(),++ue<J.length?k(J[ue]):q}}}function V(D,N){D.resolveAll&&!a.includes(D)&&a.push(D),D.resolve&&qe(u.events,N,u.events.length-N,D.resolve(u.events.slice(N),u)),D.resolveTo&&(u.events=D.resolveTo(u.events,u))}function R(){const D=g(),N=u.previous,K=u.currentConstruct,B=u.events.length,P=Array.from(o);return{from:B,restore:q};function q(){n=D,u.previous=N,u.currentConstruct=K,u.events.length=B,o=P,S()}}function S(){n.line in i&&n.column<2&&(n.column=i[n.line],n.offset+=i[n.line]-1)}}function Kg(e,t){const r=t.start._index,n=t.start._bufferIndex,i=t.end._index,a=t.end._bufferIndex;let s;if(r===i)s=[e[r].slice(n,a)];else{if(s=e.slice(r,i),n>-1){const o=s[0];typeof o=="string"?s[0]=o.slice(n):s.shift()}a>0&&s.push(e[i].slice(0,a))}return s}function Yg(e,t){let r=-1;const n=[];let i;for(;++r<e.length;){const a=e[r];let s;if(typeof a=="string")s=a;else switch(a){case-5:{s="\r";break}case-4:{s=`
|
|
9
|
-
`;break}case-3:{
|
|
10
|
-
`;break}case-2:{s=t?" ":" ";break}case-1:{if(!t&&i)continue;s=" ";break}default:s=String.fromCharCode(a)}i=a===-2,n.push(s)}return n.join("")}function Gg(e){const n={constructs:nl([Wg,...(e||{}).extensions||[]]),content:i(xm),defined:[],document:i(km),flow:i(jg),lazy:{},string:i(Hg),text:i(qg)};return n;function i(a){return s;function s(o){return Jg(n,a,o)}}}function Xg(e){for(;!hl(e););return e}const xl=/[\0\t\n\r]/g;function Qg(){let e=1,t="",r=!0,n;return i;function i(a,s,o){const l=[];let u,d,c,f,h;for(a=t+(typeof a=="string"?a.toString():new TextDecoder(s||void 0).decode(a)),c=0,t="",r&&(a.charCodeAt(0)===65279&&c++,r=void 0);c<a.length;){if(xl.lastIndex=c,u=xl.exec(a),f=u&&u.index!==void 0?u.index:a.length,h=a.charCodeAt(f),!u){t=a.slice(c);break}if(h===10&&c===f&&n)l.push(-3),n=void 0;else switch(n&&(l.push(-5),n=void 0),c<f&&(l.push(a.slice(c,f)),e+=f-c),h){case 0:{l.push(65533),e++;break}case 9:{for(d=Math.ceil(e/4)*4,l.push(-2);e++<d;)l.push(-1);break}case 10:{l.push(-4),e=1;break}default:n=!0,e=1}c=f+1}return o&&(n&&l.push(-5),t&&l.push(t),l.push(null)),l}}const Zg=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function ey(e){return e.replace(Zg,ty)}function ty(e,t,r){if(t)return t;if(r.charCodeAt(0)===35){const i=r.charCodeAt(1),a=i===120||i===88;return il(r.slice(a?2:1),a?16:10)}return _i(r)||e}const vl={}.hasOwnProperty;function ry(e,t,r){return typeof t!="string"&&(r=t,t=void 0),ny(r)(Xg(Gg(r).document().write(Qg()(e,t,!0))))}function ny(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:a(G),autolinkProtocol:R,autolinkEmail:R,atxHeading:a(lt),blockQuote:a(oe),characterEscape:R,characterReference:R,codeFenced:a(Ee),codeFencedFenceInfo:s,codeFencedFenceMeta:s,codeIndented:a(Ee,s),codeText:a(ne,s),codeTextData:R,data:R,codeFlowValue:R,definition:a(we),definitionDestinationString:s,definitionLabelString:s,definitionTitleString:s,emphasis:a(ot),hardBreakEscape:a(ht),hardBreakTrailing:a(ht),htmlFlow:a(St,s),htmlFlowData:R,htmlText:a(St,s),htmlTextData:R,image:a(ft),label:s,link:a(G),listItem:a(me),listItemValue:f,listOrdered:a(be,c),listUnordered:a(be),paragraph:a(Dt),reference:k,referenceString:s,resourceDestinationString:s,resourceTitleString:s,setextHeading:a(lt),strong:a(_n),thematicBreak:a(Tv)},exit:{atxHeading:l(),atxHeadingSequence:z,autolink:l(),autolinkEmail:le,autolinkProtocol:re,blockQuote:l(),characterEscapeValue:S,characterReferenceMarkerHexadecimal:Ye,characterReferenceMarkerNumeric:Ye,characterReferenceValue:_e,characterReference:j,codeFenced:l(b),codeFencedFence:x,codeFencedFenceInfo:h,codeFencedFenceMeta:g,codeFlowValue:S,codeIndented:l(w),codeText:l(P),codeTextData:S,data:S,definition:l(),definitionDestinationString:O,definitionLabelString:E,definitionTitleString:_,emphasis:l(),hardBreakEscape:l(N),hardBreakTrailing:l(N),htmlFlow:l(K),htmlFlowData:S,htmlText:l(B),htmlTextData:S,image:l(J),label:se,labelText:ue,lineEnding:D,link:l(q),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:Se,resourceDestinationString:v,resourceTitleString:Y,resource:xe,setextHeading:l(V),setextHeadingLineSequence:U,setextHeadingText:C,strong:l(),thematicBreak:l()}};kl(t,(e||{}).mdastExtensions||[]);const r={};return n;function n(A){let F={type:"root",children:[]};const X={stack:[F],tokenStack:[],config:t,enter:o,exit:u,buffer:s,resume:d,data:r},ie=[];let he=-1;for(;++he<A.length;)if(A[he][1].type==="listOrdered"||A[he][1].type==="listUnordered")if(A[he][0]==="enter")ie.push(he);else{const rt=ie.pop();he=i(A,rt,he)}for(he=-1;++he<A.length;){const rt=t[A[he][0]];vl.call(rt,A[he][1].type)&&rt[A[he][1].type].call(Object.assign({sliceSerialize:A[he][2].sliceSerialize},X),A[he][1])}if(X.tokenStack.length>0){const rt=X.tokenStack[X.tokenStack.length-1];(rt[1]||Sl).call(X,void 0,rt[0])}for(F.position={start:kt(A.length>0?A[0][1].start:{line:1,column:1,offset:0}),end:kt(A.length>0?A[A.length-2][1].end:{line:1,column:1,offset:0})},he=-1;++he<t.transforms.length;)F=t.transforms[he](F)||F;return F}function i(A,F,X){let ie=F-1,he=-1,rt=!1,Ot,pt,Nr,Lr;for(;++ie<=X;){const Ve=A[ie];switch(Ve[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Ve[0]==="enter"?he++:he--,Lr=void 0;break}case"lineEndingBlank":{Ve[0]==="enter"&&(Ot&&!Lr&&!he&&!Nr&&(Nr=ie),Lr=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Lr=void 0}if(!he&&Ve[0]==="enter"&&Ve[1].type==="listItemPrefix"||he===-1&&Ve[0]==="exit"&&(Ve[1].type==="listUnordered"||Ve[1].type==="listOrdered")){if(Ot){let tr=ie;for(pt=void 0;tr--;){const mt=A[tr];if(mt[1].type==="lineEnding"||mt[1].type==="lineEndingBlank"){if(mt[0]==="exit")continue;pt&&(A[pt][1].type="lineEndingBlank",rt=!0),mt[1].type="lineEnding",pt=tr}else if(!(mt[1].type==="linePrefix"||mt[1].type==="blockQuotePrefix"||mt[1].type==="blockQuotePrefixWhitespace"||mt[1].type==="blockQuoteMarker"||mt[1].type==="listItemIndent"))break}Nr&&(!pt||Nr<pt)&&(Ot._spread=!0),Ot.end=Object.assign({},pt?A[pt][1].start:Ve[1].end),A.splice(pt||ie,0,["exit",Ot,Ve[2]]),ie++,X++}if(Ve[1].type==="listItemPrefix"){const tr={type:"listItem",_spread:!1,start:Object.assign({},Ve[1].start),end:void 0};Ot=tr,A.splice(ie,0,["enter",tr,Ve[2]]),ie++,X++,Nr=void 0,Lr=!0}}}return A[F][1]._spread=rt,X}function a(A,F){return X;function X(ie){o.call(this,A(ie),ie),F&&F.call(this,ie)}}function s(){this.stack.push({type:"fragment",children:[]})}function o(A,F,X){this.stack[this.stack.length-1].children.push(A),this.stack.push(A),this.tokenStack.push([F,X||void 0]),A.position={start:kt(F.start),end:void 0}}function l(A){return F;function F(X){A&&A.call(this,X),u.call(this,X)}}function u(A,F){const X=this.stack.pop(),ie=this.tokenStack.pop();if(ie)ie[0].type!==A.type&&(F?F.call(this,A,ie[0]):(ie[1]||Sl).call(this,A,ie[0]));else throw new Error("Cannot close `"+A.type+"` ("+wr({start:A.start,end:A.end})+"): it’s not open");X.position.end=kt(A.end)}function d(){return Si(this.stack.pop())}function c(){this.data.expectingFirstListItemValue=!0}function f(A){if(this.data.expectingFirstListItemValue){const F=this.stack[this.stack.length-2];F.start=Number.parseInt(this.sliceSerialize(A),10),this.data.expectingFirstListItemValue=void 0}}function h(){const A=this.resume(),F=this.stack[this.stack.length-1];F.lang=A}function g(){const A=this.resume(),F=this.stack[this.stack.length-1];F.meta=A}function x(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function b(){const A=this.resume(),F=this.stack[this.stack.length-1];F.value=A.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function w(){const A=this.resume(),F=this.stack[this.stack.length-1];F.value=A.replace(/(\r?\n|\r)$/g,"")}function E(A){const F=this.resume(),X=this.stack[this.stack.length-1];X.label=F,X.identifier=et(this.sliceSerialize(A)).toLowerCase()}function _(){const A=this.resume(),F=this.stack[this.stack.length-1];F.title=A}function O(){const A=this.resume(),F=this.stack[this.stack.length-1];F.url=A}function z(A){const F=this.stack[this.stack.length-1];if(!F.depth){const X=this.sliceSerialize(A).length;F.depth=X}}function C(){this.data.setextHeadingSlurpLineEnding=!0}function U(A){const F=this.stack[this.stack.length-1];F.depth=this.sliceSerialize(A).codePointAt(0)===61?1:2}function V(){this.data.setextHeadingSlurpLineEnding=void 0}function R(A){const X=this.stack[this.stack.length-1].children;let ie=X[X.length-1];(!ie||ie.type!=="text")&&(ie=Tn(),ie.position={start:kt(A.start),end:void 0},X.push(ie)),this.stack.push(ie)}function S(A){const F=this.stack.pop();F.value+=this.sliceSerialize(A),F.position.end=kt(A.end)}function D(A){const F=this.stack[this.stack.length-1];if(this.data.atHardBreak){const X=F.children[F.children.length-1];X.position.end=kt(A.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(F.type)&&(R.call(this,A),S.call(this,A))}function N(){this.data.atHardBreak=!0}function K(){const A=this.resume(),F=this.stack[this.stack.length-1];F.value=A}function B(){const A=this.resume(),F=this.stack[this.stack.length-1];F.value=A}function P(){const A=this.resume(),F=this.stack[this.stack.length-1];F.value=A}function q(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const F=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=F,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function J(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const F=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=F,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function ue(A){const F=this.sliceSerialize(A),X=this.stack[this.stack.length-2];X.label=ey(F),X.identifier=et(F).toLowerCase()}function se(){const A=this.stack[this.stack.length-1],F=this.resume(),X=this.stack[this.stack.length-1];if(this.data.inReference=!0,X.type==="link"){const ie=A.children;X.children=ie}else X.alt=F}function v(){const A=this.resume(),F=this.stack[this.stack.length-1];F.url=A}function Y(){const A=this.resume(),F=this.stack[this.stack.length-1];F.title=A}function xe(){this.data.inReference=void 0}function k(){this.data.referenceType="collapsed"}function Se(A){const F=this.resume(),X=this.stack[this.stack.length-1];X.label=F,X.identifier=et(this.sliceSerialize(A)).toLowerCase(),this.data.referenceType="full"}function Ye(A){this.data.characterReferenceType=A.type}function _e(A){const F=this.sliceSerialize(A),X=this.data.characterReferenceType;let ie;X?(ie=il(F,X==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ie=_i(F);const he=this.stack[this.stack.length-1];he.value+=ie}function j(A){const F=this.stack.pop();F.position.end=kt(A.end)}function re(A){S.call(this,A);const F=this.stack[this.stack.length-1];F.url=this.sliceSerialize(A)}function le(A){S.call(this,A);const F=this.stack[this.stack.length-1];F.url="mailto:"+this.sliceSerialize(A)}function oe(){return{type:"blockquote",children:[]}}function Ee(){return{type:"code",lang:null,meta:null,value:""}}function ne(){return{type:"inlineCode",value:""}}function we(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function ot(){return{type:"emphasis",children:[]}}function lt(){return{type:"heading",depth:0,children:[]}}function ht(){return{type:"break"}}function St(){return{type:"html",value:""}}function ft(){return{type:"image",title:null,url:"",alt:null}}function G(){return{type:"link",title:null,url:"",children:[]}}function be(A){return{type:"list",ordered:A.type==="listOrdered",start:null,spread:A._spread,children:[]}}function me(A){return{type:"listItem",spread:A._spread,checked:null,children:[]}}function Dt(){return{type:"paragraph",children:[]}}function _n(){return{type:"strong",children:[]}}function Tn(){return{type:"text",value:""}}function Tv(){return{type:"thematicBreak"}}}function kt(e){return{line:e.line,column:e.column,offset:e.offset}}function kl(e,t){let r=-1;for(;++r<t.length;){const n=t[r];Array.isArray(n)?kl(e,n):iy(e,n)}}function iy(e,t){let r;for(r in t)if(vl.call(t,r))switch(r){case"canContainEols":{const n=t[r];n&&e[r].push(...n);break}case"transforms":{const n=t[r];n&&e[r].push(...n);break}case"enter":case"exit":{const n=t[r];n&&Object.assign(e[r],n);break}}}function Sl(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+wr({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+wr({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+wr({start:t.start,end:t.end})+") is still open")}function ay(e){const t=this;t.parser=r;function r(n){return ry(n,I(m(m({},t.data("settings")),e),{extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]}))}}function sy(e,t){const r={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,r),e.applyData(t,r)}function oy(e,t){const r={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,r),[e.applyData(t,r),{type:"text",value:`
|
|
11
|
-
`}]}function
|
|
12
|
-
`:"",n={},
|
|
13
|
-
`}),d.type==="element"&&d.tagName==="p"&&!i
|
|
14
|
-
`});const u={type:"element",tagName:"li",properties:
|
|
7
|
+
`);a=o.pop()||"";for(const l of o)if(l.startsWith("data: ")){const u=l.slice(6);if(u.trim()==="[DONE]"){yield{done:!0};continue}try{yield JSON.parse(u)}catch(d){}}}}finally{r.releaseLock()}})}function hp(e){return e.map(t=>{let r="";if(typeof t.content=="string")r=t.content;else if(Array.isArray(t.content)){const n=t.content.find(a=>a.type==="text");n&&typeof n=="object"&&"text"in n&&(r=n.text)}return{role:t.role,content:r}})}function fp(e){return m(m({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 Vt=new Map,ln=new Map;let Wt;function ga(e,t){const r=Vt.get(e);if(r)return r;if(t)for(const n of t){const a=ln.get(n.id);if(a)return Vt.set(e,a),a}return e}function pp(e,t){return{list(){return M(this,null,function*(){const n=[];let s,i=0;do{const l=yield e.listChats({limit:50,cursor:s}),u=l.items||[];Array.isArray(u)&&u.length>0&&n.push(...u),s=l.nextCursor||void 0,i++}while(s&&i<50);return{threads:n.map(l=>{const u=l.id;return!u||l.deletedAt?null:{status:"regular",remoteId:u,title:l.title||"New Chat",createdAt:l.createdAt?new Date(l.createdAt):new Date,updatedAt:l.updatedAt?new Date(l.updatedAt):new Date}}).filter(l=>l!==null)}})},initialize(n){return M(this,null,function*(){return{remoteId:Vt.get(n)||n,externalId:void 0}})},rename(n,a){return M(this,null,function*(){const s=ga(n);yield e.updateChat(s,{title:a})})},archive(n){return M(this,null,function*(){})},unarchive(n){return M(this,null,function*(){})},delete(n){return M(this,null,function*(){const a=ga(n);yield e.deleteChat(a)})},generateTitle(n,a){return M(this,null,function*(){var o;const s=ga(n,a);let i;try{i=(yield e.generateChatTitle(s)).title}catch(l){console.error("[generateTitle] API call failed, falling back to first message",l);const u=a.find(c=>c.role==="user"),d=(o=u==null?void 0:u.content)==null?void 0:o.filter(c=>c.type==="text").map(c=>c.text).join(" ").trim();i=d?d.length>60?d.slice(0,57)+"...":d:void 0}return Rs(l=>{const u=l.addTextPart();i&&u.append(i),u.close(),l.close()})})},fetch(n){return M(this,null,function*(){try{const a=yield e.getChat(n);return{status:"regular",remoteId:a.id||n,title:a.title||"Chat",createdAt:a.createdAt?new Date(a.createdAt):new Date,updatedAt:a.updatedAt?new Date(a.updatedAt):new Date}}catch(a){return{status:"regular",remoteId:n,createdAt:new Date,updatedAt:new Date}}})},updateRemoteId(n,a){Vt.set(n,a),t==null||t(n,a)},unstable_Provider:({children:n})=>{const a=Ci(),s=a==null?void 0:a.remoteId;b.useEffect(()=>{s&&(Wt=s)},[s]);const i=b.useMemo(()=>({load(){return M(this,null,function*(){if(!s)return{messages:[]};try{const u=yield e.getChat(s);if(!u.messages||u.messages.length===0)return{messages:[]};const d=u.messages.map(f=>fp(f)),c=d.map((f,h)=>({message:f,parentId:h>0?d[h-1].id:null}));for(const f of d)ln.set(f.id,s);return{messages:c}}catch(u){return{messages:[]}}})},append(u){return M(this,null,function*(){})}}),[s,e]),o=b.useMemo(()=>({history:i}),[i]);return p.jsx(Vn,{adapters:o,children:n})}}}class mp{constructor(){T(this,"messageMetadata",new Map);T(this,"currentMessageId",null);T(this,"listeners",new Set)}setCurrentMessage(t){this.currentMessageId=t}update(t){if(!this.currentMessageId)return;const r=this.messageMetadata.get(this.currentMessageId)||{},n=t.sources;n&&n.length>0&&(this.messageMetadata.set(this.currentMessageId,I(m({},r),{sources:n})),this.notify())}get(){return this.currentMessageId?this.messageMetadata.get(this.currentMessageId)||{}:{}}getForMessage(t){return this.messageMetadata.get(t)||{}}getCurrentMessageId(){return this.currentMessageId}clear(){this.currentMessageId=null}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}notify(){this.listeners.forEach(t=>t())}}const wt=new mp,Eo=new Map,ya=[];let un=[];function Ao(e,t,r=50,n=800){ya.push({question:e,response:t,streamingSpeed:r,initialDelay:n})}function Mo(e,t){const{modelId:r,systemPrompt:n,ephemeral:a,enableReasoning:s,onChatCreated:i,onUserMessage:o,onThreadIdUpdate:l,onBeforeRequest:u,mockResponseOnBlocked:d}=t;let c;return{run(h){return Or(this,null,function*(){var ue,ie,v,Y,we;const{messages:g,abortSignal:w}=h,x=ya.shift();if(x){o==null||o();const j=(ue=x.initialDelay)!=null?ue:800;if(j>0&&(yield new Ae(new Promise(ne=>setTimeout(ne,j)))),w!=null&&w.aborted)throw new Error("Request aborted");const re=x.response.split(" ");let le="";const oe=x.streamingSpeed||50,Ee=`premade-${Date.now()}`;a&&(i==null||i(Ee));for(let ne=0;ne<re.length;ne++){if(w!=null&&w.aborted)throw new Error("Request aborted");le+=(ne===0?"":" ")+re[ne],yield{content:[{type:"text",text:le}]},yield new Ae(new Promise(xe=>setTimeout(xe,oe+Math.random()*(oe*.5))))}yield{content:[{type:"text",text:le}]},un.push({role:"user",content:x.question},{role:"assistant",content:x.response});return}let y;for(const j of g){const re=ln.get(j.id);if(re){y=re;break}}if(!y&&g.length>0){const j=g.find(re=>re.role==="user");if(j){const le=(typeof j.content=="string"?j.content:Array.isArray(j.content)&&((ie=j.content.find(oe=>oe.type==="text"))==null?void 0:ie.text)||"").substring(0,50);y=Eo.get(le)}}!y&&c&&(y=c),o==null||o();let E=g,_=-1;for(let j=g.length-1;j>=0;j--)if(g[j].role==="assistant"){_=j;break}(y||_>=0)&&_>=0&&(E=g.slice(_+1));const O=hp(E);if(un.length>0&&!y){const j=un.map(re=>({role:re.role,content:re.content}));O.unshift(...j),un=[]}const z=[];let C;for(let j=E.length-1;j>=0;j--)if(E[j].role==="user"){C=E[j];break}if(C&&"attachments"in C){const j=C.attachments;if(j&&j.length>0){for(const re of j)if(re.file)try{const le=yield new Ae(e.uploadFile(re.file));z.push(le.id)}catch(le){}}}const U={messages:O,chatId:y||null,systemPrompt:n,ephemeral:a,enableReasoning:s,stream:!0};if(r&&r.trim()!==""&&(U.modelId=r),z.length>0&&(U.fileIds=z),u&&!(yield new Ae(u()))){if(d){const re=typeof d=="function"?d():d,le=g.filter(xe=>xe.role==="user"),oe=le.length>0?le[le.length-1]:void 0;let Ee="Message";if(oe){if(typeof oe.content=="string")Ee=oe.content;else if(Array.isArray(oe.content)){const xe=oe.content.find(ot=>ot.type==="text");Ee=(xe==null?void 0:xe.text)||"Message"}}Ao(Ee,re,40,400);const ne=ya.shift();if(ne){o==null||o();const xe=(v=ne.initialDelay)!=null?v:400;if(xe>0&&(yield new Ae(new Promise(ft=>setTimeout(ft,xe)))),w!=null&&w.aborted)throw new Error("Request aborted");const ot=ne.response.split(" ");let lt="";const ht=ne.streamingSpeed||40,St=`mock-${Date.now()}`;a&&(i==null||i(St));for(let ft=0;ft<ot.length;ft++){if(w!=null&&w.aborted)throw new Error("Request aborted");lt+=(ft===0?"":" ")+ot[ft],yield{content:[{type:"text",text:lt}]},yield new Ae(new Promise(G=>setTimeout(G,ht+Math.random()*(ht*.3))))}yield{content:[{type:"text",text:lt}]};return}}throw new Error("Request blocked")}const V=yield new Ae(e.createOrContinueChat(U,w));let R="",S="",D;const N=[];let K=0,B=!1;const P=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;wt.clear(),wt.setCurrentMessage(P);const q=()=>{N.length!==K&&(K=N.length,wt.update({sources:N.length>0?[...N]:void 0}))},J=()=>{q();const j=[];return S&&j.push({type:"reasoning",text:S}),R&&j.push({type:"text",text:R}),j.length===0&&j.push({type:"text",text:""}),{content:j}};try{for(var k=Ft(dp(V,w)),Se,Ye,_e;Se=!(Ye=yield new Ae(k.next())).done;Se=!1){const j=Ye.value;if(w!=null&&w.aborted)throw new Error("Request aborted");const re=j.id||j.chatId||j.messageId;if(re&&!D){D=re,c=re,i==null||i(re);for(const ne of g)ln.set(ne.id,re);if(g.length>0){const ne=g.find(xe=>xe.role==="user");if(ne){const ot=(typeof ne.content=="string"?ne.content:Array.isArray(ne.content)&&((Y=ne.content.find(lt=>lt.type==="text"))==null?void 0:Y.text)||"").substring(0,50);Eo.set(ot,re)}}Wt&&!Vt.has(Wt)&&Vt.set(Wt,re),l&&Wt&&l(Wt,re)}const le=j.sources;if(le&&Array.isArray(le)&&le.length>0)for(const ne of le)N.some(xe=>xe.sourceId===ne.sourceId)||N.push({sourceId:ne.sourceId,filename:ne.filename||"Unknown",score:(we=ne.score)!=null?we:1,chunkId:ne.chunkId,datasetId:ne.datasetId});const oe=j.reasoning;if(oe&&oe.length>0&&(S+=oe,yield J()),j.type)switch(j.type){case"source-document":j.sourceId&&N.push({sourceId:j.sourceId,filename:j.title||"Unknown",score:1});continue;case"reasoning-start":continue;case"reasoning-delta":j.delta&&(S+=j.delta),(R||S)&&(yield J());continue;case"reasoning-end":(R||S)&&(yield J());continue;case"text-delta":j.delta&&(S&&!B&&!R&&(B=!0,yield new Ae(new Promise(ne=>setTimeout(ne,400)))),R+=j.delta),R&&(yield J());continue;case"error":throw new Error(j.errorText||"Stream error");case"text-start":case"text-end":case"start":case"start-step":case"finish-step":case"finish":continue}const Ee=j.delta;if(Ee!=null&&(S&&!B&&!R&&(B=!0,yield new Ae(new Promise(ne=>setTimeout(ne,400)))),R+=Ee),j.content&&(R+=j.content),j.message&&(R+=j.message.content||""),j.finished){(R||S||N.length>0)&&(yield J());break}(R||S||N.length>0)&&(yield J())}}catch(Ye){_e=[Ye]}finally{try{Se&&(Ye=k.return)&&(yield new Ae(Ye.call(k)))}finally{if(_e)throw _e[0]}}(R||S||N.length>0)&&(yield J())})}}}class gr extends Error{constructor(t,r,n){super(t),this.code=r,this.file=n,this.name="AttachmentValidationError"}}const gp=["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"],yp=[".pdf",".doc",".docx",".xls",".xlsx",".txt",".md",".csv",".json",".jpg",".jpeg",".png",".gif",".webp",".svg"],bp=10*1024*1024;function Po(e){if(e===0)return"0 Bytes";const t=1024,r=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,n)).toFixed(2))+" "+r[n]}function xp(e){return e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")).toLowerCase():""}function wp(e,t){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(t.toLowerCase()):!0}function vp(){return typeof crypto!="undefined"&&crypto.randomUUID?"attachment-"+crypto.randomUUID():"attachment-"+Date.now()+"-"+Math.random().toString(36).slice(2,11)}function No(e={}){const{validation:t={},supportsVision:r=!0,onValidationError:n,onAttachmentAdded:a,onAttachmentRemoved:s}=e,{maxFileSizeBytes:i=bp,allowedMimeTypes:o=gp,allowedExtensions:l=yp,validateContentType:u=!0}=t,d=l.join(",");function c(h){if(h.size>i){const w=new gr('File "'+h.name+'" is too large ('+Po(h.size)+"). Maximum size is "+Po(i)+".","FILE_TOO_LARGE",h);throw n==null||n(w),w}if(!r&&h.type.startsWith("image/")){const w=new gr("The current model does not support image inputs. Please select a model with vision capabilities to attach images.","VISION_NOT_SUPPORTED",h);throw n==null||n(w),w}const g=xp(h.name);if(g&&!l.some(w=>w.toLowerCase()===g)){const w=new gr('File type "'+g+'" is not allowed. Allowed types: '+l.join(", "),"INVALID_TYPE",h);throw n==null||n(w),w}if(h.type&&!o.some(w=>{if(w.endsWith("/*")){const x=w.slice(0,-1);return h.type.startsWith(x)}return h.type===w})){const w=new gr('File type "'+h.type+'" is not allowed.',"INVALID_TYPE",h);throw n==null||n(w),w}if(u&&h.type&&g&&!wp(h.type,g)){const w=new gr('File extension "'+g+'" does not match content type "'+h.type+'".',"VALIDATION_FAILED",h);throw n==null||n(w),w}}return{accept:d,add(g){return M(this,arguments,function*({file:h}){c(h);let w="file";h.type.startsWith("image/")?w="image":(h.type.includes("pdf")||h.type.includes("document")||h.type.includes("text")||h.name.endsWith(".pdf")||h.name.endsWith(".docx")||h.name.endsWith(".txt")||h.name.endsWith(".md")||h.name.endsWith(".csv")||h.name.endsWith(".json"))&&(w="document");const x={id:vp(),type:w,name:h.name,contentType:h.type,file:h,status:{type:"requires-action",reason:"composer-send"}};return a==null||a(x),x})},remove(h){return M(this,null,function*(){s==null||s(h.id)})},send(h){return M(this,null,function*(){if(h.type==="image"&&h.file){const g=yield new Promise((w,x)=>{const y=new FileReader;y.onload=()=>w(y.result),y.onerror=()=>x(new Error("Failed to read file")),y.readAsDataURL(h.file)});return I(m({},h),{status:{type:"complete"},content:[{type:"image",image:g}]})}return I(m({},h),{status:{type:"complete"},content:[]})})}}}class kp{constructor(){T(this,"current",null);T(this,"listeners",new Set);T(this,"getSnapshot",()=>this.current);T(this,"subscribe",t=>(this.listeners.add(t),()=>this.listeners.delete(t)))}push(t,r){this.current={message:t,code:r,timestamp:Date.now()},this.notify()}clear(){this.current&&(this.current=null,this.notify())}notify(){this.listeners.forEach(t=>t())}}const Jt=new kp;function Sp({children:e,baseUrl:t,sessionToken:r,isProxyMode:n=!1,mode:a="multiChat",modelId:s,onModelChange:i,ephemeral:o=!1,systemPrompt:l,enableReasoning:u=!1,initialThreadId:d,onError:c,onChatCreated:f,onUserMessage:h,onThreadIdUpdate:g,onChatsLoaded:w,enableAttachments:x=!1,supportsVision:y=!0,onBeforeRequest:E,mockResponseOnBlocked:_}){const O=b.useMemo(()=>new Io(t,r||void 0,n),[t,r,n]),[z,C]=b.useState(s||null);b.useEffect(()=>{s&&C(s)},[s]);const U=b.useCallback(S=>{f==null||f(S)},[f]),V=b.useCallback((S,D)=>{g==null||g(S,D)},[g]),R=b.useMemo(()=>Mo(O,{modelId:z||void 0,systemPrompt:l,ephemeral:o,enableReasoning:u,onChatCreated:U,onUserMessage:h,onBeforeRequest:E,mockResponseOnBlocked:_}),[O,z,l,o,u,U,h,E,_]);return a==="singleChat"?p.jsx(_p,{modelAdapter:R,enableAttachments:x,supportsVision:y,children:e}):p.jsx(Tp,{client:O,modelAdapterOptions:{modelId:z||void 0,systemPrompt:l,ephemeral:o,enableReasoning:u,onChatCreated:U,onUserMessage:h,onBeforeRequest:E,mockResponseOnBlocked:_},initialThreadId:d,onChatsLoaded:w,onThreadIdUpdate:V,onError:c,enableAttachments:x,supportsVision:y,children:e})}function _p({modelAdapter:e,enableAttachments:t,supportsVision:r=!0,children:n}){const a=b.useMemo(()=>t?No({supportsVision:r,onValidationError:i=>{Jt.push(i.message,i.code)}}):void 0,[t,r]),s=Fi(e,{adapters:m({},a&&{attachments:a})});return p.jsx(Mi,{runtime:s,children:n})}function Tp({client:e,modelAdapterOptions:t,initialThreadId:r,onChatsLoaded:n,onThreadIdUpdate:a,onError:s,enableAttachments:i,supportsVision:o,children:l}){const u=b.useMemo(()=>pp(e,(x,y)=>{a==null||a(x,y)}),[e,a]),d=b.useCallback((x,y)=>{u.updateRemoteId&&u.updateRemoteId(x,y),a==null||a(x,y)},[u,a]),c=b.useMemo(()=>I(m({},u),{list(){return M(this,null,function*(){const y=yield u.list();return n==null||n(),y})}}),[u,n]);b.useEffect(()=>{window.__cuadraThreadListAdapter=c,window.__cuadraThreadListRuntime=null},[c]);const f=b.useMemo(()=>Mo(e,I(m({},t),{onThreadIdUpdate:d})),[e,t,d]),h=b.useMemo(()=>i?No({supportsVision:o,onValidationError:x=>{Jt.push(x.message,x.code)}}):void 0,[i,o]),g=b.useCallback(()=>Fi(f,{adapters:m({},h&&{attachments:h})}),[f,h]),w=$i({adapter:c,runtimeHook:g});return b.useEffect(()=>{window.__cuadraThreadListRuntime=w},[w]),p.jsx(Mi,{runtime:w,children:l})}function Qv(){}function Zv(){}function Cp(e,t){const r={};return(e[e.length-1]===""?[...e,""]:e).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}const Ip=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Ep=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Ap={};function Lo(e,t){return(Ap.jsx?Ep:Ip).test(e)}const Mp=/[ \t\n\f\r]/g;function Pp(e){return typeof e=="object"?e.type==="text"?Do(e.value):!1:Do(e)}function Do(e){return e.replace(Mp,"")===""}class yr{constructor(t,r,n){this.normal=r,this.property=t,n&&(this.space=n)}}yr.prototype.normal={},yr.prototype.property={},yr.prototype.space=void 0;function Oo(e,t){const r={},n={};for(const a of e)Object.assign(r,a.property),Object.assign(n,a.normal);return new yr(r,n,t)}function ba(e){return e.toLowerCase()}class Re{constructor(t,r){this.attribute=r,this.property=t}}Re.prototype.attribute="",Re.prototype.booleanish=!1,Re.prototype.boolean=!1,Re.prototype.commaOrSpaceSeparated=!1,Re.prototype.commaSeparated=!1,Re.prototype.defined=!1,Re.prototype.mustUseProperty=!1,Re.prototype.number=!1,Re.prototype.overloadedBoolean=!1,Re.prototype.property="",Re.prototype.spaceSeparated=!1,Re.prototype.space=void 0;let Np=0;const Q=Mt(),ke=Mt(),xa=Mt(),L=Mt(),fe=Mt(),Kt=Mt(),He=Mt();function Mt(){return Hu(2,++Np)}const wa=Object.freeze(Object.defineProperty({__proto__:null,boolean:Q,booleanish:ke,commaOrSpaceSeparated:He,commaSeparated:Kt,number:L,overloadedBoolean:xa,spaceSeparated:fe},Symbol.toStringTag,{value:"Module"})),va=Object.keys(wa);class ka extends Re{constructor(t,r,n,a){let s=-1;if(super(t,r),Fo(this,"space",a),typeof n=="number")for(;++s<va.length;){const i=va[s];Fo(this,va[s],(n&wa[i])===wa[i])}}}ka.prototype.defined=!0;function Fo(e,t,r){r&&(e[t]=r)}function Yt(e){const t={},r={};for(const[n,a]of Object.entries(e.properties)){const s=new ka(n,e.transform(e.attributes||{},n),a,e.space);e.mustUseProperty&&e.mustUseProperty.includes(n)&&(s.mustUseProperty=!0),t[n]=s,r[ba(n)]=n,r[ba(s.attribute)]=n}return new yr(t,r,e.space)}const zo=Yt({properties:{ariaActiveDescendant:null,ariaAtomic:ke,ariaAutoComplete:null,ariaBusy:ke,ariaChecked:ke,ariaColCount:L,ariaColIndex:L,ariaColSpan:L,ariaControls:fe,ariaCurrent:null,ariaDescribedBy:fe,ariaDetails:null,ariaDisabled:ke,ariaDropEffect:fe,ariaErrorMessage:null,ariaExpanded:ke,ariaFlowTo:fe,ariaGrabbed:ke,ariaHasPopup:null,ariaHidden:ke,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:fe,ariaLevel:L,ariaLive:null,ariaModal:ke,ariaMultiLine:ke,ariaMultiSelectable:ke,ariaOrientation:null,ariaOwns:fe,ariaPlaceholder:null,ariaPosInSet:L,ariaPressed:ke,ariaReadOnly:ke,ariaRelevant:null,ariaRequired:ke,ariaRoleDescription:fe,ariaRowCount:L,ariaRowIndex:L,ariaRowSpan:L,ariaSelected:ke,ariaSetSize:L,ariaSort:null,ariaValueMax:L,ariaValueMin:L,ariaValueNow:L,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function Bo(e,t){return t in e?e[t]:t}function Ro(e,t){return Bo(e,t.toLowerCase())}const Lp=Yt({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Kt,acceptCharset:fe,accessKey:fe,action:null,allow:null,allowFullScreen:Q,allowPaymentRequest:Q,allowUserMedia:Q,alt:null,as:null,async:Q,autoCapitalize:null,autoComplete:fe,autoFocus:Q,autoPlay:Q,blocking:fe,capture:null,charSet:null,checked:Q,cite:null,className:fe,cols:L,colSpan:null,content:null,contentEditable:ke,controls:Q,controlsList:fe,coords:L|Kt,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Q,defer:Q,dir:null,dirName:null,disabled:Q,download:xa,draggable:ke,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Q,formTarget:null,headers:fe,height:L,hidden:xa,high:L,href:null,hrefLang:null,htmlFor:fe,httpEquiv:fe,id:null,imageSizes:null,imageSrcSet:null,inert:Q,inputMode:null,integrity:null,is:null,isMap:Q,itemId:null,itemProp:fe,itemRef:fe,itemScope:Q,itemType:fe,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Q,low:L,manifest:null,max:null,maxLength:L,media:null,method:null,min:null,minLength:L,multiple:Q,muted:Q,name:null,nonce:null,noModule:Q,noValidate:Q,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:Q,optimum:L,pattern:null,ping:fe,placeholder:null,playsInline:Q,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Q,referrerPolicy:null,rel:fe,required:Q,reversed:Q,rows:L,rowSpan:L,sandbox:fe,scope:null,scoped:Q,seamless:Q,selected:Q,shadowRootClonable:Q,shadowRootDelegatesFocus:Q,shadowRootMode:null,shape:null,size:L,sizes:null,slot:null,span:L,spellCheck:ke,src:null,srcDoc:null,srcLang:null,srcSet:null,start:L,step:null,style:null,tabIndex:L,target:null,title:null,translate:null,type:null,typeMustMatch:Q,useMap:null,value:ke,width:L,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:fe,axis:null,background:null,bgColor:null,border:L,borderColor:null,bottomMargin:L,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Q,declare:Q,event:null,face:null,frame:null,frameBorder:null,hSpace:L,leftMargin:L,link:null,longDesc:null,lowSrc:null,marginHeight:L,marginWidth:L,noResize:Q,noHref:Q,noShade:Q,noWrap:Q,object:null,profile:null,prompt:null,rev:null,rightMargin:L,rules:null,scheme:null,scrolling:ke,standby:null,summary:null,text:null,topMargin:L,valueType:null,version:null,vAlign:null,vLink:null,vSpace:L,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Q,disableRemotePlayback:Q,prefix:null,property:null,results:L,security:null,unselectable:null},space:"html",transform:Ro}),Dp=Yt({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:He,accentHeight:L,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:L,amplitude:L,arabicForm:null,ascent:L,attributeName:null,attributeType:null,azimuth:L,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:L,by:null,calcMode:null,capHeight:L,className:fe,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:L,diffuseConstant:L,direction:null,display:null,dur:null,divisor:L,dominantBaseline:null,download:Q,dx:null,dy:null,edgeMode:null,editable:null,elevation:L,enableBackground:null,end:null,event:null,exponent:L,externalResourcesRequired:null,fill:null,fillOpacity:L,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Kt,g2:Kt,glyphName:Kt,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:L,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:L,horizOriginX:L,horizOriginY:L,id:null,ideographic:L,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:L,k:L,k1:L,k2:L,k3:L,k4:L,kernelMatrix:He,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:L,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:L,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:L,overlineThickness:L,paintOrder:null,panose1:null,path:null,pathLength:L,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:fe,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:L,pointsAtY:L,pointsAtZ:L,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:He,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:He,rev:He,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:He,requiredFeatures:He,requiredFonts:He,requiredFormats:He,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:L,specularExponent:L,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:L,strikethroughThickness:L,string:null,stroke:null,strokeDashArray:He,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:L,strokeOpacity:L,strokeWidth:null,style:null,surfaceScale:L,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:He,tabIndex:L,tableValues:null,target:null,targetX:L,targetY:L,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:He,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:L,underlineThickness:L,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:L,values:null,vAlphabetic:L,vMathematical:L,vectorEffect:null,vHanging:L,vIdeographic:L,version:null,vertAdvY:L,vertOriginX:L,vertOriginY:L,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:L,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Bo}),jo=Yt({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),$o=Yt({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Ro}),Uo=Yt({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),Op={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},Fp=/[A-Z]/g,Ho=/-[a-z]/g,zp=/^data[-\w.:]+$/i;function Bp(e,t){const r=ba(t);let n=t,a=Re;if(r in e.normal)return e.property[e.normal[r]];if(r.length>4&&r.slice(0,4)==="data"&&zp.test(t)){if(t.charAt(4)==="-"){const s=t.slice(5).replace(Ho,jp);n="data"+s.charAt(0).toUpperCase()+s.slice(1)}else{const s=t.slice(4);if(!Ho.test(s)){let i=s.replace(Fp,Rp);i.charAt(0)!=="-"&&(i="-"+i),t="data"+i}}a=ka}return new a(n,t)}function Rp(e){return"-"+e.toLowerCase()}function jp(e){return e.charAt(1).toUpperCase()}const $p=Oo([zo,Lp,jo,$o,Uo],"html"),Sa=Oo([zo,Dp,jo,$o,Uo],"svg");function Up(e){return e.join(" ").trim()}var Gt={},_a,qo;function Hp(){if(qo)return _a;qo=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,r=/^\s*/,n=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,i=/^[;\s]*/,o=/^\s+|\s+$/g,l=`
|
|
8
|
+
`,u="/",d="*",c="",f="comment",h="declaration";function g(x,y){if(typeof x!="string")throw new TypeError("First argument must be a string");if(!x)return[];y=y||{};var E=1,_=1;function O(B){var P=B.match(t);P&&(E+=P.length);var q=B.lastIndexOf(l);_=~q?B.length-q:_+B.length}function z(){var B={line:E,column:_};return function(P){return P.position=new C(B),R(),P}}function C(B){this.start=B,this.end={line:E,column:_},this.source=y.source}C.prototype.content=x;function U(B){var P=new Error(y.source+":"+E+":"+_+": "+B);if(P.reason=B,P.filename=y.source,P.line=E,P.column=_,P.source=x,!y.silent)throw P}function V(B){var P=B.exec(x);if(P){var q=P[0];return O(q),x=x.slice(q.length),P}}function R(){V(r)}function S(B){var P;for(B=B||[];P=D();)P!==!1&&B.push(P);return B}function D(){var B=z();if(!(u!=x.charAt(0)||d!=x.charAt(1))){for(var P=2;c!=x.charAt(P)&&(d!=x.charAt(P)||u!=x.charAt(P+1));)++P;if(P+=2,c===x.charAt(P-1))return U("End of comment missing");var q=x.slice(2,P-2);return _+=2,O(q),x=x.slice(P),_+=2,B({type:f,comment:q})}}function N(){var B=z(),P=V(n);if(P){if(D(),!V(a))return U("property missing ':'");var q=V(s),J=B({type:h,property:w(P[0].replace(e,c)),value:q?w(q[0].replace(e,c)):c});return V(i),J}}function K(){var B=[];S(B);for(var P;P=N();)P!==!1&&(B.push(P),S(B));return B}return R(),K()}function w(x){return x?x.replace(o,c):c}return _a=g,_a}var Vo;function qp(){if(Vo)return Gt;Vo=1;var e=Gt&&Gt.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.default=r;const t=e(Hp());function r(n,a){let s=null;if(!n||typeof n!="string")return s;const i=(0,t.default)(n),o=typeof a=="function";return i.forEach(l=>{if(l.type!=="declaration")return;const{property:u,value:d}=l;o?a(u,d,l):d&&(s=s||{},s[u]=d)}),s}return Gt}var br={},Wo;function Vp(){if(Wo)return br;Wo=1,Object.defineProperty(br,"__esModule",{value:!0}),br.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,r=/^[^-]+$/,n=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,s=function(u){return!u||r.test(u)||e.test(u)},i=function(u,d){return d.toUpperCase()},o=function(u,d){return"".concat(d,"-")},l=function(u,d){return d===void 0&&(d={}),s(u)?u:(u=u.toLowerCase(),d.reactCompat?u=u.replace(a,o):u=u.replace(n,o),u.replace(t,i))};return br.camelCase=l,br}var xr,Jo;function Wp(){if(Jo)return xr;Jo=1;var e=xr&&xr.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(qp()),r=Vp();function n(a,s){var i={};return!a||typeof a!="string"||(0,t.default)(a,function(o,l){o&&l&&(i[(0,r.camelCase)(o,s)]=l)}),i}return n.default=n,xr=n,xr}var Jp=Wp();const Kp=Br(Jp),Ko=Yo("end"),Ta=Yo("start");function Yo(e){return t;function t(r){const n=r&&r.position&&r.position[e]||{};if(typeof n.line=="number"&&n.line>0&&typeof n.column=="number"&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset=="number"&&n.offset>-1?n.offset:void 0}}}function Yp(e){const t=Ta(e),r=Ko(e);if(t&&r)return{start:t,end:r}}function wr(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Go(e.position):"start"in e||"end"in e?Go(e):"line"in e||"column"in e?Ca(e):""}function Ca(e){return Xo(e&&e.line)+":"+Xo(e&&e.column)}function Go(e){return Ca(e&&e.start)+"-"+Ca(e&&e.end)}function Xo(e){return e&&typeof e=="number"?e:1}class Pe extends Error{constructor(t,r,n){super(),typeof r=="string"&&(n=r,r=void 0);let a="",s={},i=!1;if(r&&("line"in r&&"column"in r?s={place:r}:"start"in r&&"end"in r?s={place:r}:"type"in r?s={ancestors:[r],place:r.position}:s=m({},r)),typeof t=="string"?a=t:!s.cause&&t&&(i=!0,a=t.message,s.cause=t),!s.ruleId&&!s.source&&typeof n=="string"){const l=n.indexOf(":");l===-1?s.ruleId=n:(s.source=n.slice(0,l),s.ruleId=n.slice(l+1))}if(!s.place&&s.ancestors&&s.ancestors){const l=s.ancestors[s.ancestors.length-1];l&&(s.place=l.position)}const o=s.place&&"start"in s.place?s.place.start:s.place;this.ancestors=s.ancestors||void 0,this.cause=s.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=o?o.line:void 0,this.name=wr(s.place)||"1:1",this.place=s.place||void 0,this.reason=this.message,this.ruleId=s.ruleId||void 0,this.source=s.source||void 0,this.stack=i&&s.cause&&typeof s.cause.stack=="string"?s.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Pe.prototype.file="",Pe.prototype.name="",Pe.prototype.reason="",Pe.prototype.message="",Pe.prototype.stack="",Pe.prototype.column=void 0,Pe.prototype.line=void 0,Pe.prototype.ancestors=void 0,Pe.prototype.cause=void 0,Pe.prototype.fatal=void 0,Pe.prototype.place=void 0,Pe.prototype.ruleId=void 0,Pe.prototype.source=void 0;const Ia={}.hasOwnProperty,Gp=new Map,Xp=/[A-Z]/g,Qp=new Set(["table","tbody","thead","tfoot","tr"]),Zp=new Set(["td","th"]),Qo="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function em(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const r=t.filePath||void 0;let n;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");n=lm(r,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");n=om(r,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:n,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:r,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?Sa:$p,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},s=Zo(a,e,void 0);return s&&typeof s!="string"?s:a.create(e,a.Fragment,{children:s||void 0},void 0)}function Zo(e,t,r){if(t.type==="element")return tm(e,t,r);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return rm(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return am(e,t,r);if(t.type==="mdxjsEsm")return nm(e,t);if(t.type==="root")return sm(e,t,r);if(t.type==="text")return im(e,t)}function tm(e,t,r){const n=e.schema;let a=n;t.tagName.toLowerCase()==="svg"&&n.space==="html"&&(a=Sa,e.schema=a),e.ancestors.push(t);const s=tl(e,t.tagName,!1),i=um(e,t);let o=Aa(e,t);return Qp.has(t.tagName)&&(o=o.filter(function(l){return typeof l=="string"?!Pp(l):!0})),el(e,i,s,t),Ea(i,o),e.ancestors.pop(),e.schema=n,e.create(t,s,i,r)}function rm(e,t){if(t.data&&t.data.estree&&e.evaluater){const n=t.data.estree.body[0];return n.type,e.evaluater.evaluateExpression(n.expression)}vr(e,t.position)}function nm(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);vr(e,t.position)}function am(e,t,r){const n=e.schema;let a=n;t.name==="svg"&&n.space==="html"&&(a=Sa,e.schema=a),e.ancestors.push(t);const s=t.name===null?e.Fragment:tl(e,t.name,!0),i=cm(e,t),o=Aa(e,t);return el(e,i,s,t),Ea(i,o),e.ancestors.pop(),e.schema=n,e.create(t,s,i,r)}function sm(e,t,r){const n={};return Ea(n,Aa(e,t)),e.create(t,e.Fragment,n,r)}function im(e,t){return t.value}function el(e,t,r,n){typeof r!="string"&&r!==e.Fragment&&e.passNode&&(t.node=n)}function Ea(e,t){if(t.length>0){const r=t.length>1?t:t[0];r&&(e.children=r)}}function om(e,t,r){return n;function n(a,s,i,o){const u=Array.isArray(i.children)?r:t;return o?u(s,i,o):u(s,i)}}function lm(e,t){return r;function r(n,a,s,i){const o=Array.isArray(s.children),l=Ta(n);return t(a,s,i,o,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function um(e,t){const r={};let n,a;for(a in t.properties)if(a!=="children"&&Ia.call(t.properties,a)){const s=dm(e,a,t.properties[a]);if(s){const[i,o]=s;e.tableCellAlignToStyle&&i==="align"&&typeof o=="string"&&Zp.has(t.tagName)?n=o:r[i]=o}}if(n){const s=r.style||(r.style={});s[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=n}return r}function cm(e,t){const r={};for(const n of t.attributes)if(n.type==="mdxJsxExpressionAttribute")if(n.data&&n.data.estree&&e.evaluater){const s=n.data.estree.body[0];s.type;const i=s.expression;i.type;const o=i.properties[0];o.type,Object.assign(r,e.evaluater.evaluateExpression(o.argument))}else vr(e,t.position);else{const a=n.name;let s;if(n.value&&typeof n.value=="object")if(n.value.data&&n.value.data.estree&&e.evaluater){const o=n.value.data.estree.body[0];o.type,s=e.evaluater.evaluateExpression(o.expression)}else vr(e,t.position);else s=n.value===null?!0:n.value;r[a]=s}return r}function Aa(e,t){const r=[];let n=-1;const a=e.passKeys?new Map:Gp;for(;++n<t.children.length;){const s=t.children[n];let i;if(e.passKeys){const l=s.type==="element"?s.tagName:s.type==="mdxJsxFlowElement"||s.type==="mdxJsxTextElement"?s.name:void 0;if(l){const u=a.get(l)||0;i=l+"-"+u,a.set(l,u+1)}}const o=Zo(e,s,i);o!==void 0&&r.push(o)}return r}function dm(e,t,r){const n=Bp(e.schema,t);if(!(r==null||typeof r=="number"&&Number.isNaN(r))){if(Array.isArray(r)&&(r=n.commaSeparated?Cp(r):Up(r)),n.property==="style"){let a=typeof r=="object"?r:hm(e,String(r));return e.stylePropertyNameCase==="css"&&(a=fm(a)),["style",a]}return[e.elementAttributeNameCase==="react"&&n.space?Op[n.property]||n.property:n.attribute,r]}}function hm(e,t){try{return Kp(t,{reactCompat:!0})}catch(r){if(e.ignoreInvalidStyle)return{};const n=r,a=new Pe("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:n,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw a.file=e.filePath||void 0,a.url=Qo+"#cannot-parse-style-attribute",a}}function tl(e,t,r){let n;if(!r)n={type:"Literal",value:t};else if(t.includes(".")){const a=t.split(".");let s=-1,i;for(;++s<a.length;){const o=Lo(a[s])?{type:"Identifier",name:a[s]}:{type:"Literal",value:a[s]};i=i?{type:"MemberExpression",object:i,property:o,computed:!!(s&&o.type==="Literal"),optional:!1}:o}n=i}else n=Lo(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(n.type==="Literal"){const a=n.value;return Ia.call(e.components,a)?e.components[a]:a}if(e.evaluater)return e.evaluater.evaluateExpression(n);vr(e)}function vr(e,t){const r=new Pe("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=Qo+"#cannot-handle-mdx-estrees-without-createevaluater",r}function fm(e){const t={};let r;for(r in e)Ia.call(e,r)&&(t[pm(r)]=e[r]);return t}function pm(e){let t=e.replace(Xp,mm);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function mm(e){return"-"+e.toLowerCase()}const Ma={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},gm={};function Pa(e,t){const r=gm,n=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,a=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return rl(e,n,a)}function rl(e,t,r){if(ym(e)){if("value"in e)return e.type==="html"&&!r?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return nl(e.children,t,r)}return Array.isArray(e)?nl(e,t,r):""}function nl(e,t,r){const n=[];let a=-1;for(;++a<e.length;)n[a]=rl(e[a],t,r);return n.join("")}function ym(e){return!!(e&&typeof e=="object")}const al=document.createElement("i");function Na(e){const t="&"+e+";";al.innerHTML=t;const r=al.textContent;return r.charCodeAt(r.length-1)===59&&e!=="semi"||r===t?!1:r}function qe(e,t,r,n){const a=e.length;let s=0,i;if(t<0?t=-t>a?0:a+t:t=t>a?a:t,r=r>0?r:0,n.length<1e4)i=Array.from(n),i.unshift(t,r),e.splice(...i);else for(r&&e.splice(t,r);s<n.length;)i=n.slice(s,s+1e4),i.unshift(t,0),e.splice(...i),s+=1e4,t+=1e4}function Je(e,t){return e.length>0?(qe(e,e.length,0,t),e):t}const sl={}.hasOwnProperty;function il(e){const t={};let r=-1;for(;++r<e.length;)bm(t,e[r]);return t}function bm(e,t){let r;for(r in t){const a=(sl.call(e,r)?e[r]:void 0)||(e[r]={}),s=t[r];let i;if(s)for(i in s){sl.call(a,i)||(a[i]=[]);const o=s[i];xm(a[i],Array.isArray(o)?o:o?[o]:[])}}}function xm(e,t){let r=-1;const n=[];for(;++r<t.length;)(t[r].add==="after"?e:n).push(t[r]);qe(e,0,0,n)}function ol(e,t){const r=Number.parseInt(e,t);return r<9||r===11||r>13&&r<32||r>126&&r<160||r>55295&&r<57344||r>64975&&r<65008||(r&65535)===65535||(r&65535)===65534||r>1114111?"�":String.fromCodePoint(r)}function et(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Fe=vt(/[A-Za-z]/),Ne=vt(/[\dA-Za-z]/),wm=vt(/[#-'*+\--9=?A-Z^-~]/);function cn(e){return e!==null&&(e<32||e===127)}const La=vt(/\d/),vm=vt(/[\dA-Fa-f]/),km=vt(/[!-/:-@[-`{-~]/);function W(e){return e!==null&&e<-2}function de(e){return e!==null&&(e<0||e===32)}function te(e){return e===-2||e===-1||e===32}const dn=vt(new RegExp("\\p{P}|\\p{S}","u")),Pt=vt(/\s/);function vt(e){return t;function t(r){return r!==null&&r>-1&&e.test(String.fromCharCode(r))}}function Xt(e){const t=[];let r=-1,n=0,a=0;for(;++r<e.length;){const s=e.charCodeAt(r);let i="";if(s===37&&Ne(e.charCodeAt(r+1))&&Ne(e.charCodeAt(r+2)))a=2;else if(s<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(s))||(i=String.fromCharCode(s));else if(s>55295&&s<57344){const o=e.charCodeAt(r+1);s<56320&&o>56319&&o<57344?(i=String.fromCharCode(s,o),a=1):i="�"}else i=String.fromCharCode(s);i&&(t.push(e.slice(n,r),encodeURIComponent(i)),n=r+a+1,i=""),a&&(r+=a,a=0)}return t.join("")+e.slice(n)}function se(e,t,r,n){const a=n?n-1:Number.POSITIVE_INFINITY;let s=0;return i;function i(l){return te(l)?(e.enter(r),o(l)):t(l)}function o(l){return te(l)&&s++<a?(e.consume(l),o):(e.exit(r),t(l))}}const Sm={tokenize:_m};function _m(e){const t=e.attempt(this.parser.constructs.contentInitial,n,a);let r;return t;function n(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),se(e,t,"linePrefix")}function a(o){return e.enter("paragraph"),s(o)}function s(o){const l=e.enter("chunkText",{contentType:"text",previous:r});return r&&(r.next=l),r=l,i(o)}function i(o){if(o===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(o);return}return W(o)?(e.consume(o),e.exit("chunkText"),s):(e.consume(o),i)}}const Tm={tokenize:Cm},ll={tokenize:Im};function Cm(e){const t=this,r=[];let n=0,a,s,i;return o;function o(_){if(n<r.length){const O=r[n];return t.containerState=O[1],e.attempt(O[0].continuation,l,u)(_)}return u(_)}function l(_){if(n++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,a&&E();const O=t.events.length;let z=O,C;for(;z--;)if(t.events[z][0]==="exit"&&t.events[z][1].type==="chunkFlow"){C=t.events[z][1].end;break}y(n);let U=O;for(;U<t.events.length;)t.events[U][1].end=m({},C),U++;return qe(t.events,z+1,0,t.events.slice(O)),t.events.length=U,u(_)}return o(_)}function u(_){if(n===r.length){if(!a)return f(_);if(a.currentConstruct&&a.currentConstruct.concrete)return g(_);t.interrupt=!!(a.currentConstruct&&!a._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(ll,d,c)(_)}function d(_){return a&&E(),y(n),f(_)}function c(_){return t.parser.lazy[t.now().line]=n!==r.length,i=t.now().offset,g(_)}function f(_){return t.containerState={},e.attempt(ll,h,g)(_)}function h(_){return n++,r.push([t.currentConstruct,t.containerState]),f(_)}function g(_){if(_===null){a&&E(),y(0),e.consume(_);return}return a=a||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:a,contentType:"flow",previous:s}),w(_)}function w(_){if(_===null){x(e.exit("chunkFlow"),!0),y(0),e.consume(_);return}return W(_)?(e.consume(_),x(e.exit("chunkFlow")),n=0,t.interrupt=void 0,o):(e.consume(_),w)}function x(_,O){const z=t.sliceStream(_);if(O&&z.push(null),_.previous=s,s&&(s.next=_),s=_,a.defineSkip(_.start),a.write(z),t.parser.lazy[_.start.line]){let C=a.events.length;for(;C--;)if(a.events[C][1].start.offset<i&&(!a.events[C][1].end||a.events[C][1].end.offset>i))return;const U=t.events.length;let V=U,R,S;for(;V--;)if(t.events[V][0]==="exit"&&t.events[V][1].type==="chunkFlow"){if(R){S=t.events[V][1].end;break}R=!0}for(y(n),C=U;C<t.events.length;)t.events[C][1].end=m({},S),C++;qe(t.events,V+1,0,t.events.slice(U)),t.events.length=C}}function y(_){let O=r.length;for(;O-- >_;){const z=r[O];t.containerState=z[1],z[0].exit.call(t,e)}r.length=_}function E(){a.write([null]),s=void 0,a=void 0,t.containerState._closeFlow=void 0}}function Im(e,t,r){return se(e,e.attempt(this.parser.constructs.document,t,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Qt(e){if(e===null||de(e)||Pt(e))return 1;if(dn(e))return 2}function hn(e,t,r){const n=[];let a=-1;for(;++a<e.length;){const s=e[a].resolveAll;s&&!n.includes(s)&&(t=s(t,r),n.push(s))}return t}const Da={name:"attention",resolveAll:Em,tokenize:Am};function Em(e,t){let r=-1,n,a,s,i,o,l,u,d;for(;++r<e.length;)if(e[r][0]==="enter"&&e[r][1].type==="attentionSequence"&&e[r][1]._close){for(n=r;n--;)if(e[n][0]==="exit"&&e[n][1].type==="attentionSequence"&&e[n][1]._open&&t.sliceSerialize(e[n][1]).charCodeAt(0)===t.sliceSerialize(e[r][1]).charCodeAt(0)){if((e[n][1]._close||e[r][1]._open)&&(e[r][1].end.offset-e[r][1].start.offset)%3&&!((e[n][1].end.offset-e[n][1].start.offset+e[r][1].end.offset-e[r][1].start.offset)%3))continue;l=e[n][1].end.offset-e[n][1].start.offset>1&&e[r][1].end.offset-e[r][1].start.offset>1?2:1;const c=m({},e[n][1].end),f=m({},e[r][1].start);ul(c,-l),ul(f,l),i={type:l>1?"strongSequence":"emphasisSequence",start:c,end:m({},e[n][1].end)},o={type:l>1?"strongSequence":"emphasisSequence",start:m({},e[r][1].start),end:f},s={type:l>1?"strongText":"emphasisText",start:m({},e[n][1].end),end:m({},e[r][1].start)},a={type:l>1?"strong":"emphasis",start:m({},i.start),end:m({},o.end)},e[n][1].end=m({},i.start),e[r][1].start=m({},o.end),u=[],e[n][1].end.offset-e[n][1].start.offset&&(u=Je(u,[["enter",e[n][1],t],["exit",e[n][1],t]])),u=Je(u,[["enter",a,t],["enter",i,t],["exit",i,t],["enter",s,t]]),u=Je(u,hn(t.parser.constructs.insideSpan.null,e.slice(n+1,r),t)),u=Je(u,[["exit",s,t],["enter",o,t],["exit",o,t],["exit",a,t]]),e[r][1].end.offset-e[r][1].start.offset?(d=2,u=Je(u,[["enter",e[r][1],t],["exit",e[r][1],t]])):d=0,qe(e,n-1,r-n+3,u),r=n+u.length-d-2;break}}for(r=-1;++r<e.length;)e[r][1].type==="attentionSequence"&&(e[r][1].type="data");return e}function Am(e,t){const r=this.parser.constructs.attentionMarkers.null,n=this.previous,a=Qt(n);let s;return i;function i(l){return s=l,e.enter("attentionSequence"),o(l)}function o(l){if(l===s)return e.consume(l),o;const u=e.exit("attentionSequence"),d=Qt(l),c=!d||d===2&&a||r.includes(l),f=!a||a===2&&d||r.includes(n);return u._open=!!(s===42?c:c&&(a||!f)),u._close=!!(s===42?f:f&&(d||!c)),t(l)}}function ul(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const Mm={name:"autolink",tokenize:Pm};function Pm(e,t,r){let n=0;return a;function a(h){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),s}function s(h){return Fe(h)?(e.consume(h),i):h===64?r(h):u(h)}function i(h){return h===43||h===45||h===46||Ne(h)?(n=1,o(h)):u(h)}function o(h){return h===58?(e.consume(h),n=0,l):(h===43||h===45||h===46||Ne(h))&&n++<32?(e.consume(h),o):(n=0,u(h))}function l(h){return h===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):h===null||h===32||h===60||cn(h)?r(h):(e.consume(h),l)}function u(h){return h===64?(e.consume(h),d):wm(h)?(e.consume(h),u):r(h)}function d(h){return Ne(h)?c(h):r(h)}function c(h){return h===46?(e.consume(h),n=0,d):h===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):f(h)}function f(h){if((h===45||Ne(h))&&n++<63){const g=h===45?f:c;return e.consume(h),g}return r(h)}}const kr={partial:!0,tokenize:Nm};function Nm(e,t,r){return n;function n(s){return te(s)?se(e,a,"linePrefix")(s):a(s)}function a(s){return s===null||W(s)?t(s):r(s)}}const cl={continuation:{tokenize:Dm},exit:Om,name:"blockQuote",tokenize:Lm};function Lm(e,t,r){const n=this;return a;function a(i){if(i===62){const o=n.containerState;return o.open||(e.enter("blockQuote",{_container:!0}),o.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(i),e.exit("blockQuoteMarker"),s}return r(i)}function s(i){return te(i)?(e.enter("blockQuotePrefixWhitespace"),e.consume(i),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(i))}}function Dm(e,t,r){const n=this;return a;function a(i){return te(i)?se(e,s,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(i):s(i)}function s(i){return e.attempt(cl,t,r)(i)}}function Om(e){e.exit("blockQuote")}const dl={name:"characterEscape",tokenize:Fm};function Fm(e,t,r){return n;function n(s){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(s),e.exit("escapeMarker"),a}function a(s){return km(s)?(e.enter("characterEscapeValue"),e.consume(s),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):r(s)}}const hl={name:"characterReference",tokenize:zm};function zm(e,t,r){const n=this;let a=0,s,i;return o;function o(c){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(c),e.exit("characterReferenceMarker"),l}function l(c){return c===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(c),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),s=31,i=Ne,d(c))}function u(c){return c===88||c===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(c),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),s=6,i=vm,d):(e.enter("characterReferenceValue"),s=7,i=La,d(c))}function d(c){if(c===59&&a){const f=e.exit("characterReferenceValue");return i===Ne&&!Na(n.sliceSerialize(f))?r(c):(e.enter("characterReferenceMarker"),e.consume(c),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return i(c)&&a++<s?(e.consume(c),d):r(c)}}const fl={partial:!0,tokenize:Rm},pl={concrete:!0,name:"codeFenced",tokenize:Bm};function Bm(e,t,r){const n=this,a={partial:!0,tokenize:z};let s=0,i=0,o;return l;function l(C){return u(C)}function u(C){const U=n.events[n.events.length-1];return s=U&&U[1].type==="linePrefix"?U[2].sliceSerialize(U[1],!0).length:0,o=C,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),d(C)}function d(C){return C===o?(i++,e.consume(C),d):i<3?r(C):(e.exit("codeFencedFenceSequence"),te(C)?se(e,c,"whitespace")(C):c(C))}function c(C){return C===null||W(C)?(e.exit("codeFencedFence"),n.interrupt?t(C):e.check(fl,w,O)(C)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(C))}function f(C){return C===null||W(C)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),c(C)):te(C)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),se(e,h,"whitespace")(C)):C===96&&C===o?r(C):(e.consume(C),f)}function h(C){return C===null||W(C)?c(C):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(C))}function g(C){return C===null||W(C)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),c(C)):C===96&&C===o?r(C):(e.consume(C),g)}function w(C){return e.attempt(a,O,x)(C)}function x(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),y}function y(C){return s>0&&te(C)?se(e,E,"linePrefix",s+1)(C):E(C)}function E(C){return C===null||W(C)?e.check(fl,w,O)(C):(e.enter("codeFlowValue"),_(C))}function _(C){return C===null||W(C)?(e.exit("codeFlowValue"),E(C)):(e.consume(C),_)}function O(C){return e.exit("codeFenced"),t(C)}function z(C,U,V){let R=0;return S;function S(P){return C.enter("lineEnding"),C.consume(P),C.exit("lineEnding"),D}function D(P){return C.enter("codeFencedFence"),te(P)?se(C,N,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):N(P)}function N(P){return P===o?(C.enter("codeFencedFenceSequence"),K(P)):V(P)}function K(P){return P===o?(R++,C.consume(P),K):R>=i?(C.exit("codeFencedFenceSequence"),te(P)?se(C,B,"whitespace")(P):B(P)):V(P)}function B(P){return P===null||W(P)?(C.exit("codeFencedFence"),U(P)):V(P)}}}function Rm(e,t,r){const n=this;return a;function a(i){return i===null?r(i):(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),s)}function s(i){return n.parser.lazy[n.now().line]?r(i):t(i)}}const Oa={name:"codeIndented",tokenize:$m},jm={partial:!0,tokenize:Um};function $m(e,t,r){const n=this;return a;function a(u){return e.enter("codeIndented"),se(e,s,"linePrefix",5)(u)}function s(u){const d=n.events[n.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?i(u):r(u)}function i(u){return u===null?l(u):W(u)?e.attempt(jm,i,l)(u):(e.enter("codeFlowValue"),o(u))}function o(u){return u===null||W(u)?(e.exit("codeFlowValue"),i(u)):(e.consume(u),o)}function l(u){return e.exit("codeIndented"),t(u)}}function Um(e,t,r){const n=this;return a;function a(i){return n.parser.lazy[n.now().line]?r(i):W(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),a):se(e,s,"linePrefix",5)(i)}function s(i){const o=n.events[n.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(i):W(i)?a(i):r(i)}}const Hm={name:"codeText",previous:Vm,resolve:qm,tokenize:Wm};function qm(e){let t=e.length-4,r=3,n,a;if((e[r][1].type==="lineEnding"||e[r][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(n=r;++n<t;)if(e[n][1].type==="codeTextData"){e[r][1].type="codeTextPadding",e[t][1].type="codeTextPadding",r+=2,t-=2;break}}for(n=r-1,t++;++n<=t;)a===void 0?n!==t&&e[n][1].type!=="lineEnding"&&(a=n):(n===t||e[n][1].type==="lineEnding")&&(e[a][1].type="codeTextData",n!==a+2&&(e[a][1].end=e[n-1][1].end,e.splice(a+2,n-a-2),t-=n-a-2,n=a+2),a=void 0);return e}function Vm(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Wm(e,t,r){let n=0,a,s;return i;function i(c){return e.enter("codeText"),e.enter("codeTextSequence"),o(c)}function o(c){return c===96?(e.consume(c),n++,o):(e.exit("codeTextSequence"),l(c))}function l(c){return c===null?r(c):c===32?(e.enter("space"),e.consume(c),e.exit("space"),l):c===96?(s=e.enter("codeTextSequence"),a=0,d(c)):W(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),l):(e.enter("codeTextData"),u(c))}function u(c){return c===null||c===32||c===96||W(c)?(e.exit("codeTextData"),l(c)):(e.consume(c),u)}function d(c){return c===96?(e.consume(c),a++,d):a===n?(e.exit("codeTextSequence"),e.exit("codeText"),t(c)):(s.type="codeTextData",u(c))}}class Jm{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,r){const n=r==null?Number.POSITIVE_INFINITY:r;return n<this.left.length?this.left.slice(t,n):t>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(t,r,n){const a=r||0;this.setCursor(Math.trunc(t));const s=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return n&&Sr(this.left,n),s.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),Sr(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Sr(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const r=this.left.splice(t,Number.POSITIVE_INFINITY);Sr(this.right,r.reverse())}else{const r=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);Sr(this.left,r.reverse())}}}function Sr(e,t){let r=0;if(t.length<1e4)e.push(...t);else for(;r<t.length;)e.push(...t.slice(r,r+1e4)),r+=1e4}function ml(e){const t={};let r=-1,n,a,s,i,o,l,u;const d=new Jm(e);for(;++r<d.length;){for(;r in t;)r=t[r];if(n=d.get(r),r&&n[1].type==="chunkFlow"&&d.get(r-1)[1].type==="listItemPrefix"&&(l=n[1]._tokenizer.events,s=0,s<l.length&&l[s][1].type==="lineEndingBlank"&&(s+=2),s<l.length&&l[s][1].type==="content"))for(;++s<l.length&&l[s][1].type!=="content";)l[s][1].type==="chunkText"&&(l[s][1]._isInFirstContentOfListItem=!0,s++);if(n[0]==="enter")n[1].contentType&&(Object.assign(t,Km(d,r)),r=t[r],u=!0);else if(n[1]._container){for(s=r,a=void 0;s--;)if(i=d.get(s),i[1].type==="lineEnding"||i[1].type==="lineEndingBlank")i[0]==="enter"&&(a&&(d.get(a)[1].type="lineEndingBlank"),i[1].type="lineEnding",a=s);else if(!(i[1].type==="linePrefix"||i[1].type==="listItemIndent"))break;a&&(n[1].end=m({},d.get(a)[1].start),o=d.slice(a,r),o.unshift(n),d.splice(a,r-a+1,o))}}return qe(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!u}function Km(e,t){const r=e.get(t)[1],n=e.get(t)[2];let a=t-1;const s=[];let i=r._tokenizer;i||(i=n.parser[r.contentType](r.start),r._contentTypeTextTrailing&&(i._contentTypeTextTrailing=!0));const o=i.events,l=[],u={};let d,c,f=-1,h=r,g=0,w=0;const x=[w];for(;h;){for(;e.get(++a)[1]!==h;);s.push(a),h._tokenizer||(d=n.sliceStream(h),h.next||d.push(null),c&&i.defineSkip(h.start),h._isInFirstContentOfListItem&&(i._gfmTasklistFirstContentOfListItem=!0),i.write(d),h._isInFirstContentOfListItem&&(i._gfmTasklistFirstContentOfListItem=void 0)),c=h,h=h.next}for(h=r;++f<o.length;)o[f][0]==="exit"&&o[f-1][0]==="enter"&&o[f][1].type===o[f-1][1].type&&o[f][1].start.line!==o[f][1].end.line&&(w=f+1,x.push(w),h._tokenizer=void 0,h.previous=void 0,h=h.next);for(i.events=[],h?(h._tokenizer=void 0,h.previous=void 0):x.pop(),f=x.length;f--;){const y=o.slice(x[f],x[f+1]),E=s.pop();l.push([E,E+y.length-1]),e.splice(E,2,y)}for(l.reverse(),f=-1;++f<l.length;)u[g+l[f][0]]=g+l[f][1],g+=l[f][1]-l[f][0]-1;return u}const Ym={resolve:Xm,tokenize:Qm},Gm={partial:!0,tokenize:Zm};function Xm(e){return ml(e),e}function Qm(e,t){let r;return n;function n(o){return e.enter("content"),r=e.enter("chunkContent",{contentType:"content"}),a(o)}function a(o){return o===null?s(o):W(o)?e.check(Gm,i,s)(o):(e.consume(o),a)}function s(o){return e.exit("chunkContent"),e.exit("content"),t(o)}function i(o){return e.consume(o),e.exit("chunkContent"),r.next=e.enter("chunkContent",{contentType:"content",previous:r}),r=r.next,a}}function Zm(e,t,r){const n=this;return a;function a(i){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),se(e,s,"linePrefix")}function s(i){if(i===null||W(i))return r(i);const o=n.events[n.events.length-1];return!n.parser.constructs.disable.null.includes("codeIndented")&&o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(i):e.interrupt(n.parser.constructs.flow,r,t)(i)}}function gl(e,t,r,n,a,s,i,o,l){const u=l||Number.POSITIVE_INFINITY;let d=0;return c;function c(y){return y===60?(e.enter(n),e.enter(a),e.enter(s),e.consume(y),e.exit(s),f):y===null||y===32||y===41||cn(y)?r(y):(e.enter(n),e.enter(i),e.enter(o),e.enter("chunkString",{contentType:"string"}),w(y))}function f(y){return y===62?(e.enter(s),e.consume(y),e.exit(s),e.exit(a),e.exit(n),t):(e.enter(o),e.enter("chunkString",{contentType:"string"}),h(y))}function h(y){return y===62?(e.exit("chunkString"),e.exit(o),f(y)):y===null||y===60||W(y)?r(y):(e.consume(y),y===92?g:h)}function g(y){return y===60||y===62||y===92?(e.consume(y),h):h(y)}function w(y){return!d&&(y===null||y===41||de(y))?(e.exit("chunkString"),e.exit(o),e.exit(i),e.exit(n),t(y)):d<u&&y===40?(e.consume(y),d++,w):y===41?(e.consume(y),d--,w):y===null||y===32||y===40||cn(y)?r(y):(e.consume(y),y===92?x:w)}function x(y){return y===40||y===41||y===92?(e.consume(y),w):w(y)}}function yl(e,t,r,n,a,s){const i=this;let o=0,l;return u;function u(h){return e.enter(n),e.enter(a),e.consume(h),e.exit(a),e.enter(s),d}function d(h){return o>999||h===null||h===91||h===93&&!l||h===94&&!o&&"_hiddenFootnoteSupport"in i.parser.constructs?r(h):h===93?(e.exit(s),e.enter(a),e.consume(h),e.exit(a),e.exit(n),t):W(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),c(h))}function c(h){return h===null||h===91||h===93||W(h)||o++>999?(e.exit("chunkString"),d(h)):(e.consume(h),l||(l=!te(h)),h===92?f:c)}function f(h){return h===91||h===92||h===93?(e.consume(h),o++,c):c(h)}}function bl(e,t,r,n,a,s){let i;return o;function o(f){return f===34||f===39||f===40?(e.enter(n),e.enter(a),e.consume(f),e.exit(a),i=f===40?41:f,l):r(f)}function l(f){return f===i?(e.enter(a),e.consume(f),e.exit(a),e.exit(n),t):(e.enter(s),u(f))}function u(f){return f===i?(e.exit(s),l(i)):f===null?r(f):W(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),se(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(f))}function d(f){return f===i||f===null||W(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?c:d)}function c(f){return f===i||f===92?(e.consume(f),d):d(f)}}function _r(e,t){let r;return n;function n(a){return W(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),r=!0,n):te(a)?se(e,n,r?"linePrefix":"lineSuffix")(a):t(a)}}const eg={name:"definition",tokenize:rg},tg={partial:!0,tokenize:ng};function rg(e,t,r){const n=this;let a;return s;function s(h){return e.enter("definition"),i(h)}function i(h){return yl.call(n,e,o,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(h)}function o(h){return a=et(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)),h===58?(e.enter("definitionMarker"),e.consume(h),e.exit("definitionMarker"),l):r(h)}function l(h){return de(h)?_r(e,u)(h):u(h)}function u(h){return gl(e,d,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(h)}function d(h){return e.attempt(tg,c,c)(h)}function c(h){return te(h)?se(e,f,"whitespace")(h):f(h)}function f(h){return h===null||W(h)?(e.exit("definition"),n.parser.defined.push(a),t(h)):r(h)}}function ng(e,t,r){return n;function n(o){return de(o)?_r(e,a)(o):r(o)}function a(o){return bl(e,s,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function s(o){return te(o)?se(e,i,"whitespace")(o):i(o)}function i(o){return o===null||W(o)?t(o):r(o)}}const ag={name:"hardBreakEscape",tokenize:sg};function sg(e,t,r){return n;function n(s){return e.enter("hardBreakEscape"),e.consume(s),a}function a(s){return W(s)?(e.exit("hardBreakEscape"),t(s)):r(s)}}const ig={name:"headingAtx",resolve:og,tokenize:lg};function og(e,t){let r=e.length-2,n=3,a,s;return e[n][1].type==="whitespace"&&(n+=2),r-2>n&&e[r][1].type==="whitespace"&&(r-=2),e[r][1].type==="atxHeadingSequence"&&(n===r-1||r-4>n&&e[r-2][1].type==="whitespace")&&(r-=n+1===r?2:4),r>n&&(a={type:"atxHeadingText",start:e[n][1].start,end:e[r][1].end},s={type:"chunkText",start:e[n][1].start,end:e[r][1].end,contentType:"text"},qe(e,n,r-n+1,[["enter",a,t],["enter",s,t],["exit",s,t],["exit",a,t]])),e}function lg(e,t,r){let n=0;return a;function a(d){return e.enter("atxHeading"),s(d)}function s(d){return e.enter("atxHeadingSequence"),i(d)}function i(d){return d===35&&n++<6?(e.consume(d),i):d===null||de(d)?(e.exit("atxHeadingSequence"),o(d)):r(d)}function o(d){return d===35?(e.enter("atxHeadingSequence"),l(d)):d===null||W(d)?(e.exit("atxHeading"),t(d)):te(d)?se(e,o,"whitespace")(d):(e.enter("atxHeadingText"),u(d))}function l(d){return d===35?(e.consume(d),l):(e.exit("atxHeadingSequence"),o(d))}function u(d){return d===null||d===35||de(d)?(e.exit("atxHeadingText"),o(d)):(e.consume(d),u)}}const ug=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],xl=["pre","script","style","textarea"],cg={concrete:!0,name:"htmlFlow",resolveTo:fg,tokenize:pg},dg={partial:!0,tokenize:gg},hg={partial:!0,tokenize:mg};function fg(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function pg(e,t,r){const n=this;let a,s,i,o,l;return u;function u(k){return d(k)}function d(k){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(k),c}function c(k){return k===33?(e.consume(k),f):k===47?(e.consume(k),s=!0,w):k===63?(e.consume(k),a=3,n.interrupt?t:v):Fe(k)?(e.consume(k),i=String.fromCharCode(k),x):r(k)}function f(k){return k===45?(e.consume(k),a=2,h):k===91?(e.consume(k),a=5,o=0,g):Fe(k)?(e.consume(k),a=4,n.interrupt?t:v):r(k)}function h(k){return k===45?(e.consume(k),n.interrupt?t:v):r(k)}function g(k){const Se="CDATA[";return k===Se.charCodeAt(o++)?(e.consume(k),o===Se.length?n.interrupt?t:N:g):r(k)}function w(k){return Fe(k)?(e.consume(k),i=String.fromCharCode(k),x):r(k)}function x(k){if(k===null||k===47||k===62||de(k)){const Se=k===47,Ye=i.toLowerCase();return!Se&&!s&&xl.includes(Ye)?(a=1,n.interrupt?t(k):N(k)):ug.includes(i.toLowerCase())?(a=6,Se?(e.consume(k),y):n.interrupt?t(k):N(k)):(a=7,n.interrupt&&!n.parser.lazy[n.now().line]?r(k):s?E(k):_(k))}return k===45||Ne(k)?(e.consume(k),i+=String.fromCharCode(k),x):r(k)}function y(k){return k===62?(e.consume(k),n.interrupt?t:N):r(k)}function E(k){return te(k)?(e.consume(k),E):S(k)}function _(k){return k===47?(e.consume(k),S):k===58||k===95||Fe(k)?(e.consume(k),O):te(k)?(e.consume(k),_):S(k)}function O(k){return k===45||k===46||k===58||k===95||Ne(k)?(e.consume(k),O):z(k)}function z(k){return k===61?(e.consume(k),C):te(k)?(e.consume(k),z):_(k)}function C(k){return k===null||k===60||k===61||k===62||k===96?r(k):k===34||k===39?(e.consume(k),l=k,U):te(k)?(e.consume(k),C):V(k)}function U(k){return k===l?(e.consume(k),l=null,R):k===null||W(k)?r(k):(e.consume(k),U)}function V(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||de(k)?z(k):(e.consume(k),V)}function R(k){return k===47||k===62||te(k)?_(k):r(k)}function S(k){return k===62?(e.consume(k),D):r(k)}function D(k){return k===null||W(k)?N(k):te(k)?(e.consume(k),D):r(k)}function N(k){return k===45&&a===2?(e.consume(k),q):k===60&&a===1?(e.consume(k),J):k===62&&a===4?(e.consume(k),Y):k===63&&a===3?(e.consume(k),v):k===93&&a===5?(e.consume(k),ie):W(k)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(dg,we,K)(k)):k===null||W(k)?(e.exit("htmlFlowData"),K(k)):(e.consume(k),N)}function K(k){return e.check(hg,B,we)(k)}function B(k){return e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),P}function P(k){return k===null||W(k)?K(k):(e.enter("htmlFlowData"),N(k))}function q(k){return k===45?(e.consume(k),v):N(k)}function J(k){return k===47?(e.consume(k),i="",ue):N(k)}function ue(k){if(k===62){const Se=i.toLowerCase();return xl.includes(Se)?(e.consume(k),Y):N(k)}return Fe(k)&&i.length<8?(e.consume(k),i+=String.fromCharCode(k),ue):N(k)}function ie(k){return k===93?(e.consume(k),v):N(k)}function v(k){return k===62?(e.consume(k),Y):k===45&&a===2?(e.consume(k),v):N(k)}function Y(k){return k===null||W(k)?(e.exit("htmlFlowData"),we(k)):(e.consume(k),Y)}function we(k){return e.exit("htmlFlow"),t(k)}}function mg(e,t,r){const n=this;return a;function a(i){return W(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),s):r(i)}function s(i){return n.parser.lazy[n.now().line]?r(i):t(i)}}function gg(e,t,r){return n;function n(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(kr,t,r)}}const yg={name:"htmlText",tokenize:bg};function bg(e,t,r){const n=this;let a,s,i;return o;function o(v){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(v),l}function l(v){return v===33?(e.consume(v),u):v===47?(e.consume(v),z):v===63?(e.consume(v),_):Fe(v)?(e.consume(v),V):r(v)}function u(v){return v===45?(e.consume(v),d):v===91?(e.consume(v),s=0,g):Fe(v)?(e.consume(v),E):r(v)}function d(v){return v===45?(e.consume(v),h):r(v)}function c(v){return v===null?r(v):v===45?(e.consume(v),f):W(v)?(i=c,J(v)):(e.consume(v),c)}function f(v){return v===45?(e.consume(v),h):c(v)}function h(v){return v===62?q(v):v===45?f(v):c(v)}function g(v){const Y="CDATA[";return v===Y.charCodeAt(s++)?(e.consume(v),s===Y.length?w:g):r(v)}function w(v){return v===null?r(v):v===93?(e.consume(v),x):W(v)?(i=w,J(v)):(e.consume(v),w)}function x(v){return v===93?(e.consume(v),y):w(v)}function y(v){return v===62?q(v):v===93?(e.consume(v),y):w(v)}function E(v){return v===null||v===62?q(v):W(v)?(i=E,J(v)):(e.consume(v),E)}function _(v){return v===null?r(v):v===63?(e.consume(v),O):W(v)?(i=_,J(v)):(e.consume(v),_)}function O(v){return v===62?q(v):_(v)}function z(v){return Fe(v)?(e.consume(v),C):r(v)}function C(v){return v===45||Ne(v)?(e.consume(v),C):U(v)}function U(v){return W(v)?(i=U,J(v)):te(v)?(e.consume(v),U):q(v)}function V(v){return v===45||Ne(v)?(e.consume(v),V):v===47||v===62||de(v)?R(v):r(v)}function R(v){return v===47?(e.consume(v),q):v===58||v===95||Fe(v)?(e.consume(v),S):W(v)?(i=R,J(v)):te(v)?(e.consume(v),R):q(v)}function S(v){return v===45||v===46||v===58||v===95||Ne(v)?(e.consume(v),S):D(v)}function D(v){return v===61?(e.consume(v),N):W(v)?(i=D,J(v)):te(v)?(e.consume(v),D):R(v)}function N(v){return v===null||v===60||v===61||v===62||v===96?r(v):v===34||v===39?(e.consume(v),a=v,K):W(v)?(i=N,J(v)):te(v)?(e.consume(v),N):(e.consume(v),B)}function K(v){return v===a?(e.consume(v),a=void 0,P):v===null?r(v):W(v)?(i=K,J(v)):(e.consume(v),K)}function B(v){return v===null||v===34||v===39||v===60||v===61||v===96?r(v):v===47||v===62||de(v)?R(v):(e.consume(v),B)}function P(v){return v===47||v===62||de(v)?R(v):r(v)}function q(v){return v===62?(e.consume(v),e.exit("htmlTextData"),e.exit("htmlText"),t):r(v)}function J(v){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),ue}function ue(v){return te(v)?se(e,ie,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(v):ie(v)}function ie(v){return e.enter("htmlTextData"),i(v)}}const Fa={name:"labelEnd",resolveAll:kg,resolveTo:Sg,tokenize:_g},xg={tokenize:Tg},wg={tokenize:Cg},vg={tokenize:Ig};function kg(e){let t=-1;const r=[];for(;++t<e.length;){const n=e[t][1];if(r.push(e[t]),n.type==="labelImage"||n.type==="labelLink"||n.type==="labelEnd"){const a=n.type==="labelImage"?4:2;n.type="data",t+=a}}return e.length!==r.length&&qe(e,0,e.length,r),e}function Sg(e,t){let r=e.length,n=0,a,s,i,o;for(;r--;)if(a=e[r][1],s){if(a.type==="link"||a.type==="labelLink"&&a._inactive)break;e[r][0]==="enter"&&a.type==="labelLink"&&(a._inactive=!0)}else if(i){if(e[r][0]==="enter"&&(a.type==="labelImage"||a.type==="labelLink")&&!a._balanced&&(s=r,a.type!=="labelLink")){n=2;break}}else a.type==="labelEnd"&&(i=r);const l={type:e[s][1].type==="labelLink"?"link":"image",start:m({},e[s][1].start),end:m({},e[e.length-1][1].end)},u={type:"label",start:m({},e[s][1].start),end:m({},e[i][1].end)},d={type:"labelText",start:m({},e[s+n+2][1].end),end:m({},e[i-2][1].start)};return o=[["enter",l,t],["enter",u,t]],o=Je(o,e.slice(s+1,s+n+3)),o=Je(o,[["enter",d,t]]),o=Je(o,hn(t.parser.constructs.insideSpan.null,e.slice(s+n+4,i-3),t)),o=Je(o,[["exit",d,t],e[i-2],e[i-1],["exit",u,t]]),o=Je(o,e.slice(i+1)),o=Je(o,[["exit",l,t]]),qe(e,s,e.length,o),e}function _g(e,t,r){const n=this;let a=n.events.length,s,i;for(;a--;)if((n.events[a][1].type==="labelImage"||n.events[a][1].type==="labelLink")&&!n.events[a][1]._balanced){s=n.events[a][1];break}return o;function o(f){return s?s._inactive?c(f):(i=n.parser.defined.includes(et(n.sliceSerialize({start:s.end,end:n.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelEnd"),l):r(f)}function l(f){return f===40?e.attempt(xg,d,i?d:c)(f):f===91?e.attempt(wg,d,i?u:c)(f):i?d(f):c(f)}function u(f){return e.attempt(vg,d,c)(f)}function d(f){return t(f)}function c(f){return s._balanced=!0,r(f)}}function Tg(e,t,r){return n;function n(c){return e.enter("resource"),e.enter("resourceMarker"),e.consume(c),e.exit("resourceMarker"),a}function a(c){return de(c)?_r(e,s)(c):s(c)}function s(c){return c===41?d(c):gl(e,i,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(c)}function i(c){return de(c)?_r(e,l)(c):d(c)}function o(c){return r(c)}function l(c){return c===34||c===39||c===40?bl(e,u,r,"resourceTitle","resourceTitleMarker","resourceTitleString")(c):d(c)}function u(c){return de(c)?_r(e,d)(c):d(c)}function d(c){return c===41?(e.enter("resourceMarker"),e.consume(c),e.exit("resourceMarker"),e.exit("resource"),t):r(c)}}function Cg(e,t,r){const n=this;return a;function a(o){return yl.call(n,e,s,i,"reference","referenceMarker","referenceString")(o)}function s(o){return n.parser.defined.includes(et(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)))?t(o):r(o)}function i(o){return r(o)}}function Ig(e,t,r){return n;function n(s){return e.enter("reference"),e.enter("referenceMarker"),e.consume(s),e.exit("referenceMarker"),a}function a(s){return s===93?(e.enter("referenceMarker"),e.consume(s),e.exit("referenceMarker"),e.exit("reference"),t):r(s)}}const Eg={name:"labelStartImage",resolveAll:Fa.resolveAll,tokenize:Ag};function Ag(e,t,r){const n=this;return a;function a(o){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(o),e.exit("labelImageMarker"),s}function s(o){return o===91?(e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelImage"),i):r(o)}function i(o){return o===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(o):t(o)}}const Mg={name:"labelStartLink",resolveAll:Fa.resolveAll,tokenize:Pg};function Pg(e,t,r){const n=this;return a;function a(i){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(i),e.exit("labelMarker"),e.exit("labelLink"),s}function s(i){return i===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(i):t(i)}}const za={name:"lineEnding",tokenize:Ng};function Ng(e,t){return r;function r(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),se(e,t,"linePrefix")}}const fn={name:"thematicBreak",tokenize:Lg};function Lg(e,t,r){let n=0,a;return s;function s(u){return e.enter("thematicBreak"),i(u)}function i(u){return a=u,o(u)}function o(u){return u===a?(e.enter("thematicBreakSequence"),l(u)):n>=3&&(u===null||W(u))?(e.exit("thematicBreak"),t(u)):r(u)}function l(u){return u===a?(e.consume(u),n++,l):(e.exit("thematicBreakSequence"),te(u)?se(e,o,"whitespace")(u):o(u))}}const je={continuation:{tokenize:zg},exit:Rg,name:"list",tokenize:Fg},Dg={partial:!0,tokenize:jg},Og={partial:!0,tokenize:Bg};function Fg(e,t,r){const n=this,a=n.events[n.events.length-1];let s=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,i=0;return o;function o(h){const g=n.containerState.type||(h===42||h===43||h===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!n.containerState.marker||h===n.containerState.marker:La(h)){if(n.containerState.type||(n.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),h===42||h===45?e.check(fn,r,u)(h):u(h);if(!n.interrupt||h===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),l(h)}return r(h)}function l(h){return La(h)&&++i<10?(e.consume(h),l):(!n.interrupt||i<2)&&(n.containerState.marker?h===n.containerState.marker:h===41||h===46)?(e.exit("listItemValue"),u(h)):r(h)}function u(h){return e.enter("listItemMarker"),e.consume(h),e.exit("listItemMarker"),n.containerState.marker=n.containerState.marker||h,e.check(kr,n.interrupt?r:d,e.attempt(Dg,f,c))}function d(h){return n.containerState.initialBlankLine=!0,s++,f(h)}function c(h){return te(h)?(e.enter("listItemPrefixWhitespace"),e.consume(h),e.exit("listItemPrefixWhitespace"),f):r(h)}function f(h){return n.containerState.size=s+n.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(h)}}function zg(e,t,r){const n=this;return n.containerState._closeFlow=void 0,e.check(kr,a,s);function a(o){return n.containerState.furtherBlankLines=n.containerState.furtherBlankLines||n.containerState.initialBlankLine,se(e,t,"listItemIndent",n.containerState.size+1)(o)}function s(o){return n.containerState.furtherBlankLines||!te(o)?(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,i(o)):(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,e.attempt(Og,t,i)(o))}function i(o){return n.containerState._closeFlow=!0,n.interrupt=void 0,se(e,e.attempt(je,t,r),"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function Bg(e,t,r){const n=this;return se(e,a,"listItemIndent",n.containerState.size+1);function a(s){const i=n.events[n.events.length-1];return i&&i[1].type==="listItemIndent"&&i[2].sliceSerialize(i[1],!0).length===n.containerState.size?t(s):r(s)}}function Rg(e){e.exit(this.containerState.type)}function jg(e,t,r){const n=this;return se(e,a,"listItemPrefixWhitespace",n.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(s){const i=n.events[n.events.length-1];return!te(s)&&i&&i[1].type==="listItemPrefixWhitespace"?t(s):r(s)}}const wl={name:"setextUnderline",resolveTo:$g,tokenize:Ug};function $g(e,t){let r=e.length,n,a,s;for(;r--;)if(e[r][0]==="enter"){if(e[r][1].type==="content"){n=r;break}e[r][1].type==="paragraph"&&(a=r)}else e[r][1].type==="content"&&e.splice(r,1),!s&&e[r][1].type==="definition"&&(s=r);const i={type:"setextHeading",start:m({},e[n][1].start),end:m({},e[e.length-1][1].end)};return e[a][1].type="setextHeadingText",s?(e.splice(a,0,["enter",i,t]),e.splice(s+1,0,["exit",e[n][1],t]),e[n][1].end=m({},e[s][1].end)):e[n][1]=i,e.push(["exit",i,t]),e}function Ug(e,t,r){const n=this;let a;return s;function s(u){let d=n.events.length,c;for(;d--;)if(n.events[d][1].type!=="lineEnding"&&n.events[d][1].type!=="linePrefix"&&n.events[d][1].type!=="content"){c=n.events[d][1].type==="paragraph";break}return!n.parser.lazy[n.now().line]&&(n.interrupt||c)?(e.enter("setextHeadingLine"),a=u,i(u)):r(u)}function i(u){return e.enter("setextHeadingLineSequence"),o(u)}function o(u){return u===a?(e.consume(u),o):(e.exit("setextHeadingLineSequence"),te(u)?se(e,l,"lineSuffix")(u):l(u))}function l(u){return u===null||W(u)?(e.exit("setextHeadingLine"),t(u)):r(u)}}const Hg={tokenize:qg};function qg(e){const t=this,r=e.attempt(kr,n,e.attempt(this.parser.constructs.flowInitial,a,se(e,e.attempt(this.parser.constructs.flow,a,e.attempt(Ym,a)),"linePrefix")));return r;function n(s){if(s===null){e.consume(s);return}return e.enter("lineEndingBlank"),e.consume(s),e.exit("lineEndingBlank"),t.currentConstruct=void 0,r}function a(s){if(s===null){e.consume(s);return}return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),t.currentConstruct=void 0,r}}const Vg={resolveAll:kl()},Wg=vl("string"),Jg=vl("text");function vl(e){return{resolveAll:kl(e==="text"?Kg:void 0),tokenize:t};function t(r){const n=this,a=this.parser.constructs[e],s=r.attempt(a,i,o);return i;function i(d){return u(d)?s(d):o(d)}function o(d){if(d===null){r.consume(d);return}return r.enter("data"),r.consume(d),l}function l(d){return u(d)?(r.exit("data"),s(d)):(r.consume(d),l)}function u(d){if(d===null)return!0;const c=a[d];let f=-1;if(c)for(;++f<c.length;){const h=c[f];if(!h.previous||h.previous.call(n,n.previous))return!0}return!1}}}function kl(e){return t;function t(r,n){let a=-1,s;for(;++a<=r.length;)s===void 0?r[a]&&r[a][1].type==="data"&&(s=a,a++):(!r[a]||r[a][1].type!=="data")&&(a!==s+2&&(r[s][1].end=r[a-1][1].end,r.splice(s+2,a-s-2),a=s+2),s=void 0);return e?e(r,n):r}}function Kg(e,t){let r=0;for(;++r<=e.length;)if((r===e.length||e[r][1].type==="lineEnding")&&e[r-1][1].type==="data"){const n=e[r-1][1],a=t.sliceStream(n);let s=a.length,i=-1,o=0,l;for(;s--;){const u=a[s];if(typeof u=="string"){for(i=u.length;u.charCodeAt(i-1)===32;)o++,i--;if(i)break;i=-1}else if(u===-2)l=!0,o++;else if(u!==-1){s++;break}}if(t._contentTypeTextTrailing&&r===e.length&&(o=0),o){const u={type:r===e.length||l||o<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:s?i:n.start._bufferIndex+i,_index:n.start._index+s,line:n.end.line,column:n.end.column-o,offset:n.end.offset-o},end:m({},n.end)};n.end=m({},u.start),n.start.offset===n.end.offset?Object.assign(n,u):(e.splice(r,0,["enter",u,t],["exit",u,t]),r+=2)}r++}return e}const Yg=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:{null:[42,95]},contentInitial:{91:eg},disable:{null:[]},document:{42:je,43:je,45:je,48:je,49:je,50:je,51:je,52:je,53:je,54:je,55:je,56:je,57:je,62:cl},flow:{35:ig,42:fn,45:[wl,fn],60:cg,61:wl,95:fn,96:pl,126:pl},flowInitial:{[-2]:Oa,[-1]:Oa,32:Oa},insideSpan:{null:[Da,Vg]},string:{38:hl,92:dl},text:{[-5]:za,[-4]:za,[-3]:za,33:Eg,38:hl,42:Da,60:[Mm,yg],91:Mg,92:[ag,dl],93:Fa,95:Da,96:Hm}},Symbol.toStringTag,{value:"Module"}));function Gg(e,t,r){let n={_bufferIndex:-1,_index:0,line:r&&r.line||1,column:r&&r.column||1,offset:r&&r.offset||0};const a={},s=[];let i=[],o=[];const l={attempt:U(z),check:U(C),consume:E,enter:_,exit:O,interrupt:U(C,{interrupt:!0})},u={code:null,containerState:{},defineSkip:w,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:h,write:c};let d=t.tokenize.call(u,l);return t.resolveAll&&s.push(t),u;function c(D){return i=Je(i,D),x(),i[i.length-1]!==null?[]:(V(t,0),u.events=hn(s,u.events,u),u.events)}function f(D,N){return Qg(h(D),N)}function h(D){return Xg(i,D)}function g(){const{_bufferIndex:D,_index:N,line:K,column:B,offset:P}=n;return{_bufferIndex:D,_index:N,line:K,column:B,offset:P}}function w(D){a[D.line]=D.column,S()}function x(){let D;for(;n._index<i.length;){const N=i[n._index];if(typeof N=="string")for(D=n._index,n._bufferIndex<0&&(n._bufferIndex=0);n._index===D&&n._bufferIndex<N.length;)y(N.charCodeAt(n._bufferIndex));else y(N)}}function y(D){d=d(D)}function E(D){W(D)?(n.line++,n.column=1,n.offset+=D===-3?2:1,S()):D!==-1&&(n.column++,n.offset++),n._bufferIndex<0?n._index++:(n._bufferIndex++,n._bufferIndex===i[n._index].length&&(n._bufferIndex=-1,n._index++)),u.previous=D}function _(D,N){const K=N||{};return K.type=D,K.start=g(),u.events.push(["enter",K,u]),o.push(K),K}function O(D){const N=o.pop();return N.end=g(),u.events.push(["exit",N,u]),N}function z(D,N){V(D,N.from)}function C(D,N){N.restore()}function U(D,N){return K;function K(B,P,q){let J,ue,ie,v;return Array.isArray(B)?we(B):"tokenize"in B?we([B]):Y(B);function Y(_e){return j;function j(re){const le=re!==null&&_e[re],oe=re!==null&&_e.null,Ee=[...Array.isArray(le)?le:le?[le]:[],...Array.isArray(oe)?oe:oe?[oe]:[]];return we(Ee)(re)}}function we(_e){return J=_e,ue=0,_e.length===0?q:k(_e[ue])}function k(_e){return j;function j(re){return v=R(),ie=_e,_e.partial||(u.currentConstruct=_e),_e.name&&u.parser.constructs.disable.null.includes(_e.name)?Ye():_e.tokenize.call(N?Object.assign(Object.create(u),N):u,l,Se,Ye)(re)}}function Se(_e){return D(ie,v),P}function Ye(_e){return v.restore(),++ue<J.length?k(J[ue]):q}}}function V(D,N){D.resolveAll&&!s.includes(D)&&s.push(D),D.resolve&&qe(u.events,N,u.events.length-N,D.resolve(u.events.slice(N),u)),D.resolveTo&&(u.events=D.resolveTo(u.events,u))}function R(){const D=g(),N=u.previous,K=u.currentConstruct,B=u.events.length,P=Array.from(o);return{from:B,restore:q};function q(){n=D,u.previous=N,u.currentConstruct=K,u.events.length=B,o=P,S()}}function S(){n.line in a&&n.column<2&&(n.column=a[n.line],n.offset+=a[n.line]-1)}}function Xg(e,t){const r=t.start._index,n=t.start._bufferIndex,a=t.end._index,s=t.end._bufferIndex;let i;if(r===a)i=[e[r].slice(n,s)];else{if(i=e.slice(r,a),n>-1){const o=i[0];typeof o=="string"?i[0]=o.slice(n):i.shift()}s>0&&i.push(e[a].slice(0,s))}return i}function Qg(e,t){let r=-1;const n=[];let a;for(;++r<e.length;){const s=e[r];let i;if(typeof s=="string")i=s;else switch(s){case-5:{i="\r";break}case-4:{i=`
|
|
9
|
+
`;break}case-3:{i=`\r
|
|
10
|
+
`;break}case-2:{i=t?" ":" ";break}case-1:{if(!t&&a)continue;i=" ";break}default:i=String.fromCharCode(s)}a=s===-2,n.push(i)}return n.join("")}function Zg(e){const n={constructs:il([Yg,...(e||{}).extensions||[]]),content:a(Sm),defined:[],document:a(Tm),flow:a(Hg),lazy:{},string:a(Wg),text:a(Jg)};return n;function a(s){return i;function i(o){return Gg(n,s,o)}}}function ey(e){for(;!ml(e););return e}const Sl=/[\0\t\n\r]/g;function ty(){let e=1,t="",r=!0,n;return a;function a(s,i,o){const l=[];let u,d,c,f,h;for(s=t+(typeof s=="string"?s.toString():new TextDecoder(i||void 0).decode(s)),c=0,t="",r&&(s.charCodeAt(0)===65279&&c++,r=void 0);c<s.length;){if(Sl.lastIndex=c,u=Sl.exec(s),f=u&&u.index!==void 0?u.index:s.length,h=s.charCodeAt(f),!u){t=s.slice(c);break}if(h===10&&c===f&&n)l.push(-3),n=void 0;else switch(n&&(l.push(-5),n=void 0),c<f&&(l.push(s.slice(c,f)),e+=f-c),h){case 0:{l.push(65533),e++;break}case 9:{for(d=Math.ceil(e/4)*4,l.push(-2);e++<d;)l.push(-1);break}case 10:{l.push(-4),e=1;break}default:n=!0,e=1}c=f+1}return o&&(n&&l.push(-5),t&&l.push(t),l.push(null)),l}}const ry=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function ny(e){return e.replace(ry,ay)}function ay(e,t,r){if(t)return t;if(r.charCodeAt(0)===35){const a=r.charCodeAt(1),s=a===120||a===88;return ol(r.slice(s?2:1),s?16:10)}return Na(r)||e}const _l={}.hasOwnProperty;function sy(e,t,r){return typeof t!="string"&&(r=t,t=void 0),iy(r)(ey(Zg(r).document().write(ty()(e,t,!0))))}function iy(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:s(G),autolinkProtocol:R,autolinkEmail:R,atxHeading:s(lt),blockQuote:s(oe),characterEscape:R,characterReference:R,codeFenced:s(Ee),codeFencedFenceInfo:i,codeFencedFenceMeta:i,codeIndented:s(Ee,i),codeText:s(ne,i),codeTextData:R,data:R,codeFlowValue:R,definition:s(xe),definitionDestinationString:i,definitionLabelString:i,definitionTitleString:i,emphasis:s(ot),hardBreakEscape:s(ht),hardBreakTrailing:s(ht),htmlFlow:s(St,i),htmlFlowData:R,htmlText:s(St,i),htmlTextData:R,image:s(ft),label:i,link:s(G),listItem:s(me),listItemValue:f,listOrdered:s(be,c),listUnordered:s(be),paragraph:s(Dt),reference:k,referenceString:i,resourceDestinationString:i,resourceTitleString:i,setextHeading:s(lt),strong:s(Tn),thematicBreak:s(Ev)},exit:{atxHeading:l(),atxHeadingSequence:z,autolink:l(),autolinkEmail:le,autolinkProtocol:re,blockQuote:l(),characterEscapeValue:S,characterReferenceMarkerHexadecimal:Ye,characterReferenceMarkerNumeric:Ye,characterReferenceValue:_e,characterReference:j,codeFenced:l(x),codeFencedFence:w,codeFencedFenceInfo:h,codeFencedFenceMeta:g,codeFlowValue:S,codeIndented:l(y),codeText:l(P),codeTextData:S,data:S,definition:l(),definitionDestinationString:O,definitionLabelString:E,definitionTitleString:_,emphasis:l(),hardBreakEscape:l(N),hardBreakTrailing:l(N),htmlFlow:l(K),htmlFlowData:S,htmlText:l(B),htmlTextData:S,image:l(J),label:ie,labelText:ue,lineEnding:D,link:l(q),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:Se,resourceDestinationString:v,resourceTitleString:Y,resource:we,setextHeading:l(V),setextHeadingLineSequence:U,setextHeadingText:C,strong:l(),thematicBreak:l()}};Tl(t,(e||{}).mdastExtensions||[]);const r={};return n;function n(A){let F={type:"root",children:[]};const X={stack:[F],tokenStack:[],config:t,enter:o,exit:u,buffer:i,resume:d,data:r},ae=[];let he=-1;for(;++he<A.length;)if(A[he][1].type==="listOrdered"||A[he][1].type==="listUnordered")if(A[he][0]==="enter")ae.push(he);else{const rt=ae.pop();he=a(A,rt,he)}for(he=-1;++he<A.length;){const rt=t[A[he][0]];_l.call(rt,A[he][1].type)&&rt[A[he][1].type].call(Object.assign({sliceSerialize:A[he][2].sliceSerialize},X),A[he][1])}if(X.tokenStack.length>0){const rt=X.tokenStack[X.tokenStack.length-1];(rt[1]||Cl).call(X,void 0,rt[0])}for(F.position={start:kt(A.length>0?A[0][1].start:{line:1,column:1,offset:0}),end:kt(A.length>0?A[A.length-2][1].end:{line:1,column:1,offset:0})},he=-1;++he<t.transforms.length;)F=t.transforms[he](F)||F;return F}function a(A,F,X){let ae=F-1,he=-1,rt=!1,Ot,pt,Lr,Dr;for(;++ae<=X;){const Ve=A[ae];switch(Ve[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Ve[0]==="enter"?he++:he--,Dr=void 0;break}case"lineEndingBlank":{Ve[0]==="enter"&&(Ot&&!Dr&&!he&&!Lr&&(Lr=ae),Dr=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Dr=void 0}if(!he&&Ve[0]==="enter"&&Ve[1].type==="listItemPrefix"||he===-1&&Ve[0]==="exit"&&(Ve[1].type==="listUnordered"||Ve[1].type==="listOrdered")){if(Ot){let rr=ae;for(pt=void 0;rr--;){const mt=A[rr];if(mt[1].type==="lineEnding"||mt[1].type==="lineEndingBlank"){if(mt[0]==="exit")continue;pt&&(A[pt][1].type="lineEndingBlank",rt=!0),mt[1].type="lineEnding",pt=rr}else if(!(mt[1].type==="linePrefix"||mt[1].type==="blockQuotePrefix"||mt[1].type==="blockQuotePrefixWhitespace"||mt[1].type==="blockQuoteMarker"||mt[1].type==="listItemIndent"))break}Lr&&(!pt||Lr<pt)&&(Ot._spread=!0),Ot.end=Object.assign({},pt?A[pt][1].start:Ve[1].end),A.splice(pt||ae,0,["exit",Ot,Ve[2]]),ae++,X++}if(Ve[1].type==="listItemPrefix"){const rr={type:"listItem",_spread:!1,start:Object.assign({},Ve[1].start),end:void 0};Ot=rr,A.splice(ae,0,["enter",rr,Ve[2]]),ae++,X++,Lr=void 0,Dr=!0}}}return A[F][1]._spread=rt,X}function s(A,F){return X;function X(ae){o.call(this,A(ae),ae),F&&F.call(this,ae)}}function i(){this.stack.push({type:"fragment",children:[]})}function o(A,F,X){this.stack[this.stack.length-1].children.push(A),this.stack.push(A),this.tokenStack.push([F,X||void 0]),A.position={start:kt(F.start),end:void 0}}function l(A){return F;function F(X){A&&A.call(this,X),u.call(this,X)}}function u(A,F){const X=this.stack.pop(),ae=this.tokenStack.pop();if(ae)ae[0].type!==A.type&&(F?F.call(this,A,ae[0]):(ae[1]||Cl).call(this,A,ae[0]));else throw new Error("Cannot close `"+A.type+"` ("+wr({start:A.start,end:A.end})+"): it’s not open");X.position.end=kt(A.end)}function d(){return Pa(this.stack.pop())}function c(){this.data.expectingFirstListItemValue=!0}function f(A){if(this.data.expectingFirstListItemValue){const F=this.stack[this.stack.length-2];F.start=Number.parseInt(this.sliceSerialize(A),10),this.data.expectingFirstListItemValue=void 0}}function h(){const A=this.resume(),F=this.stack[this.stack.length-1];F.lang=A}function g(){const A=this.resume(),F=this.stack[this.stack.length-1];F.meta=A}function w(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function x(){const A=this.resume(),F=this.stack[this.stack.length-1];F.value=A.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function y(){const A=this.resume(),F=this.stack[this.stack.length-1];F.value=A.replace(/(\r?\n|\r)$/g,"")}function E(A){const F=this.resume(),X=this.stack[this.stack.length-1];X.label=F,X.identifier=et(this.sliceSerialize(A)).toLowerCase()}function _(){const A=this.resume(),F=this.stack[this.stack.length-1];F.title=A}function O(){const A=this.resume(),F=this.stack[this.stack.length-1];F.url=A}function z(A){const F=this.stack[this.stack.length-1];if(!F.depth){const X=this.sliceSerialize(A).length;F.depth=X}}function C(){this.data.setextHeadingSlurpLineEnding=!0}function U(A){const F=this.stack[this.stack.length-1];F.depth=this.sliceSerialize(A).codePointAt(0)===61?1:2}function V(){this.data.setextHeadingSlurpLineEnding=void 0}function R(A){const X=this.stack[this.stack.length-1].children;let ae=X[X.length-1];(!ae||ae.type!=="text")&&(ae=Cn(),ae.position={start:kt(A.start),end:void 0},X.push(ae)),this.stack.push(ae)}function S(A){const F=this.stack.pop();F.value+=this.sliceSerialize(A),F.position.end=kt(A.end)}function D(A){const F=this.stack[this.stack.length-1];if(this.data.atHardBreak){const X=F.children[F.children.length-1];X.position.end=kt(A.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(F.type)&&(R.call(this,A),S.call(this,A))}function N(){this.data.atHardBreak=!0}function K(){const A=this.resume(),F=this.stack[this.stack.length-1];F.value=A}function B(){const A=this.resume(),F=this.stack[this.stack.length-1];F.value=A}function P(){const A=this.resume(),F=this.stack[this.stack.length-1];F.value=A}function q(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const F=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=F,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function J(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const F=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=F,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function ue(A){const F=this.sliceSerialize(A),X=this.stack[this.stack.length-2];X.label=ny(F),X.identifier=et(F).toLowerCase()}function ie(){const A=this.stack[this.stack.length-1],F=this.resume(),X=this.stack[this.stack.length-1];if(this.data.inReference=!0,X.type==="link"){const ae=A.children;X.children=ae}else X.alt=F}function v(){const A=this.resume(),F=this.stack[this.stack.length-1];F.url=A}function Y(){const A=this.resume(),F=this.stack[this.stack.length-1];F.title=A}function we(){this.data.inReference=void 0}function k(){this.data.referenceType="collapsed"}function Se(A){const F=this.resume(),X=this.stack[this.stack.length-1];X.label=F,X.identifier=et(this.sliceSerialize(A)).toLowerCase(),this.data.referenceType="full"}function Ye(A){this.data.characterReferenceType=A.type}function _e(A){const F=this.sliceSerialize(A),X=this.data.characterReferenceType;let ae;X?(ae=ol(F,X==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ae=Na(F);const he=this.stack[this.stack.length-1];he.value+=ae}function j(A){const F=this.stack.pop();F.position.end=kt(A.end)}function re(A){S.call(this,A);const F=this.stack[this.stack.length-1];F.url=this.sliceSerialize(A)}function le(A){S.call(this,A);const F=this.stack[this.stack.length-1];F.url="mailto:"+this.sliceSerialize(A)}function oe(){return{type:"blockquote",children:[]}}function Ee(){return{type:"code",lang:null,meta:null,value:""}}function ne(){return{type:"inlineCode",value:""}}function xe(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function ot(){return{type:"emphasis",children:[]}}function lt(){return{type:"heading",depth:0,children:[]}}function ht(){return{type:"break"}}function St(){return{type:"html",value:""}}function ft(){return{type:"image",title:null,url:"",alt:null}}function G(){return{type:"link",title:null,url:"",children:[]}}function be(A){return{type:"list",ordered:A.type==="listOrdered",start:null,spread:A._spread,children:[]}}function me(A){return{type:"listItem",spread:A._spread,checked:null,children:[]}}function Dt(){return{type:"paragraph",children:[]}}function Tn(){return{type:"strong",children:[]}}function Cn(){return{type:"text",value:""}}function Ev(){return{type:"thematicBreak"}}}function kt(e){return{line:e.line,column:e.column,offset:e.offset}}function Tl(e,t){let r=-1;for(;++r<t.length;){const n=t[r];Array.isArray(n)?Tl(e,n):oy(e,n)}}function oy(e,t){let r;for(r in t)if(_l.call(t,r))switch(r){case"canContainEols":{const n=t[r];n&&e[r].push(...n);break}case"transforms":{const n=t[r];n&&e[r].push(...n);break}case"enter":case"exit":{const n=t[r];n&&Object.assign(e[r],n);break}}}function Cl(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+wr({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+wr({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+wr({start:t.start,end:t.end})+") is still open")}function ly(e){const t=this;t.parser=r;function r(n){return sy(n,I(m(m({},t.data("settings")),e),{extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]}))}}function uy(e,t){const r={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,r),e.applyData(t,r)}function cy(e,t){const r={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,r),[e.applyData(t,r),{type:"text",value:`
|
|
11
|
+
`}]}function dy(e,t){const r=t.value?t.value+`
|
|
12
|
+
`:"",n={},a=t.lang?t.lang.split(/\s+/):[];a.length>0&&(n.className=["language-"+a[0]]);let s={type:"element",tagName:"code",properties:n,children:[{type:"text",value:r}]};return t.meta&&(s.data={meta:t.meta}),e.patch(t,s),s=e.applyData(t,s),s={type:"element",tagName:"pre",properties:{},children:[s]},e.patch(t,s),s}function hy(e,t){const r={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function fy(e,t){const r={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function py(e,t){const r=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=String(t.identifier).toUpperCase(),a=Xt(n.toLowerCase()),s=e.footnoteOrder.indexOf(n);let i,o=e.footnoteCounts.get(n);o===void 0?(o=0,e.footnoteOrder.push(n),i=e.footnoteOrder.length):i=s+1,o+=1,e.footnoteCounts.set(n,o);const l={type:"element",tagName:"a",properties:{href:"#"+r+"fn-"+a,id:r+"fnref-"+a+(o>1?"-"+o:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(i)}]};e.patch(t,l);const u={type:"element",tagName:"sup",properties:{},children:[l]};return e.patch(t,u),e.applyData(t,u)}function my(e,t){const r={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function gy(e,t){if(e.options.allowDangerousHtml){const r={type:"raw",value:t.value};return e.patch(t,r),e.applyData(t,r)}}function Il(e,t){const r=t.referenceType;let n="]";if(r==="collapsed"?n+="[]":r==="full"&&(n+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+n}];const a=e.all(t),s=a[0];s&&s.type==="text"?s.value="["+s.value:a.unshift({type:"text",value:"["});const i=a[a.length-1];return i&&i.type==="text"?i.value+=n:a.push({type:"text",value:n}),a}function yy(e,t){const r=String(t.identifier).toUpperCase(),n=e.definitionById.get(r);if(!n)return Il(e,t);const a={src:Xt(n.url||""),alt:t.alt};n.title!==null&&n.title!==void 0&&(a.title=n.title);const s={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,s),e.applyData(t,s)}function by(e,t){const r={src:Xt(t.url)};t.alt!==null&&t.alt!==void 0&&(r.alt=t.alt),t.title!==null&&t.title!==void 0&&(r.title=t.title);const n={type:"element",tagName:"img",properties:r,children:[]};return e.patch(t,n),e.applyData(t,n)}function xy(e,t){const r={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,r);const n={type:"element",tagName:"code",properties:{},children:[r]};return e.patch(t,n),e.applyData(t,n)}function wy(e,t){const r=String(t.identifier).toUpperCase(),n=e.definitionById.get(r);if(!n)return Il(e,t);const a={href:Xt(n.url||"")};n.title!==null&&n.title!==void 0&&(a.title=n.title);const s={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function vy(e,t){const r={href:Xt(t.url)};t.title!==null&&t.title!==void 0&&(r.title=t.title);const n={type:"element",tagName:"a",properties:r,children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function ky(e,t,r){const n=e.all(t),a=r?Sy(r):El(t),s={},i=[];if(typeof t.checked=="boolean"){const d=n[0];let c;d&&d.type==="element"&&d.tagName==="p"?c=d:(c={type:"element",tagName:"p",properties:{},children:[]},n.unshift(c)),c.children.length>0&&c.children.unshift({type:"text",value:" "}),c.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),s.className=["task-list-item"]}let o=-1;for(;++o<n.length;){const d=n[o];(a||o!==0||d.type!=="element"||d.tagName!=="p")&&i.push({type:"text",value:`
|
|
13
|
+
`}),d.type==="element"&&d.tagName==="p"&&!a?i.push(...d.children):i.push(d)}const l=n[n.length-1];l&&(a||l.type!=="element"||l.tagName!=="p")&&i.push({type:"text",value:`
|
|
14
|
+
`});const u={type:"element",tagName:"li",properties:s,children:i};return e.patch(t,u),e.applyData(t,u)}function Sy(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const r=e.children;let n=-1;for(;!t&&++n<r.length;)t=El(r[n])}return t}function El(e){const t=e.spread;return t==null?e.children.length>1:t}function _y(e,t){const r={},n=e.all(t);let a=-1;for(typeof t.start=="number"&&t.start!==1&&(r.start=t.start);++a<n.length;){const i=n[a];if(i.type==="element"&&i.tagName==="li"&&i.properties&&Array.isArray(i.properties.className)&&i.properties.className.includes("task-list-item")){r.className=["contains-task-list"];break}}const s={type:"element",tagName:t.ordered?"ol":"ul",properties:r,children:e.wrap(n,!0)};return e.patch(t,s),e.applyData(t,s)}function Ty(e,t){const r={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Cy(e,t){const r={type:"root",children:e.wrap(e.all(t))};return e.patch(t,r),e.applyData(t,r)}function Iy(e,t){const r={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Ey(e,t){const r=e.all(t),n=r.shift(),a=[];if(n){const i={type:"element",tagName:"thead",properties:{},children:e.wrap([n],!0)};e.patch(t.children[0],i),a.push(i)}if(r.length>0){const i={type:"element",tagName:"tbody",properties:{},children:e.wrap(r,!0)},o=Ta(t.children[1]),l=Ko(t.children[t.children.length-1]);o&&l&&(i.position={start:o,end:l}),a.push(i)}const s={type:"element",tagName:"table",properties:{},children:e.wrap(a,!0)};return e.patch(t,s),e.applyData(t,s)}function Ay(e,t,r){const n=r?r.children:void 0,s=(n?n.indexOf(t):1)===0?"th":"td",i=r&&r.type==="table"?r.align:void 0,o=i?i.length:t.children.length;let l=-1;const u=[];for(;++l<o;){const c=t.children[l],f={},h=i?i[l]:void 0;h&&(f.align=h);let g={type:"element",tagName:s,properties:f,children:[]};c&&(g.children=e.all(c),e.patch(c,g),g=e.applyData(c,g)),u.push(g)}const d={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(t,d),e.applyData(t,d)}function My(e,t){const r={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}const Al=9,Ml=32;function Py(e){const t=String(e),r=/\r?\n|\r/g;let n=r.exec(t),a=0;const s=[];for(;n;)s.push(Pl(t.slice(a,n.index),a>0,!0),n[0]),a=n.index+n[0].length,n=r.exec(t);return s.push(Pl(t.slice(a),a>0,!1)),s.join("")}function Pl(e,t,r){let n=0,a=e.length;if(t){let s=e.codePointAt(n);for(;s===Al||s===Ml;)n++,s=e.codePointAt(n)}if(r){let s=e.codePointAt(a-1);for(;s===Al||s===Ml;)a--,s=e.codePointAt(a-1)}return a>n?e.slice(n,a):""}function Ny(e,t){const r={type:"text",value:Py(String(t.value))};return e.patch(t,r),e.applyData(t,r)}function Ly(e,t){const r={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,r),e.applyData(t,r)}const Dy={blockquote:uy,break:cy,code:dy,delete:hy,emphasis:fy,footnoteReference:py,heading:my,html:gy,imageReference:yy,image:by,inlineCode:xy,linkReference:wy,link:vy,listItem:ky,list:_y,paragraph:Ty,root:Cy,strong:Iy,table:Ey,tableCell:My,tableRow:Ay,text:Ny,thematicBreak:Ly,toml:pn,yaml:pn,definition:pn,footnoteDefinition:pn};function pn(){}const Nl=-1,mn=0,Tr=1,gn=2,Ba=3,Ra=4,ja=5,$a=6,Ll=7,Dl=8,Ol=typeof self=="object"?self:globalThis,Oy=(e,t)=>{const r=(a,s)=>(e.set(s,a),a),n=a=>{if(e.has(a))return e.get(a);const[s,i]=t[a];switch(s){case mn:case Nl:return r(i,a);case Tr:{const o=r([],a);for(const l of i)o.push(n(l));return o}case gn:{const o=r({},a);for(const[l,u]of i)o[n(l)]=n(u);return o}case Ba:return r(new Date(i),a);case Ra:{const{source:o,flags:l}=i;return r(new RegExp(o,l),a)}case ja:{const o=r(new Map,a);for(const[l,u]of i)o.set(n(l),n(u));return o}case $a:{const o=r(new Set,a);for(const l of i)o.add(n(l));return o}case Ll:{const{name:o,message:l}=i;return r(new Ol[o](l),a)}case Dl:return r(BigInt(i),a);case"BigInt":return r(Object(BigInt(i)),a);case"ArrayBuffer":return r(new Uint8Array(i).buffer,i);case"DataView":{const{buffer:o}=new Uint8Array(i);return r(new DataView(o),i)}}return r(new Ol[s](i),a)};return n},Fl=e=>Oy(new Map,e)(0),Zt="",{toString:Fy}={},{keys:zy}=Object,Cr=e=>{const t=typeof e;if(t!=="object"||!e)return[mn,t];const r=Fy.call(e).slice(8,-1);switch(r){case"Array":return[Tr,Zt];case"Object":return[gn,Zt];case"Date":return[Ba,Zt];case"RegExp":return[Ra,Zt];case"Map":return[ja,Zt];case"Set":return[$a,Zt];case"DataView":return[Tr,r]}return r.includes("Array")?[Tr,r]:r.includes("Error")?[Ll,r]:[gn,r]},yn=([e,t])=>e===mn&&(t==="function"||t==="symbol"),By=(e,t,r,n)=>{const a=(i,o)=>{const l=n.push(i)-1;return r.set(o,l),l},s=i=>{if(r.has(i))return r.get(i);let[o,l]=Cr(i);switch(o){case mn:{let d=i;switch(l){case"bigint":o=Dl,d=i.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+l);d=null;break;case"undefined":return a([Nl],i)}return a([o,d],i)}case Tr:{if(l){let f=i;return l==="DataView"?f=new Uint8Array(i.buffer):l==="ArrayBuffer"&&(f=new Uint8Array(i)),a([l,[...f]],i)}const d=[],c=a([o,d],i);for(const f of i)d.push(s(f));return c}case gn:{if(l)switch(l){case"BigInt":return a([l,i.toString()],i);case"Boolean":case"Number":case"String":return a([l,i.valueOf()],i)}if(t&&"toJSON"in i)return s(i.toJSON());const d=[],c=a([o,d],i);for(const f of zy(i))(e||!yn(Cr(i[f])))&&d.push([s(f),s(i[f])]);return c}case Ba:return a([o,i.toISOString()],i);case Ra:{const{source:d,flags:c}=i;return a([o,{source:d,flags:c}],i)}case ja:{const d=[],c=a([o,d],i);for(const[f,h]of i)(e||!(yn(Cr(f))||yn(Cr(h))))&&d.push([s(f),s(h)]);return c}case $a:{const d=[],c=a([o,d],i);for(const f of i)(e||!yn(Cr(f)))&&d.push(s(f));return c}}const{message:u}=i;return a([o,{name:l,message:u}],i)};return s},zl=(e,{json:t,lossy:r}={})=>{const n=[];return By(!(t||r),!!t,new Map,n)(e),n},bn=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Fl(zl(e,t)):structuredClone(e):(e,t)=>Fl(zl(e,t));function Ry(e,t){const r=[{type:"text",value:"↩"}];return t>1&&r.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),r}function jy(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function $y(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=e.options.footnoteBackContent||Ry,n=e.options.footnoteBackLabel||jy,a=e.options.footnoteLabel||"Footnotes",s=e.options.footnoteLabelTagName||"h2",i=e.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let l=-1;for(;++l<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[l]);if(!u)continue;const d=e.all(u),c=String(u.identifier).toUpperCase(),f=Xt(c.toLowerCase());let h=0;const g=[],w=e.footnoteCounts.get(c);for(;w!==void 0&&++h<=w;){g.length>0&&g.push({type:"text",value:" "});let E=typeof r=="string"?r:r(l,h);typeof E=="string"&&(E={type:"text",value:E}),g.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+f+(h>1?"-"+h:""),dataFootnoteBackref:"",ariaLabel:typeof n=="string"?n:n(l,h),className:["data-footnote-backref"]},children:Array.isArray(E)?E:[E]})}const x=d[d.length-1];if(x&&x.type==="element"&&x.tagName==="p"){const E=x.children[x.children.length-1];E&&E.type==="text"?E.value+=" ":x.children.push({type:"text",value:" "}),x.children.push(...g)}else d.push(...g);const y={type:"element",tagName:"li",properties:{id:t+"fn-"+f},children:e.wrap(d,!0)};e.patch(u,y),o.push(y)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:s,properties:I(m({},bn(i)),{id:"footnote-label"}),children:[{type:"text",value:a}]},{type:"text",value:`
|
|
15
15
|
`},{type:"element",tagName:"ol",properties:{},children:e.wrap(o,!0)},{type:"text",value:`
|
|
16
|
-
`}]}}const
|
|
16
|
+
`}]}}const xn=(function(e){if(e==null)return Vy;if(typeof e=="function")return wn(e);if(typeof e=="object")return Array.isArray(e)?Uy(e):Hy(e);if(typeof e=="string")return qy(e);throw new Error("Expected function, string, or object as test")});function Uy(e){const t=[];let r=-1;for(;++r<e.length;)t[r]=xn(e[r]);return wn(n);function n(...a){let s=-1;for(;++s<t.length;)if(t[s].apply(this,a))return!0;return!1}}function Hy(e){const t=e;return wn(r);function r(n){const a=n;let s;for(s in e)if(a[s]!==t[s])return!1;return!0}}function qy(e){return wn(t);function t(r){return r&&r.type===e}}function wn(e){return t;function t(r,n,a){return!!(Wy(r)&&e.call(this,r,typeof n=="number"?n:void 0,a||void 0))}}function Vy(){return!0}function Wy(e){return e!==null&&typeof e=="object"&&"type"in e}function uk(e){return e}const Bl=[],Jy=!0,Ua=!1,Ky="skip";function Rl(e,t,r,n){let a;typeof t=="function"&&typeof r!="function"?(n=r,r=t):a=t;const s=xn(a),i=n?-1:1;o(e,void 0,[])();function o(l,u,d){const c=l&&typeof l=="object"?l:{};if(typeof c.type=="string"){const h=typeof c.tagName=="string"?c.tagName:typeof c.name=="string"?c.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(l.type+(h?"<"+h+">":""))+")"})}return f;function f(){let h=Bl,g,w,x;if((!t||s(l,u,d[d.length-1]||void 0))&&(h=Yy(r(l,d)),h[0]===Ua))return h;if("children"in l&&l.children){const y=l;if(y.children&&h[0]!==Ky)for(w=(n?y.children.length:-1)+i,x=d.concat(y);w>-1&&w<y.children.length;){const E=y.children[w];if(g=o(E,w,x)(),g[0]===Ua)return g;w=typeof g[1]=="number"?g[1]:w+i}}return h}}}function Yy(e){return Array.isArray(e)?e:typeof e=="number"?[Jy,e]:e==null?Bl:[e]}function Ha(e,t,r,n){let a,s,i;typeof t=="function"&&typeof r!="function"?(s=void 0,i=t,a=r):(s=t,i=r,a=n),Rl(e,s,o,a);function o(l,u){const d=u[u.length-1],c=d?d.children.indexOf(l):void 0;return i(l,c,d)}}const qa={}.hasOwnProperty,Gy={};function Xy(e,t){const r=t||Gy,n=new Map,a=new Map,s=new Map,i=m(m({},Dy),r.handlers),o={all:u,applyData:Zy,definitionById:n,footnoteById:a,footnoteCounts:s,footnoteOrder:[],handlers:i,one:l,options:r,patch:Qy,wrap:tb};return Ha(e,function(d){if(d.type==="definition"||d.type==="footnoteDefinition"){const c=d.type==="definition"?n:a,f=String(d.identifier).toUpperCase();c.has(f)||c.set(f,d)}}),o;function l(d,c){const f=d.type,h=o.handlers[f];if(qa.call(o.handlers,f)&&h)return h(o,d,c);if(o.options.passThrough&&o.options.passThrough.includes(f)){if("children"in d){const w=d,{children:x}=w,y=H(w,["children"]),E=bn(y);return E.children=o.all(d),E}return bn(d)}return(o.options.unknownHandler||eb)(o,d,c)}function u(d){const c=[];if("children"in d){const f=d.children;let h=-1;for(;++h<f.length;){const g=o.one(f[h],d);if(g){if(h&&f[h-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=jl(g.value)),!Array.isArray(g)&&g.type==="element")){const w=g.children[0];w&&w.type==="text"&&(w.value=jl(w.value))}Array.isArray(g)?c.push(...g):c.push(g)}}}return c}}function Qy(e,t){e.position&&(t.position=Yp(e))}function Zy(e,t){let r=t;if(e&&e.data){const n=e.data.hName,a=e.data.hChildren,s=e.data.hProperties;if(typeof n=="string")if(r.type==="element")r.tagName=n;else{const i="children"in r?r.children:[r];r={type:"element",tagName:n,properties:{},children:i}}r.type==="element"&&s&&Object.assign(r.properties,bn(s)),"children"in r&&r.children&&a!==null&&a!==void 0&&(r.children=a)}return r}function eb(e,t){const r=t.data||{},n="value"in t&&!(qa.call(r,"hProperties")||qa.call(r,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function tb(e,t){const r=[];let n=-1;for(t&&r.push({type:"text",value:`
|
|
17
17
|
`});++n<e.length;)n&&r.push({type:"text",value:`
|
|
18
18
|
`}),r.push(e[n]);return t&&e.length>0&&r.push({type:"text",value:`
|
|
19
|
-
`}),r}function
|
|
20
|
-
`},i),a}function Zy(e,t){return e&&"run"in e?function(r,n){return M(this,null,function*(){const i=Bl(r,m({file:n},t));yield e.run(i,n)})}:function(r,n){return Bl(r,m({file:n},e||t))}}function Rl(e){if(e)throw e}var zi,jl;function eb(){if(jl)return zi;jl=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,i=function(u){return typeof Array.isArray=="function"?Array.isArray(u):t.call(u)==="[object Array]"},a=function(u){if(!u||t.call(u)!=="[object Object]")return!1;var d=e.call(u,"constructor"),c=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!d&&!c)return!1;var f;for(f in u);return typeof f=="undefined"||e.call(u,f)},s=function(u,d){r&&d.name==="__proto__"?r(u,d.name,{enumerable:!0,configurable:!0,value:d.newValue,writable:!0}):u[d.name]=d.newValue},o=function(u,d){if(d==="__proto__")if(e.call(u,d)){if(n)return n(u,d).value}else return;return u[d]};return zi=function l(){var u,d,c,f,h,g,x=arguments[0],b=1,w=arguments.length,E=!1;for(typeof x=="boolean"&&(E=x,x=arguments[1]||{},b=2),(x==null||typeof x!="object"&&typeof x!="function")&&(x={});b<w;++b)if(u=arguments[b],u!=null)for(d in u)c=o(x,d),f=o(u,d),x!==f&&(E&&f&&(a(f)||(h=i(f)))?(h?(h=!1,g=c&&i(c)?c:[]):g=c&&a(c)?c:{},s(x,{name:d,newValue:l(E,g,f)})):typeof f!="undefined"&&s(x,{name:d,newValue:f}));return x},zi}var tb=eb();const Bi=Fr(tb);function Ri(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function rb(){const e=[],t={run:r,use:n};return t;function r(...i){let a=-1;const s=i.pop();if(typeof s!="function")throw new TypeError("Expected function as last argument, not "+s);o(null,...i);function o(l,...u){const d=e[++a];let c=-1;if(l){s(l);return}for(;++c<i.length;)(u[c]===null||u[c]===void 0)&&(u[c]=i[c]);i=u,d?nb(d,o)(...u):s(null,...u)}}function n(i){if(typeof i!="function")throw new TypeError("Expected `middelware` to be a function, not "+i);return e.push(i),t}}function nb(e,t){let r;return n;function n(...s){const o=e.length>s.length;let l;o&&s.push(i);try{l=e.apply(this,s)}catch(u){const d=u;if(o&&r)throw d;return i(d)}o||(l&&l.then&&typeof l.then=="function"?l.then(a,i):l instanceof Error?i(l):a(l))}function i(s,...o){r||(r=!0,t(s,...o))}function a(s){i(null,s)}}const at={basename:ib,dirname:ab,extname:sb,join:ob,sep:"/"};function ib(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Cr(e);let r=0,n=-1,i=e.length,a;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(a){r=i+1;break}}else n<0&&(a=!0,n=i+1);return n<0?"":e.slice(r,n)}if(t===e)return"";let s=-1,o=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(a){r=i+1;break}}else s<0&&(a=!0,s=i+1),o>-1&&(e.codePointAt(i)===t.codePointAt(o--)?o<0&&(n=i):(o=-1,n=s));return r===n?n=s:n<0&&(n=e.length),e.slice(r,n)}function ab(e){if(Cr(e),e.length===0)return".";let t=-1,r=e.length,n;for(;--r;)if(e.codePointAt(r)===47){if(n){t=r;break}}else n||(n=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function sb(e){Cr(e);let t=e.length,r=-1,n=0,i=-1,a=0,s;for(;t--;){const o=e.codePointAt(t);if(o===47){if(s){n=t+1;break}continue}r<0&&(s=!0,r=t+1),o===46?i<0?i=t:a!==1&&(a=1):i>-1&&(a=-1)}return i<0||r<0||a===0||a===1&&i===r-1&&i===n+1?"":e.slice(i,r)}function ob(...e){let t=-1,r;for(;++t<e.length;)Cr(e[t]),e[t]&&(r=r===void 0?e[t]:r+"/"+e[t]);return r===void 0?".":lb(r)}function lb(e){Cr(e);const t=e.codePointAt(0)===47;let r=ub(e,!t);return r.length===0&&!t&&(r="."),r.length>0&&e.codePointAt(e.length-1)===47&&(r+="/"),t?"/"+r:r}function ub(e,t){let r="",n=0,i=-1,a=0,s=-1,o,l;for(;++s<=e.length;){if(s<e.length)o=e.codePointAt(s);else{if(o===47)break;o=47}if(o===47){if(!(i===s-1||a===1))if(i!==s-1&&a===2){if(r.length<2||n!==2||r.codePointAt(r.length-1)!==46||r.codePointAt(r.length-2)!==46){if(r.length>2){if(l=r.lastIndexOf("/"),l!==r.length-1){l<0?(r="",n=0):(r=r.slice(0,l),n=r.length-1-r.lastIndexOf("/")),i=s,a=0;continue}}else if(r.length>0){r="",n=0,i=s,a=0;continue}}t&&(r=r.length>0?r+"/..":"..",n=2)}else r.length>0?r+="/"+e.slice(i+1,s):r=e.slice(i+1,s),n=s-i-1;i=s,a=0}else o===46&&a>-1?a++:a=-1}return r}function Cr(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const cb={cwd:db};function db(){return"/"}function ji(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function hb(e){if(typeof e=="string")e=new URL(e);else if(!ji(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return fb(e)}function fb(e){if(e.hostname!==""){const n=new TypeError('File URL host must be "localhost" or empty on darwin');throw n.code="ERR_INVALID_FILE_URL_HOST",n}const t=e.pathname;let r=-1;for(;++r<t.length;)if(t.codePointAt(r)===37&&t.codePointAt(r+1)===50){const n=t.codePointAt(r+2);if(n===70||n===102){const i=new TypeError("File URL path must not include encoded / characters");throw i.code="ERR_INVALID_FILE_URL_PATH",i}}return decodeURIComponent(t)}const $i=["history","path","basename","stem","extname","dirname"];class $l{constructor(t){let r;t?ji(t)?r={path:t}:typeof t=="string"||pb(t)?r={value:t}:r=t:r={},this.cwd="cwd"in r?"":cb.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let n=-1;for(;++n<$i.length;){const a=$i[n];a in r&&r[a]!==void 0&&r[a]!==null&&(this[a]=a==="history"?[...r[a]]:r[a])}let i;for(i in r)$i.includes(i)||(this[i]=r[i])}get basename(){return typeof this.path=="string"?at.basename(this.path):void 0}set basename(t){Hi(t,"basename"),Ui(t,"basename"),this.path=at.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?at.dirname(this.path):void 0}set dirname(t){Ul(this.basename,"dirname"),this.path=at.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?at.extname(this.path):void 0}set extname(t){if(Ui(t,"extname"),Ul(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=at.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){ji(t)&&(t=hb(t)),Hi(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?at.basename(this.path,this.extname):void 0}set stem(t){Hi(t,"stem"),Ui(t,"stem"),this.path=at.join(this.dirname||"",t+(this.extname||""))}fail(t,r,n){const i=this.message(t,r,n);throw i.fatal=!0,i}info(t,r,n){const i=this.message(t,r,n);return i.fatal=void 0,i}message(t,r,n){const i=new Pe(t,r,n);return this.path&&(i.name=this.path+":"+i.name,i.file=this.path),i.fatal=!1,this.messages.push(i),i}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function Ui(e,t){if(e&&e.includes(at.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+at.sep+"`")}function Hi(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function Ul(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function pb(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const mb=(function(e){const n=this.constructor.prototype,i=n[e],a=function(){return i.apply(a,arguments)};return Object.setPrototypeOf(a,n),a}),gb={}.hasOwnProperty;class qi extends mb{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=rb()}copy(){const t=new qi;let r=-1;for(;++r<this.attachers.length;){const n=this.attachers[r];t.use(...n)}return t.data(Bi(!0,{},this.namespace)),t}data(t,r){return typeof t=="string"?arguments.length===2?(Ji("data",this.frozen),this.namespace[t]=r,this):gb.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Ji("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[r,...n]=this.attachers[this.freezeIndex];if(n[0]===!1)continue;n[0]===!0&&(n[0]=void 0);const i=r.call(t,...n);typeof i=="function"&&this.transformers.use(i)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const r=wn(t),n=this.parser||this.Parser;return Vi("parse",n),n(String(r),r)}process(t,r){const n=this;return this.freeze(),Vi("process",this.parser||this.Parser),Wi("process",this.compiler||this.Compiler),r?i(void 0,r):new Promise(i);function i(a,s){const o=wn(t),l=n.parse(o);n.run(l,o,function(d,c,f){if(d||!c||!f)return u(d);const h=c,g=n.stringify(h,f);wb(g)?f.value=g:f.result=g,u(d,f)});function u(d,c){d||!c?s(d):a?a(c):r(void 0,c)}}}processSync(t){let r=!1,n;return this.freeze(),Vi("processSync",this.parser||this.Parser),Wi("processSync",this.compiler||this.Compiler),this.process(t,i),ql("processSync","process",r),n;function i(a,s){r=!0,Rl(a),n=s}}run(t,r,n){Hl(t),this.freeze();const i=this.transformers;return!n&&typeof r=="function"&&(n=r,r=void 0),n?a(void 0,n):new Promise(a);function a(s,o){const l=wn(r);i.run(t,l,u);function u(d,c,f){const h=c||t;d?o(d):s?s(h):n(void 0,h,f)}}}runSync(t,r){let n=!1,i;return this.run(t,r,a),ql("runSync","run",n),i;function a(s,o){Rl(s),i=o,n=!0}}stringify(t,r){this.freeze();const n=wn(r),i=this.compiler||this.Compiler;return Wi("stringify",i),Hl(t),i(t,n)}use(t,...r){const n=this.attachers,i=this.namespace;if(Ji("use",this.frozen),t!=null)if(typeof t=="function")l(t,r);else if(typeof t=="object")Array.isArray(t)?o(t):s(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function a(u){if(typeof u=="function")l(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[d,...c]=u;l(d,c)}else s(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function s(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");o(u.plugins),u.settings&&(i.settings=Bi(!0,i.settings,u.settings))}function o(u){let d=-1;if(u!=null)if(Array.isArray(u))for(;++d<u.length;){const c=u[d];a(c)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function l(u,d){let c=-1,f=-1;for(;++c<n.length;)if(n[c][0]===u){f=c;break}if(f===-1)n.push([u,...d]);else if(d.length>0){let[h,...g]=d;const x=n[f][1];Ri(x)&&Ri(h)&&(h=Bi(!0,x,h)),n[f]=[u,h,...g]}}}}const yb=new qi().freeze();function Vi(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Wi(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Ji(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Hl(e){if(!Ri(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function ql(e,t,r){if(!r)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function wn(e){return bb(e)?e:new $l(e)}function bb(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function wb(e){return typeof e=="string"||xb(e)}function xb(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const vb="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Vl=[],Wl={allowDangerousHtml:!0},kb=/^(https?|ircs?|mailto|xmpp)$/i,Sb=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function _b(e){const t=Tb(e),r=Cb(e);return Ib(t.runSync(t.parse(r),r),e)}function Tb(e){const t=e.rehypePlugins||Vl,r=e.remarkPlugins||Vl,n=e.remarkRehypeOptions?m(m({},e.remarkRehypeOptions),Wl):Wl;return yb().use(ay).use(r).use(Zy,n).use(t)}function Cb(e){const t=e.children||"",r=new $l;return typeof t=="string"&&(r.value=t),r}function Ib(e,t){const r=t.allowedElements,n=t.allowElement,i=t.components,a=t.disallowedElements,s=t.skipHtml,o=t.unwrapDisallowed,l=t.urlTransform||Eb;for(const d of Sb)Object.hasOwn(t,d.from)&&(""+d.from+(d.to?"use `"+d.to+"` instead":"remove it")+vb+d.id,void 0);return Oi(e,u),Xp(e,{Fragment:p.Fragment,components:i,ignoreInvalidStyle:!0,jsx:p.jsx,jsxs:p.jsxs,passKeys:!0,passNode:!0});function u(d,c,f){if(d.type==="raw"&&f&&typeof c=="number")return s?f.children.splice(c,1):f.children[c]={type:"text",value:d.value},c;if(d.type==="element"){let h;for(h in ki)if(Object.hasOwn(ki,h)&&Object.hasOwn(d.properties,h)){const g=d.properties[h],x=ki[h];(x===null||x.includes(d.tagName))&&(d.properties[h]=l(String(g||""),h,d))}}if(d.type==="element"){let h=r?!r.includes(d.tagName):a?a.includes(d.tagName):!1;if(!h&&n&&typeof c=="number"&&(h=!n(d,c,f)),h&&f&&typeof c=="number")return o&&d.children?f.children.splice(c,1,...d.children):f.children.splice(c,1),c}}}function Eb(e){const t=e.indexOf(":"),r=e.indexOf("?"),n=e.indexOf("#"),i=e.indexOf("/");return t===-1||i!==-1&&t>i||r!==-1&&t>r||n!==-1&&t>n||kb.test(e.slice(0,t))?e:""}var Ab=(e,t)=>typeof e=="string"?e===t:JSON.stringify(e)===JSON.stringify(t),Mb=(e,t)=>{if(!e||!t)return!1;const r=n=>{const o=n||{},{position:i,data:a}=o;return H(o,["position","data"])};return JSON.stringify(r(e.properties))===JSON.stringify(r(t.properties))&&Ab(e.children,t.children)},Ki=(e,t)=>Mb(e.node,t.node),Pb=(e={})=>Object.fromEntries(Object.entries(e!=null?e:{}).map(([t,r])=>{if(!r)return[t,r];const n=r,i=o=>{var l=o,{node:a}=l,s=H(l,["node"]);return p.jsx(n,m({},s))};return[t,y.memo(i,Ki)]})),Yi=y.createContext(null),Jl=()=>y.useContext(Yi)!==null,Nb=r=>{var n=r,{children:e}=n,t=H(n,["children"]);return p.jsx(Yi.Provider,{value:t,children:e})},Lb=y.memo(Nb,Ki),Db=r=>{var n=r,{node:e}=n,t=H(n,["node"]);return p.jsx("pre",m({},t))},Ob=r=>{var n=r,{node:e}=n,t=H(n,["node"]);return p.jsx("code",m({},t))},Gi=({node:e,components:{Pre:t,Code:r},code:n})=>p.jsx(t,{children:p.jsx(r,{node:e,children:n})}),Fb=()=>null,zb=({node:e,components:{Pre:t,Code:r,SyntaxHighlighter:n,CodeHeader:i},language:a,code:s})=>{const o=y.useMemo(()=>({Pre:t,Code:r}),[t,r]),l=a?n:Gi;return p.jsxs(p.Fragment,{children:[p.jsx(i,{node:e,language:a,code:s}),p.jsx(l,{node:e,components:o,language:a!=null?a:"unknown",code:s})]})},Xi={exports:{}};var Kl;function Bb(){return Kl||(Kl=1,(function(e){(function(){var t={}.hasOwnProperty;function r(){for(var a="",s=0;s<arguments.length;s++){var o=arguments[s];o&&(a=i(a,n(o)))}return a}function n(a){if(typeof a=="string"||typeof a=="number")return a;if(typeof a!="object")return"";if(Array.isArray(a))return r.apply(null,a);if(a.toString!==Object.prototype.toString&&!a.toString.toString().includes("[native code]"))return a.toString();var s="";for(var o in a)t.call(a,o)&&a[o]&&(s=i(s,o));return s}function i(a,s){return s?a?a+" "+s:a+s:a}e.exports?(r.default=r,e.exports=r):window.classNames=r})()})(Xi)),Xi.exports}var Rb=Bb();const Yl=Fr(Rb);var Gl=r=>{var n=r,{className:e}=n,t=H(n,["className"]);return s=>{var o=s,{className:i}=o,a=H(o,["className"]);return m(m({className:Yl(e,i)},t),a)}},jb=l=>{var u=l,{node:e,components:{Pre:t,Code:r,SyntaxHighlighter:n,CodeHeader:i},componentsByLanguage:a={},children:s}=u,o=H(u,["node","components","componentsByLanguage","children"]);var E,_,O,z,C,U;const d=y.useContext(Yi),c=Gl(d),f=At(V=>p.jsx(t,m({},c(V)))),h=Gl(o),g=At(V=>p.jsx(r,m({},h(V)))),x=(_=(E=/language-(\w+)/.exec(o.className||""))==null?void 0:E[1])!=null?_:"";if(typeof s!="string")return p.jsx(Gi,{node:e,components:{Pre:f,Code:g},code:s});const b=(z=(O=a[x])==null?void 0:O.SyntaxHighlighter)!=null?z:n,w=(U=(C=a[x])==null?void 0:C.CodeHeader)!=null?U:i;return p.jsx(zb,{node:e,components:{Pre:f,Code:g,SyntaxHighlighter:b,CodeHeader:w},language:x||"unknown",code:s})},$b=i=>{var a=i,{node:e,components:t,componentsByLanguage:r}=a,n=H(a,["node","components","componentsByLanguage"]);return Jl()?p.jsx(jb,m({node:e,components:t,componentsByLanguage:r},n)):p.jsx(t.Code,m({},n))},Ub=y.memo($b,(e,t)=>e.components===t.components&&e.componentsByLanguage===t.componentsByLanguage&&Ki(e,t)),{useSmooth:Hb,useSmoothStatus:qb,withSmoothContextProvider:Vb}=Yh,Wb=a=>{var s=a,{components:e,componentsByLanguage:t,smooth:r=!0,preprocess:n}=s,i=H(s,["components","componentsByLanguage","smooth","preprocess"]);const o=Hs(),l=y.useMemo(()=>n?I(m({},o),{text:n(o.text)}):o,[o,n]),{text:u}=Hb(l,r),{pre:d=Db,code:c=Ob,SyntaxHighlighter:f=Gi,CodeHeader:h=Fb}=e!=null?e:{},g=y.useMemo(()=>({Pre:d,Code:c,SyntaxHighlighter:f,CodeHeader:h}),[d,c,f,h]),x=At(w=>p.jsx(Ub,m({components:g,componentsByLanguage:t},w))),b=y.useMemo(()=>{const C=e!=null?e:{},{pre:w,code:E,SyntaxHighlighter:_,CodeHeader:O}=C,z=H(C,["pre","code","SyntaxHighlighter","CodeHeader"]);return I(m({},z),{pre:Lb,code:x})},[x,e]);return p.jsx(_b,I(m({components:b},i),{children:u}))},Xl=y.forwardRef((a,i)=>{var s=a,{className:e,containerProps:t,containerComponent:r="div"}=s,n=H(s,["className","containerProps","containerComponent"]);const o=qb();return p.jsx(r,I(m({"data-status":o.type},t),{className:Yl(e,t==null?void 0:t.className),ref:i,children:p.jsx(Wb,m({},n))}))});Xl.displayName="MarkdownTextPrimitive";var Jb=Vb(Xl);function Ql(e,t){const r=String(e);if(typeof t!="string")throw new TypeError("Expected character");let n=0,i=r.indexOf(t);for(;i!==-1;)n++,i=r.indexOf(t,i+t.length);return n}function Kb(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Yb(e,t,r){const i=yn((r||{}).ignore||[]),a=Gb(t);let s=-1;for(;++s<a.length;)Fl(e,"text",o);function o(u,d){let c=-1,f;for(;++c<d.length;){const h=d[c],g=f?f.children:void 0;if(i(h,g?g.indexOf(h):void 0,f))return;f=h}if(f)return l(u,d)}function l(u,d){const c=d[d.length-1],f=a[s][0],h=a[s][1];let g=0;const b=c.children.indexOf(u);let w=!1,E=[];f.lastIndex=0;let _=f.exec(u.value);for(;_;){const O=_.index,z={index:_.index,input:_.input,stack:[...d,u]};let C=h(..._,z);if(typeof C=="string"&&(C=C.length>0?{type:"text",value:C}:void 0),C===!1?f.lastIndex=O+1:(g!==O&&E.push({type:"text",value:u.value.slice(g,O)}),Array.isArray(C)?E.push(...C):C&&E.push(C),g=O+_[0].length,w=!0),!f.global)break;_=f.exec(u.value)}return w?(g<u.value.length&&E.push({type:"text",value:u.value.slice(g)}),c.children.splice(b,1,...E)):E=[u],b+E.length}}function Gb(e){const t=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const r=!e[0]||Array.isArray(e[0])?e:[e];let n=-1;for(;++n<r.length;){const i=r[n];t.push([Xb(i[0]),Qb(i[1])])}return t}function Xb(e){return typeof e=="string"?new RegExp(Kb(e),"g"):e}function Qb(e){return typeof e=="function"?e:function(){return e}}const Qi="phrasing",Zi=["autolink","link","image","label"];function Zb(){return{transforms:[sw],enter:{literalAutolink:tw,literalAutolinkEmail:ea,literalAutolinkHttp:ea,literalAutolinkWww:ea},exit:{literalAutolink:aw,literalAutolinkEmail:iw,literalAutolinkHttp:rw,literalAutolinkWww:nw}}}function ew(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Qi,notInConstruct:Zi},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Qi,notInConstruct:Zi},{character:":",before:"[ps]",after:"\\/",inConstruct:Qi,notInConstruct:Zi}]}}function tw(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function ea(e){this.config.enter.autolinkProtocol.call(this,e)}function rw(e){this.config.exit.autolinkProtocol.call(this,e)}function nw(e){this.config.exit.data.call(this,e);const t=this.stack[this.stack.length-1];t.type,t.url="http://"+this.sliceSerialize(e)}function iw(e){this.config.exit.autolinkEmail.call(this,e)}function aw(e){this.exit(e)}function sw(e){Yb(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,ow],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),lw]],{ignore:["link","linkReference"]})}function ow(e,t,r,n,i){let a="";if(!Zl(i)||(/^w/i.test(t)&&(r=t+r,t="",a="http://"),!uw(r)))return!1;const s=cw(r+n);if(!s[0])return!1;const o={type:"link",title:null,url:a+t+s[0],children:[{type:"text",value:t+s[0]}]};return s[1]?[o,{type:"text",value:s[1]}]:o}function lw(e,t,r,n){return!Zl(n,!0)||/[-\d_]$/.test(r)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+r,children:[{type:"text",value:t+"@"+r}]}}function uw(e){const t=e.split(".");return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function cw(e){const t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let r=t[0],n=r.indexOf(")");const i=Ql(e,"(");let a=Ql(e,")");for(;n!==-1&&i>a;)e+=r.slice(0,n+1),r=r.slice(n+1),n=r.indexOf(")"),a++;return[e,r]}function Zl(e,t){const r=e.input.charCodeAt(e.index-1);return(e.index===0||Pt(r)||un(r))&&(!t||r!==47)}eu.peek=ww;function dw(){this.buffer()}function hw(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function fw(){this.buffer()}function pw(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function mw(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=et(this.sliceSerialize(e)).toLowerCase(),r.label=t}function gw(e){this.exit(e)}function yw(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=et(this.sliceSerialize(e)).toLowerCase(),r.label=t}function bw(e){this.exit(e)}function ww(){return"["}function eu(e,t,r,n){const i=r.createTracker(n);let a=i.move("[^");const s=r.enter("footnoteReference"),o=r.enter("reference");return a+=i.move(r.safe(r.associationId(e),{after:"]",before:a})),o(),s(),a+=i.move("]"),a}function xw(){return{enter:{gfmFootnoteCallString:dw,gfmFootnoteCall:hw,gfmFootnoteDefinitionLabelString:fw,gfmFootnoteDefinition:pw},exit:{gfmFootnoteCallString:mw,gfmFootnoteCall:gw,gfmFootnoteDefinitionLabelString:yw,gfmFootnoteDefinition:bw}}}function vw(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:r,footnoteReference:eu},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function r(n,i,a,s){const o=a.createTracker(s);let l=o.move("[^");const u=a.enter("footnoteDefinition"),d=a.enter("label");return l+=o.move(a.safe(a.associationId(n),{before:l,after:"]"})),d(),l+=o.move("]:"),n.children&&n.children.length>0&&(o.shift(4),l+=o.move((t?`
|
|
21
|
-
`:" ")+
|
|
22
|
-
`)}function
|
|
23
|
-
`&&
|
|
24
|
-
`}function
|
|
19
|
+
`}),r}function jl(e){let t=0,r=e.charCodeAt(t);for(;r===9||r===32;)t++,r=e.charCodeAt(t);return e.slice(t)}function $l(e,t){const r=Xy(e,t),n=r.one(e,void 0),a=$y(r),s=Array.isArray(n)?{type:"root",children:n}:n||{type:"root",children:[]};return a&&s.children.push({type:"text",value:`
|
|
20
|
+
`},a),s}function rb(e,t){return e&&"run"in e?function(r,n){return M(this,null,function*(){const a=$l(r,m({file:n},t));yield e.run(a,n)})}:function(r,n){return $l(r,m({file:n},e||t))}}function Ul(e){if(e)throw e}var Va,Hl;function nb(){if(Hl)return Va;Hl=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,a=function(u){return typeof Array.isArray=="function"?Array.isArray(u):t.call(u)==="[object Array]"},s=function(u){if(!u||t.call(u)!=="[object Object]")return!1;var d=e.call(u,"constructor"),c=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!d&&!c)return!1;var f;for(f in u);return typeof f=="undefined"||e.call(u,f)},i=function(u,d){r&&d.name==="__proto__"?r(u,d.name,{enumerable:!0,configurable:!0,value:d.newValue,writable:!0}):u[d.name]=d.newValue},o=function(u,d){if(d==="__proto__")if(e.call(u,d)){if(n)return n(u,d).value}else return;return u[d]};return Va=function l(){var u,d,c,f,h,g,w=arguments[0],x=1,y=arguments.length,E=!1;for(typeof w=="boolean"&&(E=w,w=arguments[1]||{},x=2),(w==null||typeof w!="object"&&typeof w!="function")&&(w={});x<y;++x)if(u=arguments[x],u!=null)for(d in u)c=o(w,d),f=o(u,d),w!==f&&(E&&f&&(s(f)||(h=a(f)))?(h?(h=!1,g=c&&a(c)?c:[]):g=c&&s(c)?c:{},i(w,{name:d,newValue:l(E,g,f)})):typeof f!="undefined"&&i(w,{name:d,newValue:f}));return w},Va}var ab=nb();const Wa=Br(ab);function Ja(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function sb(){const e=[],t={run:r,use:n};return t;function r(...a){let s=-1;const i=a.pop();if(typeof i!="function")throw new TypeError("Expected function as last argument, not "+i);o(null,...a);function o(l,...u){const d=e[++s];let c=-1;if(l){i(l);return}for(;++c<a.length;)(u[c]===null||u[c]===void 0)&&(u[c]=a[c]);a=u,d?ib(d,o)(...u):i(null,...u)}}function n(a){if(typeof a!="function")throw new TypeError("Expected `middelware` to be a function, not "+a);return e.push(a),t}}function ib(e,t){let r;return n;function n(...i){const o=e.length>i.length;let l;o&&i.push(a);try{l=e.apply(this,i)}catch(u){const d=u;if(o&&r)throw d;return a(d)}o||(l&&l.then&&typeof l.then=="function"?l.then(s,a):l instanceof Error?a(l):s(l))}function a(i,...o){r||(r=!0,t(i,...o))}function s(i){a(null,i)}}const st={basename:ob,dirname:lb,extname:ub,join:cb,sep:"/"};function ob(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Ir(e);let r=0,n=-1,a=e.length,s;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(s){r=a+1;break}}else n<0&&(s=!0,n=a+1);return n<0?"":e.slice(r,n)}if(t===e)return"";let i=-1,o=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(s){r=a+1;break}}else i<0&&(s=!0,i=a+1),o>-1&&(e.codePointAt(a)===t.codePointAt(o--)?o<0&&(n=a):(o=-1,n=i));return r===n?n=i:n<0&&(n=e.length),e.slice(r,n)}function lb(e){if(Ir(e),e.length===0)return".";let t=-1,r=e.length,n;for(;--r;)if(e.codePointAt(r)===47){if(n){t=r;break}}else n||(n=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function ub(e){Ir(e);let t=e.length,r=-1,n=0,a=-1,s=0,i;for(;t--;){const o=e.codePointAt(t);if(o===47){if(i){n=t+1;break}continue}r<0&&(i=!0,r=t+1),o===46?a<0?a=t:s!==1&&(s=1):a>-1&&(s=-1)}return a<0||r<0||s===0||s===1&&a===r-1&&a===n+1?"":e.slice(a,r)}function cb(...e){let t=-1,r;for(;++t<e.length;)Ir(e[t]),e[t]&&(r=r===void 0?e[t]:r+"/"+e[t]);return r===void 0?".":db(r)}function db(e){Ir(e);const t=e.codePointAt(0)===47;let r=hb(e,!t);return r.length===0&&!t&&(r="."),r.length>0&&e.codePointAt(e.length-1)===47&&(r+="/"),t?"/"+r:r}function hb(e,t){let r="",n=0,a=-1,s=0,i=-1,o,l;for(;++i<=e.length;){if(i<e.length)o=e.codePointAt(i);else{if(o===47)break;o=47}if(o===47){if(!(a===i-1||s===1))if(a!==i-1&&s===2){if(r.length<2||n!==2||r.codePointAt(r.length-1)!==46||r.codePointAt(r.length-2)!==46){if(r.length>2){if(l=r.lastIndexOf("/"),l!==r.length-1){l<0?(r="",n=0):(r=r.slice(0,l),n=r.length-1-r.lastIndexOf("/")),a=i,s=0;continue}}else if(r.length>0){r="",n=0,a=i,s=0;continue}}t&&(r=r.length>0?r+"/..":"..",n=2)}else r.length>0?r+="/"+e.slice(a+1,i):r=e.slice(a+1,i),n=i-a-1;a=i,s=0}else o===46&&s>-1?s++:s=-1}return r}function Ir(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const fb={cwd:pb};function pb(){return"/"}function Ka(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function mb(e){if(typeof e=="string")e=new URL(e);else if(!Ka(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return gb(e)}function gb(e){if(e.hostname!==""){const n=new TypeError('File URL host must be "localhost" or empty on darwin');throw n.code="ERR_INVALID_FILE_URL_HOST",n}const t=e.pathname;let r=-1;for(;++r<t.length;)if(t.codePointAt(r)===37&&t.codePointAt(r+1)===50){const n=t.codePointAt(r+2);if(n===70||n===102){const a=new TypeError("File URL path must not include encoded / characters");throw a.code="ERR_INVALID_FILE_URL_PATH",a}}return decodeURIComponent(t)}const Ya=["history","path","basename","stem","extname","dirname"];class ql{constructor(t){let r;t?Ka(t)?r={path:t}:typeof t=="string"||yb(t)?r={value:t}:r=t:r={},this.cwd="cwd"in r?"":fb.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let n=-1;for(;++n<Ya.length;){const s=Ya[n];s in r&&r[s]!==void 0&&r[s]!==null&&(this[s]=s==="history"?[...r[s]]:r[s])}let a;for(a in r)Ya.includes(a)||(this[a]=r[a])}get basename(){return typeof this.path=="string"?st.basename(this.path):void 0}set basename(t){Xa(t,"basename"),Ga(t,"basename"),this.path=st.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?st.dirname(this.path):void 0}set dirname(t){Vl(this.basename,"dirname"),this.path=st.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?st.extname(this.path):void 0}set extname(t){if(Ga(t,"extname"),Vl(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=st.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Ka(t)&&(t=mb(t)),Xa(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?st.basename(this.path,this.extname):void 0}set stem(t){Xa(t,"stem"),Ga(t,"stem"),this.path=st.join(this.dirname||"",t+(this.extname||""))}fail(t,r,n){const a=this.message(t,r,n);throw a.fatal=!0,a}info(t,r,n){const a=this.message(t,r,n);return a.fatal=void 0,a}message(t,r,n){const a=new Pe(t,r,n);return this.path&&(a.name=this.path+":"+a.name,a.file=this.path),a.fatal=!1,this.messages.push(a),a}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function Ga(e,t){if(e&&e.includes(st.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+st.sep+"`")}function Xa(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function Vl(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function yb(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const bb=(function(e){const n=this.constructor.prototype,a=n[e],s=function(){return a.apply(s,arguments)};return Object.setPrototypeOf(s,n),s}),xb={}.hasOwnProperty;class Qa extends bb{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=sb()}copy(){const t=new Qa;let r=-1;for(;++r<this.attachers.length;){const n=this.attachers[r];t.use(...n)}return t.data(Wa(!0,{},this.namespace)),t}data(t,r){return typeof t=="string"?arguments.length===2?(ts("data",this.frozen),this.namespace[t]=r,this):xb.call(this.namespace,t)&&this.namespace[t]||void 0:t?(ts("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[r,...n]=this.attachers[this.freezeIndex];if(n[0]===!1)continue;n[0]===!0&&(n[0]=void 0);const a=r.call(t,...n);typeof a=="function"&&this.transformers.use(a)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const r=vn(t),n=this.parser||this.Parser;return Za("parse",n),n(String(r),r)}process(t,r){const n=this;return this.freeze(),Za("process",this.parser||this.Parser),es("process",this.compiler||this.Compiler),r?a(void 0,r):new Promise(a);function a(s,i){const o=vn(t),l=n.parse(o);n.run(l,o,function(d,c,f){if(d||!c||!f)return u(d);const h=c,g=n.stringify(h,f);kb(g)?f.value=g:f.result=g,u(d,f)});function u(d,c){d||!c?i(d):s?s(c):r(void 0,c)}}}processSync(t){let r=!1,n;return this.freeze(),Za("processSync",this.parser||this.Parser),es("processSync",this.compiler||this.Compiler),this.process(t,a),Jl("processSync","process",r),n;function a(s,i){r=!0,Ul(s),n=i}}run(t,r,n){Wl(t),this.freeze();const a=this.transformers;return!n&&typeof r=="function"&&(n=r,r=void 0),n?s(void 0,n):new Promise(s);function s(i,o){const l=vn(r);a.run(t,l,u);function u(d,c,f){const h=c||t;d?o(d):i?i(h):n(void 0,h,f)}}}runSync(t,r){let n=!1,a;return this.run(t,r,s),Jl("runSync","run",n),a;function s(i,o){Ul(i),a=o,n=!0}}stringify(t,r){this.freeze();const n=vn(r),a=this.compiler||this.Compiler;return es("stringify",a),Wl(t),a(t,n)}use(t,...r){const n=this.attachers,a=this.namespace;if(ts("use",this.frozen),t!=null)if(typeof t=="function")l(t,r);else if(typeof t=="object")Array.isArray(t)?o(t):i(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function s(u){if(typeof u=="function")l(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[d,...c]=u;l(d,c)}else i(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function i(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");o(u.plugins),u.settings&&(a.settings=Wa(!0,a.settings,u.settings))}function o(u){let d=-1;if(u!=null)if(Array.isArray(u))for(;++d<u.length;){const c=u[d];s(c)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function l(u,d){let c=-1,f=-1;for(;++c<n.length;)if(n[c][0]===u){f=c;break}if(f===-1)n.push([u,...d]);else if(d.length>0){let[h,...g]=d;const w=n[f][1];Ja(w)&&Ja(h)&&(h=Wa(!0,w,h)),n[f]=[u,h,...g]}}}}const wb=new Qa().freeze();function Za(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function es(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function ts(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Wl(e){if(!Ja(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Jl(e,t,r){if(!r)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function vn(e){return vb(e)?e:new ql(e)}function vb(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function kb(e){return typeof e=="string"||Sb(e)}function Sb(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const _b="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Kl=[],Yl={allowDangerousHtml:!0},Tb=/^(https?|ircs?|mailto|xmpp)$/i,Cb=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Ib(e){const t=Eb(e),r=Ab(e);return Mb(t.runSync(t.parse(r),r),e)}function Eb(e){const t=e.rehypePlugins||Kl,r=e.remarkPlugins||Kl,n=e.remarkRehypeOptions?m(m({},e.remarkRehypeOptions),Yl):Yl;return wb().use(ly).use(r).use(rb,n).use(t)}function Ab(e){const t=e.children||"",r=new ql;return typeof t=="string"&&(r.value=t),r}function Mb(e,t){const r=t.allowedElements,n=t.allowElement,a=t.components,s=t.disallowedElements,i=t.skipHtml,o=t.unwrapDisallowed,l=t.urlTransform||Pb;for(const d of Cb)Object.hasOwn(t,d.from)&&(""+d.from+(d.to?"use `"+d.to+"` instead":"remove it")+_b+d.id,void 0);return Ha(e,u),em(e,{Fragment:p.Fragment,components:a,ignoreInvalidStyle:!0,jsx:p.jsx,jsxs:p.jsxs,passKeys:!0,passNode:!0});function u(d,c,f){if(d.type==="raw"&&f&&typeof c=="number")return i?f.children.splice(c,1):f.children[c]={type:"text",value:d.value},c;if(d.type==="element"){let h;for(h in Ma)if(Object.hasOwn(Ma,h)&&Object.hasOwn(d.properties,h)){const g=d.properties[h],w=Ma[h];(w===null||w.includes(d.tagName))&&(d.properties[h]=l(String(g||""),h,d))}}if(d.type==="element"){let h=r?!r.includes(d.tagName):s?s.includes(d.tagName):!1;if(!h&&n&&typeof c=="number"&&(h=!n(d,c,f)),h&&f&&typeof c=="number")return o&&d.children?f.children.splice(c,1,...d.children):f.children.splice(c,1),c}}}function Pb(e){const t=e.indexOf(":"),r=e.indexOf("?"),n=e.indexOf("#"),a=e.indexOf("/");return t===-1||a!==-1&&t>a||r!==-1&&t>r||n!==-1&&t>n||Tb.test(e.slice(0,t))?e:""}var Nb=(e,t)=>typeof e=="string"?e===t:JSON.stringify(e)===JSON.stringify(t),Lb=(e,t)=>{if(!e||!t)return!1;const r=n=>{const o=n||{},{position:a,data:s}=o;return H(o,["position","data"])};return JSON.stringify(r(e.properties))===JSON.stringify(r(t.properties))&&Nb(e.children,t.children)},rs=(e,t)=>Lb(e.node,t.node),Db=(e={})=>Object.fromEntries(Object.entries(e!=null?e:{}).map(([t,r])=>{if(!r)return[t,r];const n=r,a=o=>{var l=o,{node:s}=l,i=H(l,["node"]);return p.jsx(n,m({},i))};return[t,b.memo(a,rs)]})),ns=b.createContext(null),Gl=()=>b.useContext(ns)!==null,Ob=r=>{var n=r,{children:e}=n,t=H(n,["children"]);return p.jsx(ns.Provider,{value:t,children:e})},Fb=b.memo(Ob,rs),zb=r=>{var n=r,{node:e}=n,t=H(n,["node"]);return p.jsx("pre",m({},t))},Bb=r=>{var n=r,{node:e}=n,t=H(n,["node"]);return p.jsx("code",m({},t))},as=({node:e,components:{Pre:t,Code:r},code:n})=>p.jsx(t,{children:p.jsx(r,{node:e,children:n})}),Rb=()=>null,jb=({node:e,components:{Pre:t,Code:r,SyntaxHighlighter:n,CodeHeader:a},language:s,code:i})=>{const o=b.useMemo(()=>({Pre:t,Code:r}),[t,r]),l=s?n:as;return p.jsxs(p.Fragment,{children:[p.jsx(a,{node:e,language:s,code:i}),p.jsx(l,{node:e,components:o,language:s!=null?s:"unknown",code:i})]})},ss={exports:{}};var Xl;function $b(){return Xl||(Xl=1,(function(e){(function(){var t={}.hasOwnProperty;function r(){for(var s="",i=0;i<arguments.length;i++){var o=arguments[i];o&&(s=a(s,n(o)))}return s}function n(s){if(typeof s=="string"||typeof s=="number")return s;if(typeof s!="object")return"";if(Array.isArray(s))return r.apply(null,s);if(s.toString!==Object.prototype.toString&&!s.toString.toString().includes("[native code]"))return s.toString();var i="";for(var o in s)t.call(s,o)&&s[o]&&(i=a(i,o));return i}function a(s,i){return i?s?s+" "+i:s+i:s}e.exports?(r.default=r,e.exports=r):window.classNames=r})()})(ss)),ss.exports}var Ub=$b();const Ql=Br(Ub);var Zl=r=>{var n=r,{className:e}=n,t=H(n,["className"]);return i=>{var o=i,{className:a}=o,s=H(o,["className"]);return m(m({className:Ql(e,a)},t),s)}},Hb=l=>{var u=l,{node:e,components:{Pre:t,Code:r,SyntaxHighlighter:n,CodeHeader:a},componentsByLanguage:s={},children:i}=u,o=H(u,["node","components","componentsByLanguage","children"]);var E,_,O,z,C,U;const d=b.useContext(ns),c=Zl(d),f=At(V=>p.jsx(t,m({},c(V)))),h=Zl(o),g=At(V=>p.jsx(r,m({},h(V)))),w=(_=(E=/language-(\w+)/.exec(o.className||""))==null?void 0:E[1])!=null?_:"";if(typeof i!="string")return p.jsx(as,{node:e,components:{Pre:f,Code:g},code:i});const x=(z=(O=s[w])==null?void 0:O.SyntaxHighlighter)!=null?z:n,y=(U=(C=s[w])==null?void 0:C.CodeHeader)!=null?U:a;return p.jsx(jb,{node:e,components:{Pre:f,Code:g,SyntaxHighlighter:x,CodeHeader:y},language:w||"unknown",code:i})},qb=a=>{var s=a,{node:e,components:t,componentsByLanguage:r}=s,n=H(s,["node","components","componentsByLanguage"]);return Gl()?p.jsx(Hb,m({node:e,components:t,componentsByLanguage:r},n)):p.jsx(t.Code,m({},n))},Vb=b.memo(qb,(e,t)=>e.components===t.components&&e.componentsByLanguage===t.componentsByLanguage&&rs(e,t)),{useSmooth:Wb,useSmoothStatus:Jb,withSmoothContextProvider:Kb}=Zh,Yb=s=>{var i=s,{components:e,componentsByLanguage:t,smooth:r=!0,preprocess:n}=i,a=H(i,["components","componentsByLanguage","smooth","preprocess"]);const o=Ki(),l=b.useMemo(()=>n?I(m({},o),{text:n(o.text)}):o,[o,n]),{text:u}=Wb(l,r),{pre:d=zb,code:c=Bb,SyntaxHighlighter:f=as,CodeHeader:h=Rb}=e!=null?e:{},g=b.useMemo(()=>({Pre:d,Code:c,SyntaxHighlighter:f,CodeHeader:h}),[d,c,f,h]),w=At(y=>p.jsx(Vb,m({components:g,componentsByLanguage:t},y))),x=b.useMemo(()=>{const C=e!=null?e:{},{pre:y,code:E,SyntaxHighlighter:_,CodeHeader:O}=C,z=H(C,["pre","code","SyntaxHighlighter","CodeHeader"]);return I(m({},z),{pre:Fb,code:w})},[w,e]);return p.jsx(Ib,I(m({components:x},a),{children:u}))},eu=b.forwardRef((s,a)=>{var i=s,{className:e,containerProps:t,containerComponent:r="div"}=i,n=H(i,["className","containerProps","containerComponent"]);const o=Jb();return p.jsx(r,I(m({"data-status":o.type},t),{className:Ql(e,t==null?void 0:t.className),ref:a,children:p.jsx(Yb,m({},n))}))});eu.displayName="MarkdownTextPrimitive";var Gb=Kb(eu);function tu(e,t){const r=String(e);if(typeof t!="string")throw new TypeError("Expected character");let n=0,a=r.indexOf(t);for(;a!==-1;)n++,a=r.indexOf(t,a+t.length);return n}function Xb(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Qb(e,t,r){const a=xn((r||{}).ignore||[]),s=Zb(t);let i=-1;for(;++i<s.length;)Rl(e,"text",o);function o(u,d){let c=-1,f;for(;++c<d.length;){const h=d[c],g=f?f.children:void 0;if(a(h,g?g.indexOf(h):void 0,f))return;f=h}if(f)return l(u,d)}function l(u,d){const c=d[d.length-1],f=s[i][0],h=s[i][1];let g=0;const x=c.children.indexOf(u);let y=!1,E=[];f.lastIndex=0;let _=f.exec(u.value);for(;_;){const O=_.index,z={index:_.index,input:_.input,stack:[...d,u]};let C=h(..._,z);if(typeof C=="string"&&(C=C.length>0?{type:"text",value:C}:void 0),C===!1?f.lastIndex=O+1:(g!==O&&E.push({type:"text",value:u.value.slice(g,O)}),Array.isArray(C)?E.push(...C):C&&E.push(C),g=O+_[0].length,y=!0),!f.global)break;_=f.exec(u.value)}return y?(g<u.value.length&&E.push({type:"text",value:u.value.slice(g)}),c.children.splice(x,1,...E)):E=[u],x+E.length}}function Zb(e){const t=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const r=!e[0]||Array.isArray(e[0])?e:[e];let n=-1;for(;++n<r.length;){const a=r[n];t.push([ex(a[0]),tx(a[1])])}return t}function ex(e){return typeof e=="string"?new RegExp(Xb(e),"g"):e}function tx(e){return typeof e=="function"?e:function(){return e}}const is="phrasing",os=["autolink","link","image","label"];function rx(){return{transforms:[ux],enter:{literalAutolink:ax,literalAutolinkEmail:ls,literalAutolinkHttp:ls,literalAutolinkWww:ls},exit:{literalAutolink:lx,literalAutolinkEmail:ox,literalAutolinkHttp:sx,literalAutolinkWww:ix}}}function nx(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:is,notInConstruct:os},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:is,notInConstruct:os},{character:":",before:"[ps]",after:"\\/",inConstruct:is,notInConstruct:os}]}}function ax(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function ls(e){this.config.enter.autolinkProtocol.call(this,e)}function sx(e){this.config.exit.autolinkProtocol.call(this,e)}function ix(e){this.config.exit.data.call(this,e);const t=this.stack[this.stack.length-1];t.type,t.url="http://"+this.sliceSerialize(e)}function ox(e){this.config.exit.autolinkEmail.call(this,e)}function lx(e){this.exit(e)}function ux(e){Qb(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,cx],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),dx]],{ignore:["link","linkReference"]})}function cx(e,t,r,n,a){let s="";if(!ru(a)||(/^w/i.test(t)&&(r=t+r,t="",s="http://"),!hx(r)))return!1;const i=fx(r+n);if(!i[0])return!1;const o={type:"link",title:null,url:s+t+i[0],children:[{type:"text",value:t+i[0]}]};return i[1]?[o,{type:"text",value:i[1]}]:o}function dx(e,t,r,n){return!ru(n,!0)||/[-\d_]$/.test(r)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+r,children:[{type:"text",value:t+"@"+r}]}}function hx(e){const t=e.split(".");return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function fx(e){const t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let r=t[0],n=r.indexOf(")");const a=tu(e,"(");let s=tu(e,")");for(;n!==-1&&a>s;)e+=r.slice(0,n+1),r=r.slice(n+1),n=r.indexOf(")"),s++;return[e,r]}function ru(e,t){const r=e.input.charCodeAt(e.index-1);return(e.index===0||Pt(r)||dn(r))&&(!t||r!==47)}nu.peek=kx;function px(){this.buffer()}function mx(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function gx(){this.buffer()}function yx(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function bx(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=et(this.sliceSerialize(e)).toLowerCase(),r.label=t}function xx(e){this.exit(e)}function wx(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=et(this.sliceSerialize(e)).toLowerCase(),r.label=t}function vx(e){this.exit(e)}function kx(){return"["}function nu(e,t,r,n){const a=r.createTracker(n);let s=a.move("[^");const i=r.enter("footnoteReference"),o=r.enter("reference");return s+=a.move(r.safe(r.associationId(e),{after:"]",before:s})),o(),i(),s+=a.move("]"),s}function Sx(){return{enter:{gfmFootnoteCallString:px,gfmFootnoteCall:mx,gfmFootnoteDefinitionLabelString:gx,gfmFootnoteDefinition:yx},exit:{gfmFootnoteCallString:bx,gfmFootnoteCall:xx,gfmFootnoteDefinitionLabelString:wx,gfmFootnoteDefinition:vx}}}function _x(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:r,footnoteReference:nu},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function r(n,a,s,i){const o=s.createTracker(i);let l=o.move("[^");const u=s.enter("footnoteDefinition"),d=s.enter("label");return l+=o.move(s.safe(s.associationId(n),{before:l,after:"]"})),d(),l+=o.move("]:"),n.children&&n.children.length>0&&(o.shift(4),l+=o.move((t?`
|
|
21
|
+
`:" ")+s.indentLines(s.containerFlow(n,o.current()),t?au:Tx))),u(),l}}function Tx(e,t,r){return t===0?e:au(e,t,r)}function au(e,t,r){return(r?"":" ")+e}const Cx=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];su.peek=Px;function Ix(){return{canContainEols:["delete"],enter:{strikethrough:Ax},exit:{strikethrough:Mx}}}function Ex(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:Cx}],handlers:{delete:su}}}function Ax(e){this.enter({type:"delete",children:[]},e)}function Mx(e){this.exit(e)}function su(e,t,r,n){const a=r.createTracker(n),s=r.enter("strikethrough");let i=a.move("~~");return i+=r.containerPhrasing(e,I(m({},a.current()),{before:i,after:"~"})),i+=a.move("~~"),s(),i}function Px(){return"~"}function Nx(e){return e.length}function Lx(e,t){const r=t||{},n=(r.align||[]).concat(),a=r.stringLength||Nx,s=[],i=[],o=[],l=[];let u=0,d=-1;for(;++d<e.length;){const w=[],x=[];let y=-1;for(e[d].length>u&&(u=e[d].length);++y<e[d].length;){const E=Dx(e[d][y]);if(r.alignDelimiters!==!1){const _=a(E);x[y]=_,(l[y]===void 0||_>l[y])&&(l[y]=_)}w.push(E)}i[d]=w,o[d]=x}let c=-1;if(typeof n=="object"&&"length"in n)for(;++c<u;)s[c]=iu(n[c]);else{const w=iu(n);for(;++c<u;)s[c]=w}c=-1;const f=[],h=[];for(;++c<u;){const w=s[c];let x="",y="";w===99?(x=":",y=":"):w===108?x=":":w===114&&(y=":");let E=r.alignDelimiters===!1?1:Math.max(1,l[c]-x.length-y.length);const _=x+"-".repeat(E)+y;r.alignDelimiters!==!1&&(E=x.length+E+y.length,E>l[c]&&(l[c]=E),h[c]=E),f[c]=_}i.splice(1,0,f),o.splice(1,0,h),d=-1;const g=[];for(;++d<i.length;){const w=i[d],x=o[d];c=-1;const y=[];for(;++c<u;){const E=w[c]||"";let _="",O="";if(r.alignDelimiters!==!1){const z=l[c]-(x[c]||0),C=s[c];C===114?_=" ".repeat(z):C===99?z%2?(_=" ".repeat(z/2+.5),O=" ".repeat(z/2-.5)):(_=" ".repeat(z/2),O=_):O=" ".repeat(z)}r.delimiterStart!==!1&&!c&&y.push("|"),r.padding!==!1&&!(r.alignDelimiters===!1&&E==="")&&(r.delimiterStart!==!1||c)&&y.push(" "),r.alignDelimiters!==!1&&y.push(_),y.push(E),r.alignDelimiters!==!1&&y.push(O),r.padding!==!1&&y.push(" "),(r.delimiterEnd!==!1||c!==u-1)&&y.push("|")}g.push(r.delimiterEnd===!1?y.join("").replace(/ +$/,""):y.join(""))}return g.join(`
|
|
22
|
+
`)}function Dx(e){return e==null?"":String(e)}function iu(e){const t=typeof e=="string"?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}function Ox(e,t,r,n){const a=r.enter("blockquote"),s=r.createTracker(n);s.move("> "),s.shift(2);const i=r.indentLines(r.containerFlow(e,s.current()),Fx);return a(),i}function Fx(e,t,r){return">"+(r?"":" ")+e}function zx(e,t){return ou(e,t.inConstruct,!0)&&!ou(e,t.notInConstruct,!1)}function ou(e,t,r){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return r;let n=-1;for(;++n<t.length;)if(e.includes(t[n]))return!0;return!1}function lu(e,t,r,n){let a=-1;for(;++a<r.unsafe.length;)if(r.unsafe[a].character===`
|
|
23
|
+
`&&zx(r.stack,r.unsafe[a]))return/[ \t]/.test(n.before)?"":" ";return`\\
|
|
24
|
+
`}function Bx(e,t){const r=String(e);let n=r.indexOf(t),a=n,s=0,i=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;n!==-1;)n===a?++s>i&&(i=s):s=1,a=n+t.length,n=r.indexOf(t,a);return i}function Rx(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function jx(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function $x(e,t,r,n){const a=jx(r),s=e.value||"",i=a==="`"?"GraveAccent":"Tilde";if(Rx(e,r)){const c=r.enter("codeIndented"),f=r.indentLines(s,Ux);return c(),f}const o=r.createTracker(n),l=a.repeat(Math.max(Bx(s,a)+1,3)),u=r.enter("codeFenced");let d=o.move(l);if(e.lang){const c=r.enter(`codeFencedLang${i}`);d+=o.move(r.safe(e.lang,m({before:d,after:" ",encode:["`"]},o.current()))),c()}if(e.lang&&e.meta){const c=r.enter(`codeFencedMeta${i}`);d+=o.move(" "),d+=o.move(r.safe(e.meta,m({before:d,after:`
|
|
25
25
|
`,encode:["`"]},o.current()))),c()}return d+=o.move(`
|
|
26
|
-
`),
|
|
27
|
-
`)),d+=o.move(l),u(),d}function
|
|
28
|
-
`},l.current())))),o(),e.title&&(o=r.enter(`title${
|
|
26
|
+
`),s&&(d+=o.move(s+`
|
|
27
|
+
`)),d+=o.move(l),u(),d}function Ux(e,t,r){return(r?"":" ")+e}function us(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function Hx(e,t,r,n){const a=us(r),s=a==='"'?"Quote":"Apostrophe",i=r.enter("definition");let o=r.enter("label");const l=r.createTracker(n);let u=l.move("[");return u+=l.move(r.safe(r.associationId(e),m({before:u,after:"]"},l.current()))),u+=l.move("]: "),o(),!e.url||/[\0- \u007F]/.test(e.url)?(o=r.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(r.safe(e.url,m({before:u,after:">"},l.current()))),u+=l.move(">")):(o=r.enter("destinationRaw"),u+=l.move(r.safe(e.url,m({before:u,after:e.title?" ":`
|
|
28
|
+
`},l.current())))),o(),e.title&&(o=r.enter(`title${s}`),u+=l.move(" "+a),u+=l.move(r.safe(e.title,m({before:u,after:a},l.current()))),u+=l.move(a),o()),i(),u}function qx(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function Er(e){return"&#x"+e.toString(16).toUpperCase()+";"}function kn(e,t,r){const n=Qt(e),a=Qt(t);return n===void 0?a===void 0?r==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:n===1?a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}uu.peek=Vx;function uu(e,t,r,n){const a=qx(r),s=r.enter("emphasis"),i=r.createTracker(n),o=i.move(a);let l=i.move(r.containerPhrasing(e,m({after:a,before:o},i.current())));const u=l.charCodeAt(0),d=kn(n.before.charCodeAt(n.before.length-1),u,a);d.inside&&(l=Er(u)+l.slice(1));const c=l.charCodeAt(l.length-1),f=kn(n.after.charCodeAt(0),c,a);f.inside&&(l=l.slice(0,-1)+Er(c));const h=i.move(a);return s(),r.attentionEncodeSurroundingInfo={after:f.outside,before:d.outside},o+l+h}function Vx(e,t,r){return r.options.emphasis||"*"}function Wx(e,t){let r=!1;return Ha(e,function(n){if("value"in n&&/\r?\n|\r/.test(n.value)||n.type==="break")return r=!0,Ua}),!!((!e.depth||e.depth<3)&&Pa(e)&&(t.options.setext||r))}function Jx(e,t,r,n){const a=Math.max(Math.min(6,e.depth||1),1),s=r.createTracker(n);if(Wx(e,r)){const d=r.enter("headingSetext"),c=r.enter("phrasing"),f=r.containerPhrasing(e,I(m({},s.current()),{before:`
|
|
29
29
|
`,after:`
|
|
30
30
|
`}));return c(),d(),f+`
|
|
31
|
-
`+(
|
|
32
|
-
`))+1))}const
|
|
33
|
-
`},
|
|
34
|
-
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:
|
|
35
|
-
`))}function l(h,g,x,b){const w=x.enter("tableCell"),E=x.enter("phrasing"),_=x.containerPhrasing(h,I(m({},b),{before:a,after:a}));return E(),w(),_}function u(h,g){return Mw(h,{align:g,alignDelimiters:n,padding:r,stringLength:i})}function d(h,g,x){const b=h.children;let w=-1;const E=[],_=g.enter("table");for(;++w<b.length;)E[w]=c(b[w],g,x);return _(),E}function c(h,g,x){const b=h.children;let w=-1;const E=[],_=g.enter("tableRow");for(;++w<b.length;)E[w]=l(b[w],h,g,x);return _(),E}function f(h,g,x){let b=gu.inlineCode(h,g,x);return x.stack.includes("tableCell")&&(b=b.replace(/\|/g,"\\$&")),b}}function yx(){return{exit:{taskListCheckValueChecked:bu,taskListCheckValueUnchecked:bu,paragraph:wx}}}function bx(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:xx}}}function bu(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function wx(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const r=this.stack[this.stack.length-1];r.type;const n=r.children[0];if(n&&n.type==="text"){const i=t.children;let a=-1,s;for(;++a<i.length;){const o=i[a];if(o.type==="paragraph"){s=o;break}}s===r&&(n.value=n.value.slice(1),n.value.length===0?r.children.shift():r.position&&n.position&&typeof n.position.start.offset=="number"&&(n.position.start.column++,n.position.start.offset++,r.position.start=Object.assign({},n.position.start)))}}this.exit(e)}function xx(e,t,r,n){const i=e.children[0],a=typeof e.checked=="boolean"&&i&&i.type==="paragraph",s="["+(e.checked?"x":" ")+"] ",o=r.createTracker(n);a&&o.move(s);let l=gu.listItem(e,t,r,m(m({},n),o.current()));return a&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),l;function u(d){return d+s}}function vx(){return[Zb(),xw(),_w(),cx(),yx()]}function kx(e){return{extensions:[ew(),vw(e),Tw(),gx(e),bx()]}}const Sx={tokenize:Ax,partial:!0},wu={tokenize:Mx,partial:!0},xu={tokenize:Px,partial:!0},vu={tokenize:Nx,partial:!0},_x={tokenize:Lx,partial:!0},ku={name:"wwwAutolink",tokenize:Ix,previous:_u},Su={name:"protocolAutolink",tokenize:Ex,previous:Tu},dt={name:"emailAutolink",tokenize:Cx,previous:Cu},st={};function Tx(){return{text:st}}let Nt=48;for(;Nt<123;)st[Nt]=dt,Nt++,Nt===58?Nt=65:Nt===91&&(Nt=97);st[43]=dt,st[45]=dt,st[46]=dt,st[95]=dt,st[72]=[dt,Su],st[104]=[dt,Su],st[87]=[dt,ku],st[119]=[dt,ku];function Cx(e,t,r){const n=this;let i,a;return s;function s(c){return!ia(c)||!Cu.call(n,n.previous)||aa(n.events)?r(c):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),o(c))}function o(c){return ia(c)?(e.consume(c),o):c===64?(e.consume(c),l):r(c)}function l(c){return c===46?e.check(_x,d,u)(c):c===45||c===95||Ne(c)?(a=!0,e.consume(c),l):d(c)}function u(c){return e.consume(c),i=!0,l}function d(c){return a&&i&&Fe(n.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(c)):r(c)}}function Ix(e,t,r){const n=this;return i;function i(s){return s!==87&&s!==119||!_u.call(n,n.previous)||aa(n.events)?r(s):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(Sx,e.attempt(wu,e.attempt(xu,a),r),r)(s))}function a(s){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(s)}}function Ex(e,t,r){const n=this;let i="",a=!1;return s;function s(c){return(c===72||c===104)&&Tu.call(n,n.previous)&&!aa(n.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),i+=String.fromCodePoint(c),e.consume(c),o):r(c)}function o(c){if(Fe(c)&&i.length<5)return i+=String.fromCodePoint(c),e.consume(c),o;if(c===58){const f=i.toLowerCase();if(f==="http"||f==="https")return e.consume(c),l}return r(c)}function l(c){return c===47?(e.consume(c),a?u:(a=!0,l)):r(c)}function u(c){return c===null||ln(c)||de(c)||Pt(c)||un(c)?r(c):e.attempt(wu,e.attempt(xu,d),r)(c)}function d(c){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(c)}}function Ax(e,t,r){let n=0;return i;function i(s){return(s===87||s===119)&&n<3?(n++,e.consume(s),i):s===46&&n===3?(e.consume(s),a):r(s)}function a(s){return s===null?r(s):t(s)}}function Mx(e,t,r){let n,i,a;return s;function s(u){return u===46||u===95?e.check(vu,l,o)(u):u===null||de(u)||Pt(u)||u!==45&&un(u)?l(u):(a=!0,e.consume(u),s)}function o(u){return u===95?n=!0:(i=n,n=void 0),e.consume(u),s}function l(u){return i||n||!a?r(u):t(u)}}function Px(e,t){let r=0,n=0;return i;function i(s){return s===40?(r++,e.consume(s),i):s===41&&n<r?a(s):s===33||s===34||s===38||s===39||s===41||s===42||s===44||s===46||s===58||s===59||s===60||s===63||s===93||s===95||s===126?e.check(vu,t,a)(s):s===null||de(s)||Pt(s)?t(s):(e.consume(s),i)}function a(s){return s===41&&n++,e.consume(s),i}}function Nx(e,t,r){return n;function n(o){return o===33||o===34||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===63||o===95||o===126?(e.consume(o),n):o===38?(e.consume(o),a):o===93?(e.consume(o),i):o===60||o===null||de(o)||Pt(o)?t(o):r(o)}function i(o){return o===null||o===40||o===91||de(o)||Pt(o)?t(o):n(o)}function a(o){return Fe(o)?s(o):r(o)}function s(o){return o===59?(e.consume(o),n):Fe(o)?(e.consume(o),s):r(o)}}function Lx(e,t,r){return n;function n(a){return e.consume(a),i}function i(a){return Ne(a)?r(a):t(a)}}function _u(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||de(e)}function Tu(e){return!Fe(e)}function Cu(e){return!(e===47||ia(e))}function ia(e){return e===43||e===45||e===46||e===95||Ne(e)}function aa(e){let t=e.length,r=!1;for(;t--;){const n=e[t][1];if((n.type==="labelLink"||n.type==="labelImage")&&!n._balanced){r=!0;break}if(n._gfmAutolinkLiteralWalkedInto){r=!1;break}}return e.length>0&&!r&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const Dx={tokenize:Ux,partial:!0};function Ox(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Rx,continuation:{tokenize:jx},exit:$x}},text:{91:{name:"gfmFootnoteCall",tokenize:Bx},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Fx,resolveTo:zx}}}}function Fx(e,t,r){const n=this;let i=n.events.length;const a=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let s;for(;i--;){const l=n.events[i][1];if(l.type==="labelImage"){s=l;break}if(l.type==="gfmFootnoteCall"||l.type==="labelLink"||l.type==="label"||l.type==="image"||l.type==="link")break}return o;function o(l){if(!s||!s._balanced)return r(l);const u=et(n.sliceSerialize({start:s.end,end:n.now()}));return u.codePointAt(0)!==94||!a.includes(u.slice(1))?r(l):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(l),e.exit("gfmFootnoteCallLabelMarker"),t(l))}}function zx(e,t){let r=e.length;for(;r--;)if(e[r][1].type==="labelImage"&&e[r][0]==="enter"){e[r][1];break}e[r+1][1].type="data",e[r+3][1].type="gfmFootnoteCallLabelMarker";const n={type:"gfmFootnoteCall",start:Object.assign({},e[r+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:"gfmFootnoteCallMarker",start:Object.assign({},e[r+3][1].end),end:Object.assign({},e[r+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;const a={type:"gfmFootnoteCallString",start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},s={type:"chunkString",contentType:"string",start:Object.assign({},a.start),end:Object.assign({},a.end)},o=[e[r+1],e[r+2],["enter",n,t],e[r+3],e[r+4],["enter",i,t],["exit",i,t],["enter",a,t],["enter",s,t],["exit",s,t],["exit",a,t],e[e.length-2],e[e.length-1],["exit",n,t]];return e.splice(r,e.length-r+1,...o),e}function Bx(e,t,r){const n=this,i=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let a=0,s;return o;function o(c){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),l}function l(c){return c!==94?r(c):(e.enter("gfmFootnoteCallMarker"),e.consume(c),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(c){if(a>999||c===93&&!s||c===null||c===91||de(c))return r(c);if(c===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return i.includes(et(n.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(c)}return de(c)||(s=!0),a++,e.consume(c),c===92?d:u}function d(c){return c===91||c===92||c===93?(e.consume(c),a++,u):u(c)}}function Rx(e,t,r){const n=this,i=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let a,s=0,o;return l;function l(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(g){return g===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",d):r(g)}function d(g){if(s>999||g===93&&!o||g===null||g===91||de(g))return r(g);if(g===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return a=et(n.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return de(g)||(o=!0),s++,e.consume(g),g===92?c:d}function c(g){return g===91||g===92||g===93?(e.consume(g),s++,d):d(g)}function f(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),i.includes(a)||i.push(a),ae(e,h,"gfmFootnoteDefinitionWhitespace")):r(g)}function h(g){return t(g)}}function jx(e,t,r){return e.check(vr,t,e.attempt(Dx,t,r))}function $x(e){e.exit("gfmFootnoteDefinition")}function Ux(e,t,r){const n=this;return ae(e,i,"gfmFootnoteDefinitionIndent",5);function i(a){const s=n.events[n.events.length-1];return s&&s[1].type==="gfmFootnoteDefinitionIndent"&&s[2].sliceSerialize(s[1],!0).length===4?t(a):r(a)}}function Hx(e){let r=(e||{}).singleTilde;const n={name:"strikethrough",tokenize:a,resolveAll:i};return r==null&&(r=!0),{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function i(s,o){let l=-1;for(;++l<s.length;)if(s[l][0]==="enter"&&s[l][1].type==="strikethroughSequenceTemporary"&&s[l][1]._close){let u=l;for(;u--;)if(s[u][0]==="exit"&&s[u][1].type==="strikethroughSequenceTemporary"&&s[u][1]._open&&s[l][1].end.offset-s[l][1].start.offset===s[u][1].end.offset-s[u][1].start.offset){s[l][1].type="strikethroughSequence",s[u][1].type="strikethroughSequence";const d={type:"strikethrough",start:Object.assign({},s[u][1].start),end:Object.assign({},s[l][1].end)},c={type:"strikethroughText",start:Object.assign({},s[u][1].end),end:Object.assign({},s[l][1].start)},f=[["enter",d,o],["enter",s[u][1],o],["exit",s[u][1],o],["enter",c,o]],h=o.parser.constructs.insideSpan.null;h&&qe(f,f.length,0,cn(h,s.slice(u+1,l),o)),qe(f,f.length,0,[["exit",c,o],["enter",s[l][1],o],["exit",s[l][1],o],["exit",d,o]]),qe(s,u-1,l-u+3,f),l=u+f.length-2;break}}for(l=-1;++l<s.length;)s[l][1].type==="strikethroughSequenceTemporary"&&(s[l][1].type="data");return s}function a(s,o,l){const u=this.previous,d=this.events;let c=0;return f;function f(g){return u===126&&d[d.length-1][1].type!=="characterEscape"?l(g):(s.enter("strikethroughSequenceTemporary"),h(g))}function h(g){const x=Qt(u);if(g===126)return c>1?l(g):(s.consume(g),c++,h);if(c<2&&!r)return l(g);const b=s.exit("strikethroughSequenceTemporary"),w=Qt(g);return b._open=!w||w===2&&!!x,b._close=!x||x===2&&!!w,o(g)}}}class qx{constructor(){this.map=[]}add(t,r,n){Vx(this,t,r,n)}consume(t){if(this.map.sort(function(a,s){return a[0]-s[0]}),this.map.length===0)return;let r=this.map.length;const n=[];for(;r>0;)r-=1,n.push(t.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),t.length=this.map[r][0];n.push(t.slice()),t.length=0;let i=n.pop();for(;i;){for(const a of i)t.push(a);i=n.pop()}this.map.length=0}}function Vx(e,t,r,n){let i=0;if(!(r===0&&n.length===0)){for(;i<e.map.length;){if(e.map[i][0]===t){e.map[i][1]+=r,e.map[i][2].push(...n);return}i+=1}e.map.push([t,r,n])}}function Wx(e,t){let r=!1;const n=[];for(;t<e.length;){const i=e[t];if(r){if(i[0]==="enter")i[1].type==="tableContent"&&n.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(i[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const a=n.length-1;n[a]=n[a]==="left"?"center":"right"}}else if(i[1].type==="tableDelimiterRow")break}else i[0]==="enter"&&i[1].type==="tableDelimiterRow"&&(r=!0);t+=1}return n}function Jx(){return{flow:{null:{name:"table",tokenize:Kx,resolveAll:Yx}}}}function Kx(e,t,r){const n=this;let i=0,a=0,s;return o;function o(S){let D=n.events.length-1;for(;D>-1;){const B=n.events[D][1].type;if(B==="lineEnding"||B==="linePrefix")D--;else break}const N=D>-1?n.events[D][1].type:null,K=N==="tableHead"||N==="tableRow"?C:l;return K===C&&n.parser.lazy[n.now().line]?r(S):K(S)}function l(S){return e.enter("tableHead"),e.enter("tableRow"),u(S)}function u(S){return S===124||(s=!0,a+=1),d(S)}function d(S){return S===null?r(S):W(S)?a>1?(a=0,n.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(S),e.exit("lineEnding"),h):r(S):te(S)?ae(e,d,"whitespace")(S):(a+=1,s&&(s=!1,i+=1),S===124?(e.enter("tableCellDivider"),e.consume(S),e.exit("tableCellDivider"),s=!0,d):(e.enter("data"),c(S)))}function c(S){return S===null||S===124||de(S)?(e.exit("data"),d(S)):(e.consume(S),S===92?f:c)}function f(S){return S===92||S===124?(e.consume(S),c):c(S)}function h(S){return n.interrupt=!1,n.parser.lazy[n.now().line]?r(S):(e.enter("tableDelimiterRow"),s=!1,te(S)?ae(e,g,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(S):g(S))}function g(S){return S===45||S===58?b(S):S===124?(s=!0,e.enter("tableCellDivider"),e.consume(S),e.exit("tableCellDivider"),x):z(S)}function x(S){return te(S)?ae(e,b,"whitespace")(S):b(S)}function b(S){return S===58?(a+=1,s=!0,e.enter("tableDelimiterMarker"),e.consume(S),e.exit("tableDelimiterMarker"),w):S===45?(a+=1,w(S)):S===null||W(S)?O(S):z(S)}function w(S){return S===45?(e.enter("tableDelimiterFiller"),E(S)):z(S)}function E(S){return S===45?(e.consume(S),E):S===58?(s=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(S),e.exit("tableDelimiterMarker"),_):(e.exit("tableDelimiterFiller"),_(S))}function _(S){return te(S)?ae(e,O,"whitespace")(S):O(S)}function O(S){return S===124?g(S):S===null||W(S)?!s||i!==a?z(S):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(S)):z(S)}function z(S){return r(S)}function C(S){return e.enter("tableRow"),U(S)}function U(S){return S===124?(e.enter("tableCellDivider"),e.consume(S),e.exit("tableCellDivider"),U):S===null||W(S)?(e.exit("tableRow"),t(S)):te(S)?ae(e,U,"whitespace")(S):(e.enter("data"),V(S))}function V(S){return S===null||S===124||de(S)?(e.exit("data"),U(S)):(e.consume(S),S===92?R:V)}function R(S){return S===92||S===124?(e.consume(S),V):V(S)}}function Yx(e,t){let r=-1,n=!0,i=0,a=[0,0,0,0],s=[0,0,0,0],o=!1,l=0,u,d,c;const f=new qx;for(;++r<e.length;){const h=e[r],g=h[1];h[0]==="enter"?g.type==="tableHead"?(o=!1,l!==0&&(Iu(f,t,l,u,d),d=void 0,l=0),u={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(r,0,[["enter",u,t]])):g.type==="tableRow"||g.type==="tableDelimiterRow"?(n=!0,c=void 0,a=[0,0,0,0],s=[0,r+1,0,0],o&&(o=!1,d={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(r,0,[["enter",d,t]])),i=g.type==="tableDelimiterRow"?2:d?3:1):i&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(n=!1,s[2]===0&&(a[1]!==0&&(s[0]=s[1],c=vn(f,t,a,i,void 0,c),a=[0,0,0,0]),s[2]=r)):g.type==="tableCellDivider"&&(n?n=!1:(a[1]!==0&&(s[0]=s[1],c=vn(f,t,a,i,void 0,c)),a=s,s=[a[1],r,0,0])):g.type==="tableHead"?(o=!0,l=r):g.type==="tableRow"||g.type==="tableDelimiterRow"?(l=r,a[1]!==0?(s[0]=s[1],c=vn(f,t,a,i,r,c)):s[1]!==0&&(c=vn(f,t,s,i,r,c)),i=0):i&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(s[3]=r)}for(l!==0&&Iu(f,t,l,u,d),f.consume(t.events),r=-1;++r<t.events.length;){const h=t.events[r];h[0]==="enter"&&h[1].type==="table"&&(h[1]._align=Wx(t.events,r))}return e}function vn(e,t,r,n,i,a){const s=n===1?"tableHeader":n===2?"tableDelimiter":"tableData",o="tableContent";r[0]!==0&&(a.end=Object.assign({},er(t.events,r[0])),e.add(r[0],0,[["exit",a,t]]));const l=er(t.events,r[1]);if(a={type:s,start:Object.assign({},l),end:Object.assign({},l)},e.add(r[1],0,[["enter",a,t]]),r[2]!==0){const u=er(t.events,r[2]),d=er(t.events,r[3]),c={type:o,start:Object.assign({},u),end:Object.assign({},d)};if(e.add(r[2],0,[["enter",c,t]]),n!==2){const f=t.events[r[2]],h=t.events[r[3]];if(f[1].end=Object.assign({},h[1].end),f[1].type="chunkText",f[1].contentType="text",r[3]>r[2]+1){const g=r[2]+1,x=r[3]-r[2]-1;e.add(g,x,[])}}e.add(r[3]+1,0,[["exit",c,t]])}return i!==void 0&&(a.end=Object.assign({},er(t.events,i)),e.add(i,0,[["exit",a,t]]),a=void 0),a}function Iu(e,t,r,n,i){const a=[],s=er(t.events,r);i&&(i.end=Object.assign({},s),a.push(["exit",i,t])),n.end=Object.assign({},s),a.push(["exit",n,t]),e.add(r+1,0,a)}function er(e,t){const r=e[t],n=r[0]==="enter"?"start":"end";return r[1][n]}const Gx={name:"tasklistCheck",tokenize:Qx};function Xx(){return{text:{91:Gx}}}function Qx(e,t,r){const n=this;return i;function i(l){return n.previous!==null||!n._gfmTasklistFirstContentOfListItem?r(l):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),a)}function a(l){return de(l)?(e.enter("taskListCheckValueUnchecked"),e.consume(l),e.exit("taskListCheckValueUnchecked"),s):l===88||l===120?(e.enter("taskListCheckValueChecked"),e.consume(l),e.exit("taskListCheckValueChecked"),s):r(l)}function s(l){return l===93?(e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),o):r(l)}function o(l){return W(l)?t(l):te(l)?e.check({tokenize:Zx},t,r)(l):r(l)}}function Zx(e,t,r){return ae(e,n,"whitespace");function n(i){return i===null?r(i):t(i)}}function ev(e){return nl([Tx(),Ox(),Hx(e),Jx(),Xx()])}const tv={};function rv(e){const t=this,r=e||tv,n=t.data(),i=n.micromarkExtensions||(n.micromarkExtensions=[]),a=n.fromMarkdownExtensions||(n.fromMarkdownExtensions=[]),s=n.toMarkdownExtensions||(n.toMarkdownExtensions=[]);i.push(ev(r)),a.push(vx()),s.push(kx(r))}function Te(...e){return e.filter(Boolean).join(" ")}const nv=({content:e})=>p.jsx(Jb,{remarkPlugins:[rv],className:"cuadra-aui-md",components:sv,children:e}),sa=y.memo(nv),iv=({language:e,code:t})=>{const{isCopied:r,copyToClipboard:n}=av(),i=()=>{!t||r||n(t)};return p.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:[p.jsx("span",{className:"cuadra-lowercase [&>span]:cuadra-text-xs cuadra-font-brand",children:e}),p.jsxs("button",{onClick:i,className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-muted cuadra-transition-colors","aria-label":"Copy code",children:[!r&&p.jsx(qu,{className:"cuadra-h-4 cuadra-w-4"}),r&&p.jsx(fa,{className:"cuadra-h-4 cuadra-w-4"})]})]})},av=({copiedDuration:e=3e3}={})=>{const[t,r]=y.useState(!1);return{isCopied:t,copyToClipboard:i=>{i&&navigator.clipboard.writeText(i).then(()=>{r(!0),setTimeout(()=>r(!1),e)})}}},sv=Pb({h1:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h1",m({className:Te("cuadra-mb-6 cuadra-scroll-m-20 cuadra-text-2xl cuadra-font-normal cuadra-tracking-tight last:cuadra-mb-0 font-brand",e)},t))},h2:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h2",m({className:Te("cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h3:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h3",m({className:Te("cuadra-mb-3 cuadra-mt-5 cuadra-scroll-m-20 cuadra-text-lg cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h4:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h4",m({className:Te("cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h5:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h5",m({className:Te("cuadra-my-4 cuadra-text-lg cuadra-font-normal first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h6:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h6",m({className:Te("cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand",e)},t))},p:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("p",m({className:Te("cuadra-mb-5 cuadra-mt-5 cuadra-leading-7 first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},a:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("a",m({className:Te("cuadra-text-primary cuadra-font-medium cuadra-underline cuadra-underline-offset-4 font-brand",e)},t))},blockquote:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("blockquote",m({className:Te("cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand",e)},t))},ul:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("ul",m({className:Te("cuadra-my-5 cuadra-ml-6 cuadra-list-disc [&>li]:cuadra-mt-2 font-brand",e)},t))},ol:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("ol",m({className:Te("cuadra-my-5 cuadra-ml-6 cuadra-list-decimal [&>li]:cuadra-mt-2 font-brand",e)},t))},hr:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("hr",m({className:Te("cuadra-my-5 cuadra-border-b",e)},t))},table:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("table",m({className:Te("cuadra-my-5 cuadra-w-full cuadra-border-separate cuadra-border-spacing-0 cuadra-overflow-y-auto font-brand",e)},t))},th:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("th",m({className:Te("cuadra-bg-muted cuadra-px-4 cuadra-py-2 cuadra-text-left cuadra-font-normal first:cuadra-rounded-tl-lg last:cuadra-rounded-tr-lg [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand",e)},t))},td:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("td",m({className:Te("cuadra-border-b cuadra-border-l cuadra-px-4 cuadra-py-2 cuadra-text-left last:cuadra-border-r [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand",e)},t))},tr:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("tr",m({className:Te("cuadra-m-0 cuadra-border-b cuadra-p-0 first:cuadra-border-t [&:last-child>td:first-child]:cuadra-rounded-bl-lg [&:last-child>td:last-child]:cuadra-rounded-br-lg",e)},t))},sup:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("sup",m({className:Te("[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand",e)},t))},pre:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("pre",m({className:Te("cuadra-overflow-x-auto cuadra-whitespace-pre-wrap cuadra-break-words cuadra-rounded-b-lg !cuadra-rounded-t-none cuadra-bg-muted cuadra-p-4 cuadra-text-foreground font-brand",e)},t))},code:function(n){var i=n,{className:t}=i,r=H(i,["className"]);const a=Jl();return p.jsx("code",m({className:Te(!a&&"cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand",t)},r))},CodeHeader:iv});function Eu(n){var i=n,{className:e="",variant:t="default"}=i,r=H(i,["className","variant"]);const a="cuadra-inline-flex cuadra-items-center cuadra-rounded-md cuadra-px-3 cuadra-py-1.5 cuadra-text-xs cuadra-font-medium font-brand",s={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 p.jsx("div",m({className:`${a} ${s[t]||s.default} ${e}`},r))}function ov(e){const t=new Map;for(const r of e){const n=t.get(r.filename);(!n||r.score>n.score)&&t.set(r.filename,r)}return Array.from(t.values()).sort((r,n)=>n.score-r.score)}function lv({sources:e,maxVisible:t=3}){if(!e||e.length===0)return null;const r=ov(e),n=r.slice(0,t),i=r.length-t;return p.jsxs("div",{className:"cuadra-mt-4 cuadra-pt-3 cuadra-border-t cuadra-border-border",children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1.5 cuadra-mb-2.5",children:[p.jsx(ma,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground"}),p.jsx("span",{className:"cuadra-text-xs cuadra-font-medium cuadra-text-muted-foreground font-brand",children:"Sources"})]}),p.jsxs("div",{className:"cuadra-flex cuadra-flex-wrap cuadra-gap-2",children:[n.map((a,s)=>p.jsx(cv,{source:a},a.sourceId||s)),i>0&&p.jsxs(Eu,{variant:"subtle",children:["+",i," more"]})]})]})}function uv(e){var r;switch((r=e.split(".").pop())==null?void 0:r.toLowerCase()){case"csv":case"xlsx":case"xls":return Vu;case"md":case"txt":return Wu;default:return ma}}function cv({source:e}){const{filename:t,score:r}=e,n=uv(t);return p.jsxs(Eu,{className:"cuadra-gap-2 cuadra-cursor-default",title:r<1?`${Math.round(r*100)}% relevant`:void 0,children:[p.jsx(n,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-shrink-0 cuadra-opacity-60"}),p.jsx("span",{className:"cuadra-truncate cuadra-max-w-[180px]",children:t}),r<1&&r>0&&p.jsxs("span",{className:"cuadra-opacity-50 cuadra-text-[10px] cuadra-tabular-nums",children:[Math.round(r*100),"%"]})]})}const dv=y.forwardRef(function({welcomeTitle:t="What shall we explore today?",welcomeSubtitle:r,extraTopPadding:n,suggestions:i,inputPlaceholder:a="Reply...",enableAttachments:s=!1,preMadeResponseDelay:o=1e3,streamingSpeed:l=50,safeArea:u=!1,composerBorder:d=!1,models:c,selectedModelId:f,onModelChange:h,showChatHeader:g=!1},x){const b=bs(),w=pe(),[E,_]=y.useState(!1),[O,z]=y.useState(null),[C,U]=y.useState(!1),V=y.useSyncExternalStore(Jt.subscribe,Jt.getSnapshot);y.useEffect(()=>{if(V){const P=setTimeout(()=>Jt.clear(),4e3);return()=>clearTimeout(P)}},[V]);const R=ws(P=>{const q=P.messages;return!q||q.length===0}),S=R&&!E,D=y.useCallback((P,q,J)=>{var ue,se;if(!C)try{const v=(ue=J==null?void 0:J.streamingSpeed)!=null?ue:l,Y=(se=J==null?void 0:J.delay)!=null?se:o;Co(P,q,v,Y),w.composer().setText(P),setTimeout(()=>{w.composer().send()},10)}catch(v){}},[C,l,o,w]),N=y.useCallback(P=>{try{w.composer().setText(P),setTimeout(()=>{w.composer().send()},10)}catch(q){}},[w]),K=y.useCallback(P=>M(null,null,function*(){var q;if(!(C||!b))try{if(P.response){const J=(q=P.responseDelay)!=null?q:o;yield D(P.prompt,P.response,{delay:J,streamingSpeed:l})}else N(P.prompt)}catch(J){}}),[b,C,o,l,D,N]),B=y.useCallback(()=>M(null,null,function*(){try{const P=window.__cuadraThreadListRuntime,q=P==null?void 0:P.threadList;q!=null&&q.switchToNewThread&&(yield q.switchToNewThread())}catch(P){}}),[]);return y.useImperativeHandle(x,()=>({sendMessage:N,sendPreMadeQA:D,clearChat:B}),[N,D,B]),y.useEffect(()=>{var P,q;if(!b){_(!1);return}try{const J=b==null?void 0:b.store;if(!J){_(!1);return}const ue=(P=J.subscribe)==null?void 0:P.call(J,v=>{const Y=v==null?void 0:v.threadId,xe=(v==null?void 0:v.messages)||[],k=(v==null?void 0:v.isLoadingHistory)||!1,Se=xe.length;Y&&Y!==O&&z(Y),_(k&&Se===0)}),se=(q=J.getState)==null?void 0:q.call(J);if(se){const v=se==null?void 0:se.threadId,Y=(se==null?void 0:se.messages)||[],xe=(se==null?void 0:se.isLoadingHistory)||!1,k=Y.length;v&&v!==O&&z(v),_(xe&&k===0)}return()=>{ue&&ue()}}catch(J){_(!1)}},[b,O]),p.jsxs(ho,{className:"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full cuadra-relative",children:[g&&p.jsx(bv,{}),p.jsxs(co,{disabled:!s,className:`cuadra-flex-1 cuadra-flex cuadra-flex-col cuadra-min-h-0 cuadra-relative ${S?"cuadra-justify-center":""}`,children:[p.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:p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-3",children:[p.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:p.jsx(Yu,{className:"cuadra-h-6 cuadra-w-6"})}),p.jsx("p",{className:"cuadra-text-sm cuadra-font-medium cuadra-text-foreground font-brand",children:"Drop files here"})]})}),p.jsx(mo,{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":n||(g?"0.5rem":"2rem")},children:E?p.jsx("div",{className:"cuadra-absolute cuadra-inset-0 cuadra-flex cuadra-items-center cuadra-justify-center",children:p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-3",children:[p.jsx(ga,{className:"cuadra-h-5 cuadra-w-5 cuadra-animate-spin cuadra-text-muted-foreground"}),p.jsx("p",{className:"cuadra-text-sm cuadra-text-muted-foreground font-brand",children:"Loading messages..."})]})}):p.jsxs("div",{className:"cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full cuadra-px-4",children:[p.jsx(fo,{children:p.jsx(hv,{title:t,subtitle:r})}),p.jsx(ip,{components:{UserMessage:fv,AssistantMessage:gv}})]})}),p.jsx("div",{className:`cuadra-w-full cuadra-px-4 cuadra-pt-2 ${S?"cuadra-pb-2":"cuadra-pb-4"}`,style:u?{paddingBottom:"calc(env(safe-area-inset-bottom) + 1rem)"}:void 0,children:p.jsxs("div",{className:"cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full",children:[V&&p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-mb-2 cuadra-px-3 cuadra-py-2 cuadra-rounded-lg cuadra-text-xs font-brand cuadra-animate-in cuadra-fade-in cuadra-slide-in-from-bottom-2",style:{backgroundColor:"var(--cuadra-muted)",color:"var(--cuadra-foreground)",opacity:.85},children:[p.jsx(Hu,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-flex-shrink-0 cuadra-text-muted-foreground"}),p.jsx("span",{className:"cuadra-flex-1 cuadra-text-muted-foreground",children:V.message}),p.jsx("button",{type:"button",onClick:()=>Jt.clear(),className:"cuadra-flex-shrink-0 cuadra-p-0.5 cuadra-rounded hover:cuadra-bg-black/5 cuadra-transition-colors","aria-label":"Dismiss",children:p.jsx(wa,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})]}),s&&p.jsx(uo,{components:{Attachment:()=>{const P=ee(({attachment:q})=>q);return P?p.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:[p.jsx(ya,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground",strokeWidth:1.5}),p.jsx("span",{className:"cuadra-text-xs cuadra-text-foreground font-brand",children:P.name||"Attachment"}),p.jsx(ff,{asChild:!0,children:p.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:p.jsx(wa,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})})]}):null}}}),p.jsxs(eo,{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:d?"1px solid hsl(var(--cuadra-border))":"none"},children:[p.jsx(oo,{asChild:!0,children:p.jsx("textarea",{rows:1,placeholder:a,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"}})}),p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-px-3 cuadra-pb-2.5 cuadra-pt-1",children:[p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1",children:s&&p.jsx(Yf,{multiple:!0,asChild:!0,children:p.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:[p.jsx(ba,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground",strokeWidth:1.5}),p.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"})]})})}),p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[c&&c.length>0&&p.jsx(yv,{models:c,selectedModelId:f,onModelChange:h,threadIsEmpty:R,onNewChat:B}),p.jsx(Mf,{asChild:!0,children:p.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:p.jsx(Uu,{className:"cuadra-h-4 cuadra-w-4",strokeWidth:2})})})]})]})]})]})}),S&&i&&i.length>0&&p.jsx("div",{className:"cuadra-flex cuadra-flex-wrap cuadra-justify-center cuadra-gap-2 cuadra-px-4 cuadra-pb-6 cuadra-pt-1 cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full",children:i.map((P,q)=>p.jsx("button",{type:"button",onClick:()=>K(P),disabled:C,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:P.prompt},`suggestion-${q}`))})]})]})});function hv({title:e,subtitle:t}){return p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-text-center cuadra-py-6",children:[p.jsx("h2",{className:"cuadra-text-4xl cuadra-font-normal cuadra-text-muted-foreground cuadra-tracking-tight",style:{fontFamily:"var(--cuadra-font-logo), Outfit, -apple-system, sans-serif"},children:e}),t&&p.jsx("p",{className:"cuadra-text-base cuadra-text-muted-foreground/70 cuadra-mt-3 cuadra-max-w-lg cuadra-whitespace-pre-line",children:t})]})}function fv(){return p.jsx(ii,{className:"cuadra-flex cuadra-w-full cuadra-justify-end cuadra-py-2.5",children:p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-end cuadra-gap-2 cuadra-max-w-[80%]",children:[p.jsx(Qs,{components:{Attachment:()=>{var a;const e=ee(({attachment:s})=>s);if(!e)return null;const t=e.type==="image",r=e.file,n=(a=e.content)==null?void 0:a.find(s=>s.type==="image"),i=r?URL.createObjectURL(r):n==null?void 0:n.image;return p.jsx("div",{className:"cuadra-mb-1",children:t&&i?p.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)"}}):p.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:[p.jsx(ya,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground"}),p.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground font-brand",children:e.name||"Attachment"})]})})}}}),p.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:p.jsx(ai,{components:{Text:({text:e})=>p.jsx(sa,{content:e||""})}})})]})})}function pv({text:e}){const[t,r]=y.useState(!1),n=ee(({message:i})=>{var a;return((a=i==null?void 0:i.status)==null?void 0:a.type)==="running"});return e?n?p.jsx("div",{className:"cuadra-mb-3 cuadra-py-1",children:p.jsx("div",{className:"cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand cuadra-animate-text-shimmer",children:e})}):p.jsxs("div",{className:"cuadra-mb-3",children:[p.jsxs("button",{type:"button",onClick:()=>r(!t),className:"cuadra-flex cuadra-items-center cuadra-gap-1.5 cuadra-py-1 cuadra-text-sm cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-colors font-brand",children:[p.jsx(Mn,{className:`cuadra-h-3.5 cuadra-w-3.5 cuadra-shrink-0 cuadra-transition-transform cuadra-duration-200 ${t?"":"cuadra--rotate-90"}`}),p.jsx("span",{children:"Reasoning"})]}),p.jsx("div",{className:`cuadra-overflow-hidden cuadra-transition-all cuadra-duration-200 cuadra-ease-out ${t?"cuadra-max-h-[2000px] cuadra-opacity-100":"cuadra-max-h-0 cuadra-opacity-0"}`,children:p.jsx("div",{className:"cuadra-pl-5 cuadra-pt-2 cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand",children:p.jsx(sa,{content:e})})})]}):null}function mv(){return p.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:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1",children:[p.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}}),p.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}}),p.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}})]}),p.jsx("span",{children:"Thinking..."})]})}function gv(){const e=ee(({message:s})=>{var o;return((o=s==null?void 0:s.status)==null?void 0:o.type)==="running"}),t=ee(({message:s})=>{const o=s==null?void 0:s.content;return!o||!Array.isArray(o)?!1:o.some(l=>!!(l.type==="text"&&l.text&&l.text.length>0||l.type==="reasoning"&&l.text&&l.text.length>0))}),r=y.useRef(!1),[n,i]=y.useState(null);y.useEffect(()=>{if(e&&t&&!r.current){const s=xt.getCurrentMessageId();s&&(r.current=!0,i(s))}},[e,t]);const a=y.useSyncExternalStore(s=>xt.subscribe(s),()=>{var s,o;if(n){const l=xt.getForMessage(n);return(s=l.sources)!=null&&s.length?l.sources:null}if(e&&t){const l=xt.getCurrentMessageId();if(l){const u=xt.getForMessage(l);return(o=u.sources)!=null&&o.length?u.sources:null}}return null},()=>null);return p.jsx(ii,{className:"cuadra-flex cuadra-w-full cuadra-justify-start cuadra-py-2.5",children:p.jsxs("div",{className:"cuadra-text-foreground cuadra-max-w-full cuadra-break-words font-brand",style:{fontSize:"0.9375rem",lineHeight:"1.75"},children:[p.jsx(ai,{components:{Text:({text:s})=>p.jsx(sa,{content:s||""}),Reasoning:({text:s})=>p.jsx(pv,{text:s||""})}}),e&&!t&&p.jsx(mv,{}),a&&a.length>0&&p.jsx(lv,{sources:a})]})})}function kn({label:e,children:t}){return p.jsxs("span",{className:"cuadra-relative cuadra-inline-flex cuadra-group/tip",children:[t,p.jsx("span",{className:"cuadra-absolute cuadra-bottom-full cuadra-left-1/2 cuadra-mb-1.5 cuadra-hidden group-hover/tip:cuadra-flex cuadra-items-center cuadra-whitespace-nowrap cuadra-rounded-md cuadra-px-2 cuadra-py-1 cuadra-text-[10px] cuadra-pointer-events-none cuadra-z-50 font-brand",style:{backgroundColor:"var(--cuadra-popover)",color:"var(--cuadra-foreground)",boxShadow:"0 2px 8px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)",transform:"translateX(-50%)"},children:e})]})}function yv({models:e,selectedModelId:t,onModelChange:r,threadIsEmpty:n,onNewChat:i}){const[a,s]=y.useState(!1),o=e.find(u=>u.id===t)||e[0];if(!o)return null;const l=u=>M(null,null,function*(){s(!1),!n&&u!==t&&(yield i==null?void 0:i()),r==null||r(u)});return p.jsxs("div",{className:"cuadra-relative",children:[p.jsxs("button",{type:"button",onClick:()=>s(!a),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:[p.jsx("span",{children:o.name}),o.supportsReasoning&&p.jsx(kn,{label:"Reasoning",children:p.jsx(ha,{className:"cuadra-h-3 cuadra-w-3"})}),o.supportsVision&&p.jsx(kn,{label:"Vision",children:p.jsx(pa,{className:"cuadra-h-3 cuadra-w-3"})}),p.jsx(Mn,{className:"cuadra-h-3 cuadra-w-3"})]}),a&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:()=>s(!1)}),p.jsx("div",{className:"cuadra-absolute cuadra-bottom-full cuadra-right-0 cuadra-mb-2 cuadra-z-50 cuadra-rounded-xl cuadra-min-w-[200px] cuadra-py-1",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 4px 24px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)"},children:e.map(u=>p.jsxs("button",{type:"button",className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-justify-between cuadra-gap-3 cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted/60 cuadra-transition-colors font-brand",onClick:()=>l(u.id),children:[p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-min-w-0",children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1.5",children:[p.jsx("span",{className:"cuadra-text-foreground cuadra-truncate",children:u.name}),u.supportsReasoning&&p.jsx(kn,{label:"Reasoning",children:p.jsx(ha,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})}),u.supportsVision&&p.jsx(kn,{label:"Vision",children:p.jsx(pa,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})})]}),u.description&&p.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground",children:u.description})]}),u.id===t&&p.jsx(fa,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-primary cuadra-flex-shrink-0"})]},u.id))})]})]})}function bv(){const e=ee(({threadListItem:i})=>{var a;return(a=i==null?void 0:i.title)!=null?a:null}),[t,r]=y.useState(!1),n=e||"Untitled chat";return p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-px-3 cuadra-py-2 cuadra-min-h-[48px]",children:p.jsxs("div",{className:"cuadra-relative",children:[p.jsxs("button",{type:"button",onClick:()=>r(!t),className:"cuadra-flex cuadra-items-center cuadra-gap-1 cuadra-text-sm cuadra-text-foreground hover:cuadra-bg-muted/60 cuadra-rounded-lg cuadra-px-2 cuadra-py-1.5 cuadra-transition-colors font-brand",children:[p.jsx("span",{className:"cuadra-font-medium cuadra-truncate cuadra-max-w-[200px]",children:n}),p.jsx(Mn,{className:`cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground cuadra-flex-shrink-0 cuadra-transition-transform cuadra-duration-200 ${t?"cuadra-rotate-180":""}`})]}),t&&p.jsx(wv,{onClose:()=>r(!1)})]})})}function wv({onClose:e}){return p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:e}),p.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:p.jsxs(ko,{className:"cuadra-flex cuadra-flex-col",children:[p.jsx("div",{className:"cuadra-px-2 cuadra-py-1.5",children:p.jsxs(wo,{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:[p.jsx(ba,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"New Chat"]})}),p.jsx(xv,{onSelect:e})]})})]})}function xv({onSelect:e}){const t=ee(({threads:i})=>{var a;return(a=i==null?void 0:i.threadIds)!=null?a:[]}),r=ee(({threads:i})=>i==null?void 0:i.newThreadId);return t.some(i=>i!==r)?p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-mx-3 cuadra-my-0.5",style:{borderTop:"1px solid rgba(0,0,0,0.06)"}}),p.jsx("div",{className:"cuadra-overflow-y-auto cuadra-px-2 cuadra-pb-1.5 scrollbar-thin",style:{maxHeight:"340px"},children:p.jsx(vo,{components:{ThreadListItem:i=>p.jsx(vv,I(m({},i),{onSelect:e}))}})})]}):null}function vv({onSelect:e}){const t=vs(),r=xs(),n=Xd(),i=ws(b=>b.threadId),a=(t==null?void 0:t.id)===i,[s,o]=y.useState(!1),[l,u]=y.useState(!1),[d,c]=y.useState((t==null?void 0:t.title)||""),[f,h]=y.useState(!1),g=()=>M(null,null,function*(){if(!(t!=null&&t.remoteId)||!d||d===t.title){u(!1);return}try{h(!0),yield r.rename(d)}catch(b){}finally{h(!1),u(!1)}}),x=b=>M(null,null,function*(){b.stopPropagation();try{yield r.delete(),a&&(yield n.switchToNewThread())}catch(w){console.error("[CuadraChat] Failed to delete thread:",w)}});return y.useEffect(()=>{t!=null&&t.title&&!l&&c(t.title)},[t==null?void 0:t.title,l]),t?p.jsxs(So,{className:`cuadra-relative cuadra-flex cuadra-items-center cuadra-rounded-lg cuadra-transition-colors cuadra-cursor-pointer ${a?"cuadra-bg-muted":"hover:cuadra-bg-muted/60"}`,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),children:[l?p.jsx("div",{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0",onClick:b=>b.stopPropagation(),onMouseDown:b=>b.stopPropagation(),onKeyDown:b=>b.stopPropagation(),onKeyUp:b=>b.stopPropagation(),onKeyPress:b=>b.stopPropagation(),children:p.jsx("input",{className:"cuadra-w-full cuadra-bg-transparent cuadra-border-0 cuadra-border-b cuadra-text-sm cuadra-text-foreground cuadra-py-0.5 cuadra-px-0 cuadra-outline-none font-brand",style:{borderBottomColor:"var(--cuadra-primary)",borderBottomWidth:"1.5px"},value:d,onChange:b=>c(b.target.value),onKeyDown:b=>{b.stopPropagation(),b.key==="Enter"&&g(),b.key==="Escape"&&(u(!1),c(t.title||""))},onBlur:()=>void g(),disabled:f,autoFocus:!0})}):p.jsx(sp,{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0 cuadra-cursor-pointer",onClick:()=>e==null?void 0:e(),children:p.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground cuadra-truncate cuadra-block cuadra-text-left font-brand",children:t.title||"Chat"})}),(s||a)&&!l&&p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-0.5 cuadra-mr-1.5 cuadra-flex-shrink-0",children:[p.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-background/60 cuadra-transition-colors",onClick:b=>{b.stopPropagation(),u(!0),c(t.title||"Chat")},title:"Rename",children:p.jsx(Ju,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})}),p.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-destructive/10 cuadra-transition-colors",onClick:x,title:"Delete",children:p.jsx(Ku,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-destructive"})})]})]}):null}const oa=({children:e,className:t="",paddingX:r="px-0",paddingY:n="py-0",borderSizePx:i=2,style:a,contentStyle:s})=>p.jsx("div",{className:`cuadra-relative cuadra-bg-background md:cuadra-rounded-lg cuadra-overflow-hidden cuadra-flex cuadra-flex-col ${r} ${n} ${t}`,style:m(m({border:i>0?`${i}px solid var(--cuadra-primary)`:"none"},a),s),children:e}),kv=y.createContext(void 0),la=({children:e,value:t})=>p.jsx(kv.Provider,{value:t,children:e});function Sv(){y.useEffect(()=>{if(document.querySelector("style[data-cuadra-uikit]"))return;const t=document.createElement("div");t.className="cuadra-flex",document.body.appendChild(t);const r=window.getComputedStyle(t).display==="flex";if(document.body.removeChild(t),r)return;const 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=="undefined"&&typeof location=="undefined"?require("url").pathToFileURL(__filename).href:typeof document=="undefined"?location.href:$e&&$e.tagName.toUpperCase()==="SCRIPT"&&$e.src||new URL("cuadra-uikit.umd.js",document.baseURI).href).href];let a=!1;for(const s of i)if(n.href=s,n.onload=()=>{a=!0},n.onerror=()=>{},document.head.appendChild(n),a)break},[])}const Au=y.forwardRef(function({config:t},r){Sv();const n=y.useRef(null),i=y.useRef(!1),{baseUrl:a,proxyUrl:s,sessionToken:o,mode:l="multiChat",modelMode:u="fixed",modelId:d,onModelChange:c,ephemeral:f=!1,systemPrompt:h,enableReasoning:g=!1,initialThreadId:x,welcomeTitle:b,welcomeSubtitle:w,extraTopPadding:E,suggestions:_,inputPlaceholder:O,preMadeResponseDelay:z=1e3,streamingSpeed:C=50,initialMessage:U,initialPreMadeQA:V,theme:R="system",onError:S,onChatCreated:D,onUserMessage:N,onThreadIdUpdate:K,enableAttachments:B=!1,supportsVision:P,onBeforeRequest:q,mockResponseOnBlocked:J}=t;y.useImperativeHandle(r,()=>({sendMessage:G=>{var be;(be=n.current)==null||be.sendMessage(G)},sendPreMadeQA:(G,be,me)=>{var Dt;(Dt=n.current)==null||Dt.sendPreMadeQA(G,be,me)},clearChat:()=>{var G;(G=n.current)==null||G.clearChat()}}),[]),y.useEffect(()=>{if(i.current)return;const G=setTimeout(()=>{var be,me;V?(i.current=!0,(be=n.current)==null||be.sendPreMadeQA(V.question,V.answer,{delay:z,streamingSpeed:C})):U&&(i.current=!0,(me=n.current)==null||me.sendMessage(U))},500);return()=>clearTimeout(G)},[U,V,z,C]);const ue=s||a||"",se=!!s,v=y.useMemo(()=>new _o(ue,o||void 0,se),[ue,o,se]),[Y,xe]=y.useState(null),[k,Se]=y.useState(!1),[Ye,_e]=y.useState(null),[j,re]=y.useState(!1);y.useEffect(()=>{l==="multiChat"&&re(!0)},[l]);const le=y.useCallback(()=>M(null,null,function*(){if(u==="selector"){Se(!0),_e(null);try{const G=yield v.listModels();xe(G)}catch(G){_e(G instanceof Error?G:new Error("Failed to load models"))}finally{Se(!1)}}}),[v,u]);y.useEffect(()=>{u==="selector"&&le()},[u,le]),y.useEffect(()=>(typeof window!="undefined"&&(window.__cuadraUIKitRefetchModels=le),()=>{typeof window!="undefined"&&delete window.__cuadraUIKitRefetchModels}),[le]);const[oe,Ee]=y.useState(u==="fixed"&&d||null),ne=y.useRef(oe),we=y.useCallback(G=>{const be=ne.current;Ee(G),ne.current=G,c==null||c(G),be!==null&&be!==G&&l==="multiChat"&&setTimeout(()=>{var Dt,_n;const me=window.__cuadraThreadListRuntime;if((Dt=me==null?void 0:me.threads)!=null&&Dt.switchToNewThread)try{me.threads.switchToNewThread()}catch(Tn){}else if((_n=me==null?void 0:me.threads)!=null&&_n.createThread)try{me.threads.createThread()}catch(Tn){}else if(me!=null&&me.switchToNewThread)try{me.switchToNewThread()}catch(Tn){}},100)},[c,l]);y.useEffect(()=>{if(u==="selector"&&(Y!=null&&Y.items)&&Y.items.length>0&&!oe){const G=Y.items[0];if(G!=null&&G.id){const be=G.id;Ee(be),c==null||c(be)}}},[u,Y==null?void 0:Y.items,oe,c]);const ot=u==="fixed"?!!d:!!oe,lt=y.useMemo(()=>{var G;if(P!==void 0)return P;if(u==="selector"&&oe&&(Y!=null&&Y.items)){const be=Y.items.find(me=>me.id===oe);return(G=be==null?void 0:be.supportsVision)!=null?G:!0}return!0},[P,u,oe,Y==null?void 0:Y.items]),ht=y.useMemo(()=>((Y==null?void 0:Y.items)||[]).filter(G=>(G==null?void 0:G.id)&&(G==null?void 0:G.displayName)).map(G=>{var be,me;return{id:G.id,name:G.displayName,supportsVision:(be=G.supportsVision)!=null?be:!1,supportsReasoning:(me=G.supportsReasoning)!=null?me:!1}}),[Y]),St=y.useMemo(()=>({currentModelId:oe||"",models:ht,modelsLoading:k,modelsError:Ye,onModelChange:we,refetchModels:le}),[oe,ht,k,Ye,we,le]);return u==="selector"&&k||l==="multiChat"&&j?p.jsx(la,{value:St,children:p.jsx(oa,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",borderSizePx:t.borderless?0:2,children:p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:p.jsx(ga,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"})})})}):u==="selector"&&!ot&&Ye?p.jsx(la,{value:St,children:p.jsx(oa,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",children:p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2",children:p.jsx("p",{className:"cuadra-text-sm cuadra-text-destructive font-brand",children:"Failed to load models"})})})})}):p.jsx("div",{className:"cuadra-uikit cuadra-h-full cuadra-w-full",style:{height:"100%",width:"100%"},children:p.jsx(la,{value:St,children:p.jsx(xp,{baseUrl:se?ue:a||ue,sessionToken:o,isProxyMode:se,mode:l,modelMode:u,modelId:oe||d||void 0,onModelChange:we,ephemeral:f,systemPrompt:h,enableReasoning:g,initialThreadId:x,enableAttachments:B,supportsVision:lt,onError:S,onChatCreated:D,onUserMessage:N,onThreadIdUpdate:K,onBeforeRequest:q,mockResponseOnBlocked:J,onChatsLoaded:()=>{l==="multiChat"&&re(!1)},children:p.jsx(oa,{paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",className:`cuadra-h-full ${t.containerClass||""}`,borderSizePx:t.borderless?0:2,style:{height:"100%"},children:p.jsx("div",{className:"cuadra-h-full cuadra-flex cuadra-relative",style:{height:"100%"},children:p.jsx("div",{className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:p.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0",children:p.jsx(dv,{ref:n,welcomeTitle:b,welcomeSubtitle:w,extraTopPadding:E,suggestions:_,inputPlaceholder:O,enableAttachments:B,preMadeResponseDelay:z,streamingSpeed:C,safeArea:t.safeArea,showChatHeader:l==="multiChat",models:u==="selector"?ht:void 0,selectedModelId:oe||void 0,onModelChange:u==="selector"?we:void 0,theme:R})})})})})})})})});class Sn{constructor(){T(this,"config",null);T(this,"root",null);T(this,"container",null);T(this,"instances",new Map)}init(t){if(!t.baseUrl&&!t.proxyUrl)throw new Error("Either baseUrl or proxyUrl is required");if(t.modelMode==="fixed"&&t.modelId!==void 0&&(!t.modelId||t.modelId.trim()===""))throw new Error("modelId cannot be empty when explicitly provided. Omit modelId to let backend resolve it.");const r=t.containerId||"cuadra-chat";let n=document.getElementById(r);n||(n=document.createElement("div"),n.id=r,document.body.appendChild(n)),t.containerClass&&n.classList.add(...t.containerClass.split(" ")),this.config=I(m({},t),{containerId:r}),this.container=n,this.root=ge.createRoot(n),this.root.render(y.createElement(Mu,{config:this.config})),this.instances.set(r,this)}destroy(t){var i;const r=t||((i=this.config)==null?void 0:i.containerId);if(!r)return;const n=this.instances.get(r);n!=null&&n.root&&(n.root.unmount(),n.root=null),n!=null&&n.container&&n.container.parentNode&&n.container.parentNode.removeChild(n.container),this.instances.delete(r)}updateConfig(t,r){var s;const n=r||((s=this.config)==null?void 0:s.containerId);if(!n)return;const i=this.instances.get(n);if(!(i!=null&&i.config))return;const a=m(m({},i.config),t);i.config=a,i.root&&i.container&&i.root.render(y.createElement(Mu,{config:a}))}getInstance(t){var n;const r=t||((n=this.config)==null?void 0:n.containerId);return r&&this.instances.get(r)||null}static parseConfigFromAttributes(t,r){const n={};return t.dataset.baseUrl&&(n.baseUrl=t.dataset.baseUrl),t.dataset.proxyUrl&&(n.proxyUrl=t.dataset.proxyUrl),t.dataset.sessionToken&&(n.sessionToken=t.dataset.sessionToken),t.dataset.containerId&&(n.containerId=t.dataset.containerId),t.dataset.containerClass&&(n.containerClass=t.dataset.containerClass),t.dataset.mode&&(n.mode=t.dataset.mode),t.dataset.modelMode&&(n.modelMode=t.dataset.modelMode),t.dataset.modelId&&(n.modelId=t.dataset.modelId),t.dataset.ephemeral&&(n.ephemeral=t.dataset.ephemeral==="true"),t.dataset.systemPrompt&&(n.systemPrompt=t.dataset.systemPrompt),r&&(r.dataset.baseUrl&&(n.baseUrl=r.dataset.baseUrl),r.dataset.proxyUrl&&(n.proxyUrl=r.dataset.proxyUrl),r.dataset.sessionToken&&(n.sessionToken=r.dataset.sessionToken),r.dataset.mode&&(n.mode=r.dataset.mode),r.dataset.modelMode&&(n.modelMode=r.dataset.modelMode),r.dataset.modelId&&(n.modelId=r.dataset.modelId)),n}}const Mu=({config:e})=>p.jsx(Au,{config:e});let ze=null;typeof window!="undefined"&&(ze=new Sn);const Pu={init:e=>(ze||(ze=new Sn),ze.init(e)),destroy:e=>ze==null?void 0:ze.destroy(e),updateConfig:(e,t)=>ze==null?void 0:ze.updateConfig(e,t),getInstance:e=>ze==null?void 0:ze.getInstance(e),refetchModels:()=>{if(typeof window!="undefined"){const e=window.__cuadraUIKitRefetchModels;e&&e()}},version:"0.1.0"};if(typeof window!="undefined"){window.CuadraUIKit=Pu;const e=()=>{const t=document.querySelectorAll('script[src*="cuadra-uikit"]'),r=Array.from(t).find(n=>(n.getAttribute("src")||"").includes("cuadra-uikit.umd.js"));r&&r.dataset.autoInit!=="false"&&_v(r)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):setTimeout(e,0)}function _v(e){if(!e||!ze)return;const t=Sn.parseConfigFromAttributes(e),r=t.containerId||"cuadra-chat",n=document.getElementById(r);if(n){const i=Sn.parseConfigFromAttributes(e,n);Object.assign(t,i)}(t.baseUrl||t.proxyUrl)&&ze.init(t)}$.WidgetContent=Au,$.default=Pu,Object.defineProperties($,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
|
31
|
+
`+(a===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
|
|
32
|
+
`))+1))}const i="#".repeat(a),o=r.enter("headingAtx"),l=r.enter("phrasing");s.move(i+" ");let u=r.containerPhrasing(e,m({before:"# ",after:`
|
|
33
|
+
`},s.current()));return/^[\t ]/.test(u)&&(u=Er(u.charCodeAt(0))+u.slice(1)),u=u?i+" "+u:i,r.options.closeAtx&&(u+=" "+i),l(),o(),u}cu.peek=Kx;function cu(e){return e.value||""}function Kx(){return"<"}du.peek=Yx;function du(e,t,r,n){const a=us(r),s=a==='"'?"Quote":"Apostrophe",i=r.enter("image");let o=r.enter("label");const l=r.createTracker(n);let u=l.move("![");return u+=l.move(r.safe(e.alt,m({before:u,after:"]"},l.current()))),u+=l.move("]("),o(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(o=r.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(r.safe(e.url,m({before:u,after:">"},l.current()))),u+=l.move(">")):(o=r.enter("destinationRaw"),u+=l.move(r.safe(e.url,m({before:u,after:e.title?" ":")"},l.current())))),o(),e.title&&(o=r.enter(`title${s}`),u+=l.move(" "+a),u+=l.move(r.safe(e.title,m({before:u,after:a},l.current()))),u+=l.move(a),o()),u+=l.move(")"),i(),u}function Yx(){return"!"}hu.peek=Gx;function hu(e,t,r,n){const a=e.referenceType,s=r.enter("imageReference");let i=r.enter("label");const o=r.createTracker(n);let l=o.move("![");const u=r.safe(e.alt,m({before:l,after:"]"},o.current()));l+=o.move(u+"]["),i();const d=r.stack;r.stack=[],i=r.enter("reference");const c=r.safe(r.associationId(e),m({before:l,after:"]"},o.current()));return i(),r.stack=d,s(),a==="full"||!u||u!==c?l+=o.move(c+"]"):a==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function Gx(){return"!"}fu.peek=Xx;function fu(e,t,r){let n=e.value||"",a="`",s=-1;for(;new RegExp("(^|[^`])"+a+"([^`]|$)").test(n);)a+="`";for(/[^ \r\n]/.test(n)&&(/^[ \r\n]/.test(n)&&/[ \r\n]$/.test(n)||/^`|`$/.test(n))&&(n=" "+n+" ");++s<r.unsafe.length;){const i=r.unsafe[s],o=r.compilePattern(i);let l;if(i.atBreak)for(;l=o.exec(n);){let u=l.index;n.charCodeAt(u)===10&&n.charCodeAt(u-1)===13&&u--,n=n.slice(0,u)+" "+n.slice(l.index+1)}}return a+n+a}function Xx(){return"`"}function pu(e,t){const r=Pa(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(r===e.url||"mailto:"+r===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}mu.peek=Qx;function mu(e,t,r,n){const a=us(r),s=a==='"'?"Quote":"Apostrophe",i=r.createTracker(n);let o,l;if(pu(e,r)){const d=r.stack;r.stack=[],o=r.enter("autolink");let c=i.move("<");return c+=i.move(r.containerPhrasing(e,m({before:c,after:">"},i.current()))),c+=i.move(">"),o(),r.stack=d,c}o=r.enter("link"),l=r.enter("label");let u=i.move("[");return u+=i.move(r.containerPhrasing(e,m({before:u,after:"]("},i.current()))),u+=i.move("]("),l(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(l=r.enter("destinationLiteral"),u+=i.move("<"),u+=i.move(r.safe(e.url,m({before:u,after:">"},i.current()))),u+=i.move(">")):(l=r.enter("destinationRaw"),u+=i.move(r.safe(e.url,m({before:u,after:e.title?" ":")"},i.current())))),l(),e.title&&(l=r.enter(`title${s}`),u+=i.move(" "+a),u+=i.move(r.safe(e.title,m({before:u,after:a},i.current()))),u+=i.move(a),l()),u+=i.move(")"),o(),u}function Qx(e,t,r){return pu(e,r)?"<":"["}gu.peek=Zx;function gu(e,t,r,n){const a=e.referenceType,s=r.enter("linkReference");let i=r.enter("label");const o=r.createTracker(n);let l=o.move("[");const u=r.containerPhrasing(e,m({before:l,after:"]"},o.current()));l+=o.move(u+"]["),i();const d=r.stack;r.stack=[],i=r.enter("reference");const c=r.safe(r.associationId(e),m({before:l,after:"]"},o.current()));return i(),r.stack=d,s(),a==="full"||!u||u!==c?l+=o.move(c+"]"):a==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function Zx(){return"["}function cs(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function ew(e){const t=cs(e),r=e.options.bulletOther;if(!r)return t==="*"?"-":"*";if(r!=="*"&&r!=="+"&&r!=="-")throw new Error("Cannot serialize items with `"+r+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(r===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+r+"`) to be different");return r}function tw(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function yu(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function rw(e,t,r,n){const a=r.enter("list"),s=r.bulletCurrent;let i=e.ordered?tw(r):cs(r);const o=e.ordered?i==="."?")":".":ew(r);let l=t&&r.bulletLastUsed?i===r.bulletLastUsed:!1;if(!e.ordered){const d=e.children?e.children[0]:void 0;if((i==="*"||i==="-")&&d&&(!d.children||!d.children[0])&&r.stack[r.stack.length-1]==="list"&&r.stack[r.stack.length-2]==="listItem"&&r.stack[r.stack.length-3]==="list"&&r.stack[r.stack.length-4]==="listItem"&&r.indexStack[r.indexStack.length-1]===0&&r.indexStack[r.indexStack.length-2]===0&&r.indexStack[r.indexStack.length-3]===0&&(l=!0),yu(r)===i&&d){let c=-1;for(;++c<e.children.length;){const f=e.children[c];if(f&&f.type==="listItem"&&f.children&&f.children[0]&&f.children[0].type==="thematicBreak"){l=!0;break}}}}l&&(i=o),r.bulletCurrent=i;const u=r.containerFlow(e,n);return r.bulletLastUsed=i,r.bulletCurrent=s,a(),u}function nw(e){const t=e.options.listItemIndent||"one";if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function aw(e,t,r,n){const a=nw(r);let s=r.bulletCurrent||cs(r);t&&t.type==="list"&&t.ordered&&(s=(typeof t.start=="number"&&t.start>-1?t.start:1)+(r.options.incrementListMarker===!1?0:t.children.indexOf(e))+s);let i=s.length+1;(a==="tab"||a==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(i=Math.ceil(i/4)*4);const o=r.createTracker(n);o.move(s+" ".repeat(i-s.length)),o.shift(i);const l=r.enter("listItem"),u=r.indentLines(r.containerFlow(e,o.current()),d);return l(),u;function d(c,f,h){return f?(h?"":" ".repeat(i))+c:(h?s:s+" ".repeat(i-s.length))+c}}function sw(e,t,r,n){const a=r.enter("paragraph"),s=r.enter("phrasing"),i=r.containerPhrasing(e,n);return s(),a(),i}const iw=xn(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function ow(e,t,r,n){return(e.children.some(function(i){return iw(i)})?r.containerPhrasing:r.containerFlow).call(r,e,n)}function lw(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}bu.peek=uw;function bu(e,t,r,n){const a=lw(r),s=r.enter("strong"),i=r.createTracker(n),o=i.move(a+a);let l=i.move(r.containerPhrasing(e,m({after:a,before:o},i.current())));const u=l.charCodeAt(0),d=kn(n.before.charCodeAt(n.before.length-1),u,a);d.inside&&(l=Er(u)+l.slice(1));const c=l.charCodeAt(l.length-1),f=kn(n.after.charCodeAt(0),c,a);f.inside&&(l=l.slice(0,-1)+Er(c));const h=i.move(a+a);return s(),r.attentionEncodeSurroundingInfo={after:f.outside,before:d.outside},o+l+h}function uw(e,t,r){return r.options.strong||"*"}function cw(e,t,r,n){return r.safe(e.value,n)}function dw(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function hw(e,t,r){const n=(yu(r)+(r.options.ruleSpaces?" ":"")).repeat(dw(r));return r.options.ruleSpaces?n.slice(0,-1):n}const xu={blockquote:Ox,break:lu,code:$x,definition:Hx,emphasis:uu,hardBreak:lu,heading:Jx,html:cu,image:du,imageReference:hu,inlineCode:fu,link:mu,linkReference:gu,list:rw,listItem:aw,paragraph:sw,root:ow,strong:bu,text:cw,thematicBreak:hw};function fw(){return{enter:{table:pw,tableData:wu,tableHeader:wu,tableRow:gw},exit:{codeText:yw,table:mw,tableData:ds,tableHeader:ds,tableRow:ds}}}function pw(e){const t=e._align;this.enter({type:"table",align:t.map(function(r){return r==="none"?null:r}),children:[]},e),this.data.inTable=!0}function mw(e){this.exit(e),this.data.inTable=void 0}function gw(e){this.enter({type:"tableRow",children:[]},e)}function ds(e){this.exit(e)}function wu(e){this.enter({type:"tableCell",children:[]},e)}function yw(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,bw));const r=this.stack[this.stack.length-1];r.type,r.value=t,this.exit(e)}function bw(e,t){return t==="|"?t:e}function xw(e){const t=e||{},r=t.tableCellPadding,n=t.tablePipeAlign,a=t.stringLength,s=r?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
34
|
+
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:i,tableCell:l,tableRow:o}};function i(h,g,w,x){return u(d(h,w,x),h.align)}function o(h,g,w,x){const y=c(h,w,x),E=u([y]);return E.slice(0,E.indexOf(`
|
|
35
|
+
`))}function l(h,g,w,x){const y=w.enter("tableCell"),E=w.enter("phrasing"),_=w.containerPhrasing(h,I(m({},x),{before:s,after:s}));return E(),y(),_}function u(h,g){return Lx(h,{align:g,alignDelimiters:n,padding:r,stringLength:a})}function d(h,g,w){const x=h.children;let y=-1;const E=[],_=g.enter("table");for(;++y<x.length;)E[y]=c(x[y],g,w);return _(),E}function c(h,g,w){const x=h.children;let y=-1;const E=[],_=g.enter("tableRow");for(;++y<x.length;)E[y]=l(x[y],h,g,w);return _(),E}function f(h,g,w){let x=xu.inlineCode(h,g,w);return w.stack.includes("tableCell")&&(x=x.replace(/\|/g,"\\$&")),x}}function ww(){return{exit:{taskListCheckValueChecked:vu,taskListCheckValueUnchecked:vu,paragraph:kw}}}function vw(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:Sw}}}function vu(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function kw(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const r=this.stack[this.stack.length-1];r.type;const n=r.children[0];if(n&&n.type==="text"){const a=t.children;let s=-1,i;for(;++s<a.length;){const o=a[s];if(o.type==="paragraph"){i=o;break}}i===r&&(n.value=n.value.slice(1),n.value.length===0?r.children.shift():r.position&&n.position&&typeof n.position.start.offset=="number"&&(n.position.start.column++,n.position.start.offset++,r.position.start=Object.assign({},n.position.start)))}}this.exit(e)}function Sw(e,t,r,n){const a=e.children[0],s=typeof e.checked=="boolean"&&a&&a.type==="paragraph",i="["+(e.checked?"x":" ")+"] ",o=r.createTracker(n);s&&o.move(i);let l=xu.listItem(e,t,r,m(m({},n),o.current()));return s&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),l;function u(d){return d+i}}function _w(){return[rx(),Sx(),Ix(),fw(),ww()]}function Tw(e){return{extensions:[nx(),_x(e),Ex(),xw(e),vw()]}}const Cw={tokenize:Nw,partial:!0},ku={tokenize:Lw,partial:!0},Su={tokenize:Dw,partial:!0},_u={tokenize:Ow,partial:!0},Iw={tokenize:Fw,partial:!0},Tu={name:"wwwAutolink",tokenize:Mw,previous:Iu},Cu={name:"protocolAutolink",tokenize:Pw,previous:Eu},dt={name:"emailAutolink",tokenize:Aw,previous:Au},it={};function Ew(){return{text:it}}let Nt=48;for(;Nt<123;)it[Nt]=dt,Nt++,Nt===58?Nt=65:Nt===91&&(Nt=97);it[43]=dt,it[45]=dt,it[46]=dt,it[95]=dt,it[72]=[dt,Cu],it[104]=[dt,Cu],it[87]=[dt,Tu],it[119]=[dt,Tu];function Aw(e,t,r){const n=this;let a,s;return i;function i(c){return!hs(c)||!Au.call(n,n.previous)||fs(n.events)?r(c):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),o(c))}function o(c){return hs(c)?(e.consume(c),o):c===64?(e.consume(c),l):r(c)}function l(c){return c===46?e.check(Iw,d,u)(c):c===45||c===95||Ne(c)?(s=!0,e.consume(c),l):d(c)}function u(c){return e.consume(c),a=!0,l}function d(c){return s&&a&&Fe(n.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(c)):r(c)}}function Mw(e,t,r){const n=this;return a;function a(i){return i!==87&&i!==119||!Iu.call(n,n.previous)||fs(n.events)?r(i):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(Cw,e.attempt(ku,e.attempt(Su,s),r),r)(i))}function s(i){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(i)}}function Pw(e,t,r){const n=this;let a="",s=!1;return i;function i(c){return(c===72||c===104)&&Eu.call(n,n.previous)&&!fs(n.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),a+=String.fromCodePoint(c),e.consume(c),o):r(c)}function o(c){if(Fe(c)&&a.length<5)return a+=String.fromCodePoint(c),e.consume(c),o;if(c===58){const f=a.toLowerCase();if(f==="http"||f==="https")return e.consume(c),l}return r(c)}function l(c){return c===47?(e.consume(c),s?u:(s=!0,l)):r(c)}function u(c){return c===null||cn(c)||de(c)||Pt(c)||dn(c)?r(c):e.attempt(ku,e.attempt(Su,d),r)(c)}function d(c){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(c)}}function Nw(e,t,r){let n=0;return a;function a(i){return(i===87||i===119)&&n<3?(n++,e.consume(i),a):i===46&&n===3?(e.consume(i),s):r(i)}function s(i){return i===null?r(i):t(i)}}function Lw(e,t,r){let n,a,s;return i;function i(u){return u===46||u===95?e.check(_u,l,o)(u):u===null||de(u)||Pt(u)||u!==45&&dn(u)?l(u):(s=!0,e.consume(u),i)}function o(u){return u===95?n=!0:(a=n,n=void 0),e.consume(u),i}function l(u){return a||n||!s?r(u):t(u)}}function Dw(e,t){let r=0,n=0;return a;function a(i){return i===40?(r++,e.consume(i),a):i===41&&n<r?s(i):i===33||i===34||i===38||i===39||i===41||i===42||i===44||i===46||i===58||i===59||i===60||i===63||i===93||i===95||i===126?e.check(_u,t,s)(i):i===null||de(i)||Pt(i)?t(i):(e.consume(i),a)}function s(i){return i===41&&n++,e.consume(i),a}}function Ow(e,t,r){return n;function n(o){return o===33||o===34||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===63||o===95||o===126?(e.consume(o),n):o===38?(e.consume(o),s):o===93?(e.consume(o),a):o===60||o===null||de(o)||Pt(o)?t(o):r(o)}function a(o){return o===null||o===40||o===91||de(o)||Pt(o)?t(o):n(o)}function s(o){return Fe(o)?i(o):r(o)}function i(o){return o===59?(e.consume(o),n):Fe(o)?(e.consume(o),i):r(o)}}function Fw(e,t,r){return n;function n(s){return e.consume(s),a}function a(s){return Ne(s)?r(s):t(s)}}function Iu(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||de(e)}function Eu(e){return!Fe(e)}function Au(e){return!(e===47||hs(e))}function hs(e){return e===43||e===45||e===46||e===95||Ne(e)}function fs(e){let t=e.length,r=!1;for(;t--;){const n=e[t][1];if((n.type==="labelLink"||n.type==="labelImage")&&!n._balanced){r=!0;break}if(n._gfmAutolinkLiteralWalkedInto){r=!1;break}}return e.length>0&&!r&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const zw={tokenize:Vw,partial:!0};function Bw(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Uw,continuation:{tokenize:Hw},exit:qw}},text:{91:{name:"gfmFootnoteCall",tokenize:$w},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Rw,resolveTo:jw}}}}function Rw(e,t,r){const n=this;let a=n.events.length;const s=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let i;for(;a--;){const l=n.events[a][1];if(l.type==="labelImage"){i=l;break}if(l.type==="gfmFootnoteCall"||l.type==="labelLink"||l.type==="label"||l.type==="image"||l.type==="link")break}return o;function o(l){if(!i||!i._balanced)return r(l);const u=et(n.sliceSerialize({start:i.end,end:n.now()}));return u.codePointAt(0)!==94||!s.includes(u.slice(1))?r(l):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(l),e.exit("gfmFootnoteCallLabelMarker"),t(l))}}function jw(e,t){let r=e.length;for(;r--;)if(e[r][1].type==="labelImage"&&e[r][0]==="enter"){e[r][1];break}e[r+1][1].type="data",e[r+3][1].type="gfmFootnoteCallLabelMarker";const n={type:"gfmFootnoteCall",start:Object.assign({},e[r+3][1].start),end:Object.assign({},e[e.length-1][1].end)},a={type:"gfmFootnoteCallMarker",start:Object.assign({},e[r+3][1].end),end:Object.assign({},e[r+3][1].end)};a.end.column++,a.end.offset++,a.end._bufferIndex++;const s={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},e[e.length-1][1].start)},i={type:"chunkString",contentType:"string",start:Object.assign({},s.start),end:Object.assign({},s.end)},o=[e[r+1],e[r+2],["enter",n,t],e[r+3],e[r+4],["enter",a,t],["exit",a,t],["enter",s,t],["enter",i,t],["exit",i,t],["exit",s,t],e[e.length-2],e[e.length-1],["exit",n,t]];return e.splice(r,e.length-r+1,...o),e}function $w(e,t,r){const n=this,a=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let s=0,i;return o;function o(c){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),l}function l(c){return c!==94?r(c):(e.enter("gfmFootnoteCallMarker"),e.consume(c),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(c){if(s>999||c===93&&!i||c===null||c===91||de(c))return r(c);if(c===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return a.includes(et(n.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(c)}return de(c)||(i=!0),s++,e.consume(c),c===92?d:u}function d(c){return c===91||c===92||c===93?(e.consume(c),s++,u):u(c)}}function Uw(e,t,r){const n=this,a=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let s,i=0,o;return l;function l(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(g){return g===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",d):r(g)}function d(g){if(i>999||g===93&&!o||g===null||g===91||de(g))return r(g);if(g===93){e.exit("chunkString");const w=e.exit("gfmFootnoteDefinitionLabelString");return s=et(n.sliceSerialize(w)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return de(g)||(o=!0),i++,e.consume(g),g===92?c:d}function c(g){return g===91||g===92||g===93?(e.consume(g),i++,d):d(g)}function f(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),a.includes(s)||a.push(s),se(e,h,"gfmFootnoteDefinitionWhitespace")):r(g)}function h(g){return t(g)}}function Hw(e,t,r){return e.check(kr,t,e.attempt(zw,t,r))}function qw(e){e.exit("gfmFootnoteDefinition")}function Vw(e,t,r){const n=this;return se(e,a,"gfmFootnoteDefinitionIndent",5);function a(s){const i=n.events[n.events.length-1];return i&&i[1].type==="gfmFootnoteDefinitionIndent"&&i[2].sliceSerialize(i[1],!0).length===4?t(s):r(s)}}function Ww(e){let r=(e||{}).singleTilde;const n={name:"strikethrough",tokenize:s,resolveAll:a};return r==null&&(r=!0),{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function a(i,o){let l=-1;for(;++l<i.length;)if(i[l][0]==="enter"&&i[l][1].type==="strikethroughSequenceTemporary"&&i[l][1]._close){let u=l;for(;u--;)if(i[u][0]==="exit"&&i[u][1].type==="strikethroughSequenceTemporary"&&i[u][1]._open&&i[l][1].end.offset-i[l][1].start.offset===i[u][1].end.offset-i[u][1].start.offset){i[l][1].type="strikethroughSequence",i[u][1].type="strikethroughSequence";const d={type:"strikethrough",start:Object.assign({},i[u][1].start),end:Object.assign({},i[l][1].end)},c={type:"strikethroughText",start:Object.assign({},i[u][1].end),end:Object.assign({},i[l][1].start)},f=[["enter",d,o],["enter",i[u][1],o],["exit",i[u][1],o],["enter",c,o]],h=o.parser.constructs.insideSpan.null;h&&qe(f,f.length,0,hn(h,i.slice(u+1,l),o)),qe(f,f.length,0,[["exit",c,o],["enter",i[l][1],o],["exit",i[l][1],o],["exit",d,o]]),qe(i,u-1,l-u+3,f),l=u+f.length-2;break}}for(l=-1;++l<i.length;)i[l][1].type==="strikethroughSequenceTemporary"&&(i[l][1].type="data");return i}function s(i,o,l){const u=this.previous,d=this.events;let c=0;return f;function f(g){return u===126&&d[d.length-1][1].type!=="characterEscape"?l(g):(i.enter("strikethroughSequenceTemporary"),h(g))}function h(g){const w=Qt(u);if(g===126)return c>1?l(g):(i.consume(g),c++,h);if(c<2&&!r)return l(g);const x=i.exit("strikethroughSequenceTemporary"),y=Qt(g);return x._open=!y||y===2&&!!w,x._close=!w||w===2&&!!y,o(g)}}}class Jw{constructor(){this.map=[]}add(t,r,n){Kw(this,t,r,n)}consume(t){if(this.map.sort(function(s,i){return s[0]-i[0]}),this.map.length===0)return;let r=this.map.length;const n=[];for(;r>0;)r-=1,n.push(t.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),t.length=this.map[r][0];n.push(t.slice()),t.length=0;let a=n.pop();for(;a;){for(const s of a)t.push(s);a=n.pop()}this.map.length=0}}function Kw(e,t,r,n){let a=0;if(!(r===0&&n.length===0)){for(;a<e.map.length;){if(e.map[a][0]===t){e.map[a][1]+=r,e.map[a][2].push(...n);return}a+=1}e.map.push([t,r,n])}}function Yw(e,t){let r=!1;const n=[];for(;t<e.length;){const a=e[t];if(r){if(a[0]==="enter")a[1].type==="tableContent"&&n.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(a[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const s=n.length-1;n[s]=n[s]==="left"?"center":"right"}}else if(a[1].type==="tableDelimiterRow")break}else a[0]==="enter"&&a[1].type==="tableDelimiterRow"&&(r=!0);t+=1}return n}function Gw(){return{flow:{null:{name:"table",tokenize:Xw,resolveAll:Qw}}}}function Xw(e,t,r){const n=this;let a=0,s=0,i;return o;function o(S){let D=n.events.length-1;for(;D>-1;){const B=n.events[D][1].type;if(B==="lineEnding"||B==="linePrefix")D--;else break}const N=D>-1?n.events[D][1].type:null,K=N==="tableHead"||N==="tableRow"?C:l;return K===C&&n.parser.lazy[n.now().line]?r(S):K(S)}function l(S){return e.enter("tableHead"),e.enter("tableRow"),u(S)}function u(S){return S===124||(i=!0,s+=1),d(S)}function d(S){return S===null?r(S):W(S)?s>1?(s=0,n.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(S),e.exit("lineEnding"),h):r(S):te(S)?se(e,d,"whitespace")(S):(s+=1,i&&(i=!1,a+=1),S===124?(e.enter("tableCellDivider"),e.consume(S),e.exit("tableCellDivider"),i=!0,d):(e.enter("data"),c(S)))}function c(S){return S===null||S===124||de(S)?(e.exit("data"),d(S)):(e.consume(S),S===92?f:c)}function f(S){return S===92||S===124?(e.consume(S),c):c(S)}function h(S){return n.interrupt=!1,n.parser.lazy[n.now().line]?r(S):(e.enter("tableDelimiterRow"),i=!1,te(S)?se(e,g,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(S):g(S))}function g(S){return S===45||S===58?x(S):S===124?(i=!0,e.enter("tableCellDivider"),e.consume(S),e.exit("tableCellDivider"),w):z(S)}function w(S){return te(S)?se(e,x,"whitespace")(S):x(S)}function x(S){return S===58?(s+=1,i=!0,e.enter("tableDelimiterMarker"),e.consume(S),e.exit("tableDelimiterMarker"),y):S===45?(s+=1,y(S)):S===null||W(S)?O(S):z(S)}function y(S){return S===45?(e.enter("tableDelimiterFiller"),E(S)):z(S)}function E(S){return S===45?(e.consume(S),E):S===58?(i=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(S),e.exit("tableDelimiterMarker"),_):(e.exit("tableDelimiterFiller"),_(S))}function _(S){return te(S)?se(e,O,"whitespace")(S):O(S)}function O(S){return S===124?g(S):S===null||W(S)?!i||a!==s?z(S):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(S)):z(S)}function z(S){return r(S)}function C(S){return e.enter("tableRow"),U(S)}function U(S){return S===124?(e.enter("tableCellDivider"),e.consume(S),e.exit("tableCellDivider"),U):S===null||W(S)?(e.exit("tableRow"),t(S)):te(S)?se(e,U,"whitespace")(S):(e.enter("data"),V(S))}function V(S){return S===null||S===124||de(S)?(e.exit("data"),U(S)):(e.consume(S),S===92?R:V)}function R(S){return S===92||S===124?(e.consume(S),V):V(S)}}function Qw(e,t){let r=-1,n=!0,a=0,s=[0,0,0,0],i=[0,0,0,0],o=!1,l=0,u,d,c;const f=new Jw;for(;++r<e.length;){const h=e[r],g=h[1];h[0]==="enter"?g.type==="tableHead"?(o=!1,l!==0&&(Mu(f,t,l,u,d),d=void 0,l=0),u={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(r,0,[["enter",u,t]])):g.type==="tableRow"||g.type==="tableDelimiterRow"?(n=!0,c=void 0,s=[0,0,0,0],i=[0,r+1,0,0],o&&(o=!1,d={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(r,0,[["enter",d,t]])),a=g.type==="tableDelimiterRow"?2:d?3:1):a&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(n=!1,i[2]===0&&(s[1]!==0&&(i[0]=i[1],c=Sn(f,t,s,a,void 0,c),s=[0,0,0,0]),i[2]=r)):g.type==="tableCellDivider"&&(n?n=!1:(s[1]!==0&&(i[0]=i[1],c=Sn(f,t,s,a,void 0,c)),s=i,i=[s[1],r,0,0])):g.type==="tableHead"?(o=!0,l=r):g.type==="tableRow"||g.type==="tableDelimiterRow"?(l=r,s[1]!==0?(i[0]=i[1],c=Sn(f,t,s,a,r,c)):i[1]!==0&&(c=Sn(f,t,i,a,r,c)),a=0):a&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(i[3]=r)}for(l!==0&&Mu(f,t,l,u,d),f.consume(t.events),r=-1;++r<t.events.length;){const h=t.events[r];h[0]==="enter"&&h[1].type==="table"&&(h[1]._align=Yw(t.events,r))}return e}function Sn(e,t,r,n,a,s){const i=n===1?"tableHeader":n===2?"tableDelimiter":"tableData",o="tableContent";r[0]!==0&&(s.end=Object.assign({},er(t.events,r[0])),e.add(r[0],0,[["exit",s,t]]));const l=er(t.events,r[1]);if(s={type:i,start:Object.assign({},l),end:Object.assign({},l)},e.add(r[1],0,[["enter",s,t]]),r[2]!==0){const u=er(t.events,r[2]),d=er(t.events,r[3]),c={type:o,start:Object.assign({},u),end:Object.assign({},d)};if(e.add(r[2],0,[["enter",c,t]]),n!==2){const f=t.events[r[2]],h=t.events[r[3]];if(f[1].end=Object.assign({},h[1].end),f[1].type="chunkText",f[1].contentType="text",r[3]>r[2]+1){const g=r[2]+1,w=r[3]-r[2]-1;e.add(g,w,[])}}e.add(r[3]+1,0,[["exit",c,t]])}return a!==void 0&&(s.end=Object.assign({},er(t.events,a)),e.add(a,0,[["exit",s,t]]),s=void 0),s}function Mu(e,t,r,n,a){const s=[],i=er(t.events,r);a&&(a.end=Object.assign({},i),s.push(["exit",a,t])),n.end=Object.assign({},i),s.push(["exit",n,t]),e.add(r+1,0,s)}function er(e,t){const r=e[t],n=r[0]==="enter"?"start":"end";return r[1][n]}const Zw={name:"tasklistCheck",tokenize:tv};function ev(){return{text:{91:Zw}}}function tv(e,t,r){const n=this;return a;function a(l){return n.previous!==null||!n._gfmTasklistFirstContentOfListItem?r(l):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),s)}function s(l){return de(l)?(e.enter("taskListCheckValueUnchecked"),e.consume(l),e.exit("taskListCheckValueUnchecked"),i):l===88||l===120?(e.enter("taskListCheckValueChecked"),e.consume(l),e.exit("taskListCheckValueChecked"),i):r(l)}function i(l){return l===93?(e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),o):r(l)}function o(l){return W(l)?t(l):te(l)?e.check({tokenize:rv},t,r)(l):r(l)}}function rv(e,t,r){return se(e,n,"whitespace");function n(a){return a===null?r(a):t(a)}}function nv(e){return il([Ew(),Bw(),Ww(e),Gw(),ev()])}const av={};function sv(e){const t=this,r=e||av,n=t.data(),a=n.micromarkExtensions||(n.micromarkExtensions=[]),s=n.fromMarkdownExtensions||(n.fromMarkdownExtensions=[]),i=n.toMarkdownExtensions||(n.toMarkdownExtensions=[]);a.push(nv(r)),s.push(_w()),i.push(Tw(r))}function Ce(...e){return e.filter(Boolean).join(" ")}const iv=({content:e})=>p.jsx(Gb,{remarkPlugins:[sv],className:"cuadra-aui-md",components:uv,children:e}),ps=b.memo(iv),ov=({language:e,code:t})=>{const{isCopied:r,copyToClipboard:n}=lv(),a=()=>{!t||r||n(t)};return p.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:[p.jsx("span",{className:"cuadra-lowercase [&>span]:cuadra-text-xs cuadra-font-brand",children:e}),p.jsxs("button",{onClick:a,className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-muted cuadra-transition-colors","aria-label":"Copy code",children:[!r&&p.jsx(Ku,{className:"cuadra-h-4 cuadra-w-4"}),r&&p.jsx(Nn,{className:"cuadra-h-4 cuadra-w-4"})]})]})},lv=({copiedDuration:e=3e3}={})=>{const[t,r]=b.useState(!1);return{isCopied:t,copyToClipboard:a=>{a&&navigator.clipboard.writeText(a).then(()=>{r(!0),setTimeout(()=>r(!1),e)})}}},uv=Db({h1:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h1",m({className:Ce("cuadra-mb-6 cuadra-scroll-m-20 cuadra-text-2xl cuadra-font-normal cuadra-tracking-tight last:cuadra-mb-0 font-brand",e)},t))},h2:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h2",m({className:Ce("cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h3:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h3",m({className:Ce("cuadra-mb-3 cuadra-mt-5 cuadra-scroll-m-20 cuadra-text-lg cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h4:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h4",m({className:Ce("cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h5:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h5",m({className:Ce("cuadra-my-4 cuadra-text-lg cuadra-font-normal first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h6:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("h6",m({className:Ce("cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand",e)},t))},p:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("p",m({className:Ce("cuadra-mb-5 cuadra-mt-5 cuadra-leading-7 first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},a:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("a",m({className:Ce("cuadra-text-primary cuadra-font-medium cuadra-underline cuadra-underline-offset-4 font-brand",e)},t))},blockquote:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("blockquote",m({className:Ce("cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand",e)},t))},ul:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("ul",m({className:Ce("cuadra-my-5 cuadra-ml-6 cuadra-list-disc [&>li]:cuadra-mt-2 font-brand",e)},t))},ol:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("ol",m({className:Ce("cuadra-my-5 cuadra-ml-6 cuadra-list-decimal [&>li]:cuadra-mt-2 font-brand",e)},t))},hr:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("hr",m({className:Ce("cuadra-my-5 cuadra-border-b",e)},t))},table:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("table",m({className:Ce("cuadra-my-5 cuadra-w-full cuadra-border-separate cuadra-border-spacing-0 cuadra-overflow-y-auto font-brand",e)},t))},th:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("th",m({className:Ce("cuadra-bg-muted cuadra-px-4 cuadra-py-2 cuadra-text-left cuadra-font-normal first:cuadra-rounded-tl-lg last:cuadra-rounded-tr-lg [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand",e)},t))},td:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("td",m({className:Ce("cuadra-border-b cuadra-border-l cuadra-px-4 cuadra-py-2 cuadra-text-left last:cuadra-border-r [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand",e)},t))},tr:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("tr",m({className:Ce("cuadra-m-0 cuadra-border-b cuadra-p-0 first:cuadra-border-t [&:last-child>td:first-child]:cuadra-rounded-bl-lg [&:last-child>td:last-child]:cuadra-rounded-br-lg",e)},t))},sup:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("sup",m({className:Ce("[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand",e)},t))},pre:r=>{var n=r,{className:e}=n,t=H(n,["className"]);return p.jsx("pre",m({className:Ce("cuadra-overflow-x-auto cuadra-whitespace-pre-wrap cuadra-break-words cuadra-rounded-b-lg !cuadra-rounded-t-none cuadra-bg-muted cuadra-p-4 cuadra-text-foreground font-brand",e)},t))},code:function(n){var a=n,{className:t}=a,r=H(a,["className"]);const s=Gl();return p.jsx("code",m({className:Ce(!s&&"cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand",t)},r))},CodeHeader:ov});function Pu(n){var a=n,{className:e="",variant:t="default"}=a,r=H(a,["className","variant"]);const s="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 p.jsx("div",m({className:`${s} ${i[t]||i.default} ${e}`},r))}function cv(e){const t=new Map;for(const r of e){const n=t.get(r.filename);(!n||r.score>n.score)&&t.set(r.filename,r)}return Array.from(t.values()).sort((r,n)=>n.score-r.score)}function dv({sources:e,maxVisible:t=3}){if(!e||e.length===0)return null;const r=cv(e),n=r.slice(0,t),a=r.length-t;return p.jsxs("div",{className:"cuadra-mt-4 cuadra-pt-3 cuadra-border-t cuadra-border-border",children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1.5 cuadra-mb-2.5",children:[p.jsx(ws,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground"}),p.jsx("span",{className:"cuadra-text-xs cuadra-font-medium cuadra-text-muted-foreground font-brand",children:"Sources"})]}),p.jsxs("div",{className:"cuadra-flex cuadra-flex-wrap cuadra-gap-2",children:[n.map((s,i)=>p.jsx(fv,{source:s},s.sourceId||i)),a>0&&p.jsxs(Pu,{variant:"subtle",children:["+",a," more"]})]})]})}function hv(e){var r;switch((r=e.split(".").pop())==null?void 0:r.toLowerCase()){case"csv":case"xlsx":case"xls":return Gu;case"md":case"txt":return Xu;default:return ws}}function fv({source:e}){const{filename:t,score:r}=e,n=hv(t);return p.jsxs(Pu,{className:"cuadra-gap-2 cuadra-cursor-default",title:r<1?`${Math.round(r*100)}% relevant`:void 0,children:[p.jsx(n,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-shrink-0 cuadra-opacity-60"}),p.jsx("span",{className:"cuadra-truncate cuadra-max-w-[180px]",children:t}),r<1&&r>0&&p.jsxs("span",{className:"cuadra-opacity-50 cuadra-text-[10px] cuadra-tabular-nums",children:[Math.round(r*100),"%"]})]})}const pv=b.forwardRef(function({welcomeTitle:t="What shall we explore today?",welcomeSubtitle:r,extraTopPadding:n,suggestions:a,inputPlaceholder:s="Reply...",enableAttachments:i=!1,preMadeResponseDelay:o=1e3,streamingSpeed:l=50,safeArea:u=!1,composerBorder:d=!1,models:c,selectedModelId:f,onModelChange:h,showChatHeader:g=!1},w){const x=Si(),y=pe(),[E,_]=b.useState(!1),[O,z]=b.useState(null),[C,U]=b.useState(!1),V=b.useSyncExternalStore(Jt.subscribe,Jt.getSnapshot);b.useEffect(()=>{if(V){const P=setTimeout(()=>Jt.clear(),4e3);return()=>clearTimeout(P)}},[V]);const R=_i(P=>{const q=P.messages;return!q||q.length===0}),S=R&&!E,D=b.useCallback((P,q,J)=>{var ue,ie;if(!C)try{const v=(ue=J==null?void 0:J.streamingSpeed)!=null?ue:l,Y=(ie=J==null?void 0:J.delay)!=null?ie:o;Ao(P,q,v,Y),y.composer().setText(P),setTimeout(()=>{y.composer().send()},10)}catch(v){}},[C,l,o,y]),N=b.useCallback(P=>{try{y.composer().setText(P),setTimeout(()=>{y.composer().send()},10)}catch(q){}},[y]),K=b.useCallback(P=>M(null,null,function*(){var q;if(!(C||!x))try{if(P.response){const J=(q=P.responseDelay)!=null?q:o;yield D(P.prompt,P.response,{delay:J,streamingSpeed:l})}else N(P.prompt)}catch(J){}}),[x,C,o,l,D,N]),B=b.useCallback(()=>M(null,null,function*(){try{const P=window.__cuadraThreadListRuntime,q=P==null?void 0:P.threadList;q!=null&&q.switchToNewThread&&(yield q.switchToNewThread())}catch(P){}}),[]);return b.useImperativeHandle(w,()=>({sendMessage:N,sendPreMadeQA:D,clearChat:B}),[N,D,B]),b.useEffect(()=>{var P,q;if(!x){_(!1);return}try{const J=x==null?void 0:x.store;if(!J){_(!1);return}const ue=(P=J.subscribe)==null?void 0:P.call(J,v=>{const Y=v==null?void 0:v.threadId,we=(v==null?void 0:v.messages)||[],k=(v==null?void 0:v.isLoadingHistory)||!1,Se=we.length;Y&&Y!==O&&z(Y),_(k&&Se===0)}),ie=(q=J.getState)==null?void 0:q.call(J);if(ie){const v=ie==null?void 0:ie.threadId,Y=(ie==null?void 0:ie.messages)||[],we=(ie==null?void 0:ie.isLoadingHistory)||!1,k=Y.length;v&&v!==O&&z(v),_(we&&k===0)}return()=>{ue&&ue()}}catch(J){_(!1)}},[x,O]),p.jsxs(yo,{className:"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full cuadra-relative",children:[g&&p.jsx(vv,{}),p.jsxs(go,{disabled:!i,className:`cuadra-flex-1 cuadra-flex cuadra-flex-col cuadra-min-h-0 cuadra-relative ${S?"cuadra-justify-center":""}`,children:[p.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:p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-3",children:[p.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:p.jsx(Zu,{className:"cuadra-h-6 cuadra-w-6"})}),p.jsx("p",{className:"cuadra-text-sm cuadra-font-medium cuadra-text-foreground font-brand",children:"Drop files here"})]})}),p.jsx(wo,{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":n||(g?"0.5rem":"2rem")},children:E?p.jsx("div",{className:"cuadra-absolute cuadra-inset-0 cuadra-flex cuadra-items-center cuadra-justify-center",children:p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-3",children:[p.jsx(vs,{className:"cuadra-h-5 cuadra-w-5 cuadra-animate-spin cuadra-text-muted-foreground"}),p.jsx("p",{className:"cuadra-text-sm cuadra-text-muted-foreground font-brand",children:"Loading messages..."})]})}):p.jsxs("div",{className:"cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full cuadra-px-4",children:[p.jsx(bo,{children:p.jsx(mv,{title:t,subtitle:r})}),p.jsx(lp,{components:{UserMessage:gv,AssistantMessage:xv}})]})}),p.jsx("div",{className:`cuadra-w-full cuadra-px-4 cuadra-pt-2 ${S?"cuadra-pb-2":"cuadra-pb-4"}`,style:u?{paddingBottom:"calc(env(safe-area-inset-bottom) + 1rem)"}:void 0,children:p.jsxs("div",{className:"cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full",children:[V&&p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-mb-2 cuadra-px-3 cuadra-py-2 cuadra-rounded-lg cuadra-text-xs font-brand cuadra-animate-in cuadra-fade-in cuadra-slide-in-from-bottom-2",style:{backgroundColor:"var(--cuadra-muted)",color:"var(--cuadra-foreground)",opacity:.85},children:[p.jsx(Ju,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-flex-shrink-0 cuadra-text-muted-foreground"}),p.jsx("span",{className:"cuadra-flex-1 cuadra-text-muted-foreground",children:V.message}),p.jsx("button",{type:"button",onClick:()=>Jt.clear(),className:"cuadra-flex-shrink-0 cuadra-p-0.5 cuadra-rounded hover:cuadra-bg-black/5 cuadra-transition-colors","aria-label":"Dismiss",children:p.jsx(zr,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})]}),i&&p.jsx(mo,{components:{Attachment:()=>{const P=ee(({attachment:q})=>q);return P?p.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:[p.jsx(ks,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground",strokeWidth:1.5}),p.jsx("span",{className:"cuadra-text-xs cuadra-text-foreground font-brand",children:P.name||"Attachment"}),p.jsx(yf,{asChild:!0,children:p.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:p.jsx(zr,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})})]}):null}}}),p.jsxs(so,{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:d?"1px solid hsl(var(--cuadra-border))":"none"},children:[p.jsx(fo,{asChild:!0,children:p.jsx("textarea",{rows:1,placeholder:s,className:"cuadra-flex cuadra-min-h-[44px] cuadra-w-full cuadra-rounded-t-2xl cuadra-border-0 cuadra-bg-transparent cuadra-px-4 cuadra-pt-3.5 cuadra-pb-1 cuadra-text-base cuadra-text-foreground placeholder:cuadra-text-muted-foreground focus-visible:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-resize-none font-brand",style:{fontSize:"1rem",lineHeight:"1.5"}})}),p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-px-3 cuadra-pb-2.5 cuadra-pt-1",children:[p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1",children:i&&p.jsx(Zf,{multiple:!0,asChild:!0,children:p.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:[p.jsx(On,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground",strokeWidth:1.5}),p.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"})]})})}),p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[c&&c.length>0&&p.jsx(wv,{models:c,selectedModelId:f,onModelChange:h,threadIsEmpty:R,onNewChat:B}),p.jsx(Df,{asChild:!0,children:p.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:p.jsx(Wu,{className:"cuadra-h-4 cuadra-w-4",strokeWidth:2})})})]})]})]})]})}),S&&a&&a.length>0&&p.jsx("div",{className:"cuadra-flex cuadra-flex-wrap cuadra-justify-center cuadra-gap-2 cuadra-px-4 cuadra-pb-6 cuadra-pt-1 cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full",children:a.map((P,q)=>p.jsx("button",{type:"button",onClick:()=>K(P),disabled:C,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:P.prompt},`suggestion-${q}`))})]})]})});function mv({title:e,subtitle:t}){return p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-text-center cuadra-py-6",children:[p.jsx("h2",{className:"cuadra-text-4xl cuadra-font-normal cuadra-text-foreground/80 cuadra-tracking-tight",style:{fontFamily:"var(--cuadra-font-logo), Outfit, -apple-system, sans-serif"},children:e}),t&&p.jsx("p",{className:"cuadra-text-base cuadra-text-muted-foreground cuadra-mt-3 cuadra-max-w-lg cuadra-whitespace-pre-line",children:t})]})}function gv(){return p.jsx(ua,{className:"cuadra-flex cuadra-w-full cuadra-justify-end cuadra-py-2.5",children:p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-end cuadra-gap-2 cuadra-max-w-[80%]",children:[p.jsx(no,{components:{Attachment:()=>{var s;const e=ee(({attachment:i})=>i);if(!e)return null;const t=e.type==="image",r=e.file,n=(s=e.content)==null?void 0:s.find(i=>i.type==="image"),a=r?URL.createObjectURL(r):n==null?void 0:n.image;return p.jsx("div",{className:"cuadra-mb-1",children:t&&a?p.jsx("img",{src:a,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)"}}):p.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:[p.jsx(ks,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground"}),p.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground font-brand",children:e.name||"Attachment"})]})})}}}),p.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:p.jsx(ca,{components:{Text:({text:e})=>p.jsx(ps,{content:e||""})}})})]})})}function yv({text:e}){const[t,r]=b.useState(!1),n=ee(({message:a})=>{var s;return((s=a==null?void 0:a.status)==null?void 0:s.type)==="running"});return e?n?p.jsx("div",{className:"cuadra-mb-3 cuadra-py-1",children:p.jsx("div",{className:"cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand cuadra-animate-text-shimmer",children:e})}):p.jsxs("div",{className:"cuadra-mb-3",children:[p.jsxs("button",{type:"button",onClick:()=>r(!t),className:"cuadra-flex cuadra-items-center cuadra-gap-1.5 cuadra-py-1 cuadra-text-sm cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-colors font-brand",children:[p.jsx(Ln,{className:`cuadra-h-3.5 cuadra-w-3.5 cuadra-shrink-0 cuadra-transition-transform cuadra-duration-200 ${t?"":"cuadra--rotate-90"}`}),p.jsx("span",{children:"Reasoning"})]}),p.jsx("div",{className:`cuadra-overflow-hidden cuadra-transition-all cuadra-duration-200 cuadra-ease-out ${t?"cuadra-max-h-[2000px] cuadra-opacity-100":"cuadra-max-h-0 cuadra-opacity-0"}`,children:p.jsx("div",{className:"cuadra-pl-5 cuadra-pt-2 cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand",children:p.jsx(ps,{content:e})})})]}):null}function bv(){return p.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:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1",children:[p.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}}),p.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}}),p.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}})]}),p.jsx("span",{children:"Thinking..."})]})}function xv(){const e=ee(({message:i})=>{var o;return((o=i==null?void 0:i.status)==null?void 0:o.type)==="running"}),t=ee(({message:i})=>{const o=i==null?void 0:i.content;return!o||!Array.isArray(o)?!1:o.some(l=>!!(l.type==="text"&&l.text&&l.text.length>0||l.type==="reasoning"&&l.text&&l.text.length>0))}),r=b.useRef(!1),[n,a]=b.useState(null);b.useEffect(()=>{if(e&&t&&!r.current){const i=wt.getCurrentMessageId();i&&(r.current=!0,a(i))}},[e,t]);const s=b.useSyncExternalStore(i=>wt.subscribe(i),()=>{var i,o;if(n){const l=wt.getForMessage(n);return(i=l.sources)!=null&&i.length?l.sources:null}if(e&&t){const l=wt.getCurrentMessageId();if(l){const u=wt.getForMessage(l);return(o=u.sources)!=null&&o.length?u.sources:null}}return null},()=>null);return p.jsx(ua,{className:"cuadra-flex cuadra-w-full cuadra-justify-start cuadra-py-2.5",children:p.jsxs("div",{className:"cuadra-text-foreground cuadra-max-w-full cuadra-break-words font-brand",style:{fontSize:"0.9375rem",lineHeight:"1.75"},children:[p.jsx(ca,{components:{Text:({text:i})=>p.jsx(ps,{content:i||""}),Reasoning:({text:i})=>p.jsx(yv,{text:i||""})}}),e&&!t&&p.jsx(bv,{}),s&&s.length>0&&p.jsx(dv,{sources:s})]})})}function tr({label:e,children:t}){return p.jsxs("span",{className:"cuadra-relative cuadra-inline-flex cuadra-group/tip",children:[t,p.jsx("span",{className:"cuadra-absolute cuadra-bottom-full cuadra-left-1/2 cuadra-mb-1.5 cuadra-hidden group-hover/tip:cuadra-flex cuadra-items-center cuadra-whitespace-nowrap cuadra-rounded-md cuadra-px-2 cuadra-py-1 cuadra-text-[10px] cuadra-pointer-events-none cuadra-z-50 font-brand",style:{backgroundColor:"var(--cuadra-popover)",color:"var(--cuadra-foreground)",boxShadow:"0 2px 8px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)",transform:"translateX(-50%)"},children:e})]})}function wv({models:e,selectedModelId:t,onModelChange:r,threadIsEmpty:n,onNewChat:a}){const[s,i]=b.useState(!1),o=e.find(u=>u.id===t)||e[0];if(!o)return null;const l=u=>M(null,null,function*(){i(!1),!n&&u!==t&&(yield a==null?void 0:a()),r==null||r(u)});return p.jsxs("div",{className:"cuadra-relative",children:[p.jsxs("button",{type:"button",onClick:()=>i(!s),className:"cuadra-flex cuadra-items-center cuadra-gap-1 cuadra-px-2.5 cuadra-py-1.5 cuadra-rounded-lg cuadra-text-xs cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-colors font-brand",children:[p.jsx("span",{children:o.name}),o.supportsReasoning&&p.jsx(tr,{label:"Reasoning",children:p.jsx(Pn,{className:"cuadra-h-3 cuadra-w-3"})}),o.supportsVision&&p.jsx(tr,{label:"Vision",children:p.jsx(Dn,{className:"cuadra-h-3 cuadra-w-3"})}),p.jsx(Ln,{className:"cuadra-h-3 cuadra-w-3"})]}),s&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-hidden md:cuadra-block cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:()=>i(!1)}),p.jsxs("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-50 cuadra-flex cuadra-flex-col md:cuadra-hidden",style:{backgroundColor:"var(--cuadra-popover)"},children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-px-4 cuadra-py-3 cuadra-min-h-[48px]",style:{borderBottom:"1px solid rgba(0,0,0,0.06)"},children:[p.jsx("span",{className:"cuadra-text-sm cuadra-font-semibold cuadra-text-foreground font-brand",children:"Select Model"}),p.jsx("button",{type:"button",onClick:()=>i(!1),className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-p-1.5 cuadra-rounded-lg cuadra-text-muted-foreground hover:cuadra-bg-muted/60 cuadra-transition-colors",children:p.jsx(zr,{className:"cuadra-h-5 cuadra-w-5"})})]}),p.jsx("div",{className:"cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto cuadra-py-1",children:e.map(u=>p.jsxs("button",{type:"button",className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-justify-between cuadra-gap-3 cuadra-px-4 cuadra-py-3 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted/60 cuadra-transition-colors cuadra-border-b cuadra-border-border/40 last:cuadra-border-b-0 font-brand",onClick:()=>l(u.id),children:[p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-min-w-0",children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1.5",children:[p.jsx("span",{className:"cuadra-text-foreground cuadra-truncate",children:u.name}),u.supportsReasoning&&p.jsx(tr,{label:"Reasoning",children:p.jsx(Pn,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})}),u.supportsVision&&p.jsx(tr,{label:"Vision",children:p.jsx(Dn,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})})]}),u.description&&p.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground",children:u.description})]}),u.id===t&&p.jsx(Nn,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-primary cuadra-flex-shrink-0"})]},u.id))})]}),p.jsx("div",{className:"cuadra-hidden md:cuadra-block cuadra-absolute cuadra-bottom-full cuadra-right-0 cuadra-mb-2 cuadra-z-50 cuadra-rounded-xl cuadra-min-w-[200px] cuadra-py-1",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 4px 24px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)"},children:e.map(u=>p.jsxs("button",{type:"button",className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-justify-between cuadra-gap-3 cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted/60 cuadra-transition-colors font-brand",onClick:()=>l(u.id),children:[p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-min-w-0",children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1.5",children:[p.jsx("span",{className:"cuadra-text-foreground cuadra-truncate",children:u.name}),u.supportsReasoning&&p.jsx(tr,{label:"Reasoning",children:p.jsx(Pn,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})}),u.supportsVision&&p.jsx(tr,{label:"Vision",children:p.jsx(Dn,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground cuadra-flex-shrink-0"})})]}),u.description&&p.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground",children:u.description})]}),u.id===t&&p.jsx(Nn,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-primary cuadra-flex-shrink-0"})]},u.id))})]})]})}function vv(){const e=ee(({threadListItem:a})=>{var s;return(s=a==null?void 0:a.title)!=null?s:null}),[t,r]=b.useState(!1),n=e||"Untitled chat";return p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-px-3 cuadra-py-2 cuadra-min-h-[48px] cuadra-justify-end md:cuadra-justify-start",children:p.jsxs("div",{className:"cuadra-relative",children:[p.jsxs("button",{type:"button",onClick:()=>r(!t),className:"cuadra-hidden md:cuadra-flex cuadra-items-center cuadra-gap-1 cuadra-text-sm cuadra-text-foreground hover:cuadra-bg-muted/60 cuadra-rounded-lg cuadra-px-2 cuadra-py-1.5 cuadra-transition-colors font-brand",children:[p.jsx("span",{className:"cuadra-font-medium cuadra-truncate cuadra-max-w-[200px]",children:n}),p.jsx(Ln,{className:`cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground cuadra-flex-shrink-0 cuadra-transition-transform cuadra-duration-200 ${t?"cuadra-rotate-180":""}`})]}),p.jsx("button",{type:"button",onClick:()=>r(!t),className:"cuadra-flex md:cuadra-hidden cuadra-items-center cuadra-justify-center cuadra-text-foreground hover:cuadra-bg-muted/60 cuadra-rounded-lg cuadra-p-2 cuadra-transition-colors",children:p.jsx(Qu,{className:"cuadra-h-5 cuadra-w-5"})}),t&&p.jsx(kv,{onClose:()=>r(!1)})]})})}function kv({onClose:e}){return p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-hidden md:cuadra-block cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:e}),p.jsxs("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-50 cuadra-flex cuadra-flex-col md:cuadra-hidden",style:{backgroundColor:"var(--cuadra-popover)"},children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-px-4 cuadra-py-3 cuadra-min-h-[48px]",style:{borderBottom:"1px solid rgba(0,0,0,0.06)"},children:[p.jsx("span",{className:"cuadra-text-sm cuadra-font-semibold cuadra-text-foreground font-brand",children:"Chats"}),p.jsx("button",{type:"button",onClick:e,className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-p-1.5 cuadra-rounded-lg cuadra-text-muted-foreground hover:cuadra-bg-muted/60 cuadra-transition-colors",children:p.jsx(zr,{className:"cuadra-h-5 cuadra-w-5"})})]}),p.jsxs(pa,{className:"cuadra-flex cuadra-flex-col cuadra-flex-1 cuadra-min-h-0",children:[p.jsx("div",{className:"cuadra-px-3 cuadra-py-2",children:p.jsxs(fa,{className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-gap-2.5 cuadra-px-3 cuadra-py-2.5 cuadra-rounded-lg cuadra-text-sm cuadra-text-foreground hover:cuadra-bg-muted cuadra-transition-colors cuadra-cursor-pointer font-brand",onClick:e,children:[p.jsx(On,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"New Chat"]})}),p.jsx(Nu,{onSelect:e,fullHeight:!0})]})]}),p.jsx("div",{className:"cuadra-hidden md:cuadra-flex cuadra-absolute cuadra-left-0 cuadra-top-full cuadra-mt-1 cuadra-z-50 cuadra-w-[300px] cuadra-rounded-xl cuadra-overflow-hidden cuadra-flex-col",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 4px 24px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)"},children:p.jsxs(pa,{className:"cuadra-flex cuadra-flex-col",children:[p.jsx("div",{className:"cuadra-px-2 cuadra-py-1.5",children:p.jsxs(fa,{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:[p.jsx(On,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"New Chat"]})}),p.jsx(Nu,{onSelect:e})]})})]})}function Nu({onSelect:e,fullHeight:t}){const r=ee(({threads:s})=>{var i;return(i=s==null?void 0:s.threadIds)!=null?i:[]}),n=ee(({threads:s})=>s==null?void 0:s.newThreadId);return r.some(s=>s!==n)?p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-mx-3 cuadra-my-0.5",style:{borderTop:"1px solid rgba(0,0,0,0.06)"}}),p.jsx("div",{className:`cuadra-overflow-y-auto scrollbar-thin ${t?"cuadra-flex-1 cuadra-min-h-0 cuadra-px-3 cuadra-pb-3 cuadra-flex cuadra-flex-col cuadra-gap-2":"cuadra-px-2 cuadra-pb-1.5"}`,style:t?void 0:{maxHeight:"340px"},children:p.jsx(To,{components:{ThreadListItem:s=>p.jsx(Sv,I(m({},s),{onSelect:e,fullHeight:t}))}})})]}):null}function Sv({onSelect:e,fullHeight:t}){const r=Ci(),n=Ti(),a=th(),s=_i(y=>y.threadId),i=(r==null?void 0:r.id)===s,[o,l]=b.useState(!1),[u,d]=b.useState(!1),[c,f]=b.useState((r==null?void 0:r.title)||""),[h,g]=b.useState(!1),w=()=>M(null,null,function*(){if(!(r!=null&&r.remoteId)||!c||c===r.title){d(!1);return}try{g(!0),yield n.rename(c)}catch(y){}finally{g(!1),d(!1)}}),x=y=>M(null,null,function*(){y.stopPropagation();try{yield n.delete(),i&&(yield a.switchToNewThread())}catch(E){console.error("[CuadraChat] Failed to delete thread:",E)}});return b.useEffect(()=>{r!=null&&r.title&&!u&&f(r.title)},[r==null?void 0:r.title,u]),r?t?p.jsxs(ma,{className:`cuadra-relative cuadra-flex cuadra-items-center cuadra-rounded-xl cuadra-transition-colors cuadra-cursor-pointer ${i?"cuadra-bg-primary/10 cuadra-ring-1 cuadra-ring-primary/20":"cuadra-bg-muted/40"}`,children:[u?p.jsx("div",{className:"cuadra-flex-1 cuadra-px-4 cuadra-py-3.5 cuadra-min-w-0",onClick:y=>y.stopPropagation(),onMouseDown:y=>y.stopPropagation(),onKeyDown:y=>y.stopPropagation(),onKeyUp:y=>y.stopPropagation(),onKeyPress:y=>y.stopPropagation(),children:p.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:c,onChange:y=>f(y.target.value),onKeyDown:y=>{y.stopPropagation(),y.key==="Enter"&&w(),y.key==="Escape"&&(d(!1),f(r.title||""))},onBlur:()=>void w(),disabled:h,autoFocus:!0})}):p.jsx(Co,{className:"cuadra-flex-1 cuadra-px-4 cuadra-py-3.5 cuadra-min-w-0 cuadra-cursor-pointer",onClick:()=>e==null?void 0:e(),children:p.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground cuadra-truncate cuadra-block cuadra-text-left font-brand",children:r.title||"Chat"})}),!u&&p.jsx(_v,{onRename:()=>{d(!0),f(r.title||"Chat")},onDelete:x})]}):p.jsxs(ma,{className:`cuadra-relative cuadra-flex cuadra-items-center cuadra-rounded-lg cuadra-transition-colors cuadra-cursor-pointer cuadra-border-b cuadra-border-border/40 last:cuadra-border-b-0 ${i?"cuadra-bg-muted":"hover:cuadra-bg-muted/60"}`,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[u?p.jsx("div",{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0",onClick:y=>y.stopPropagation(),onMouseDown:y=>y.stopPropagation(),onKeyDown:y=>y.stopPropagation(),onKeyUp:y=>y.stopPropagation(),onKeyPress:y=>y.stopPropagation(),children:p.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:c,onChange:y=>f(y.target.value),onKeyDown:y=>{y.stopPropagation(),y.key==="Enter"&&w(),y.key==="Escape"&&(d(!1),f(r.title||""))},onBlur:()=>void w(),disabled:h,autoFocus:!0})}):p.jsx(Co,{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0 cuadra-cursor-pointer",onClick:()=>e==null?void 0:e(),children:p.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground cuadra-truncate cuadra-block cuadra-text-left font-brand",children:r.title||"Chat"})}),(o||i)&&!u&&p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-0.5 cuadra-mr-1.5 cuadra-flex-shrink-0",children:[p.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-background/60 cuadra-transition-colors",onClick:y=>{y.stopPropagation(),d(!0),f(r.title||"Chat")},title:"Rename",children:p.jsx(Ss,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})}),p.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-destructive/10 cuadra-transition-colors",onClick:x,title:"Delete",children:p.jsx(_s,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-destructive"})})]})]}):null}function _v({onRename:e,onDelete:t}){const[r,n]=b.useState(!1);return p.jsxs("div",{className:"cuadra-relative cuadra-flex-shrink-0 cuadra-mr-2",children:[p.jsx("button",{type:"button",className:"cuadra-p-2 cuadra-rounded-lg cuadra-text-muted-foreground hover:cuadra-bg-background/60 cuadra-transition-colors",onClick:a=>{a.stopPropagation(),n(!r)},children:p.jsx(Yu,{className:"cuadra-h-4 cuadra-w-4"})}),r&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-50",onClick:a=>{a.stopPropagation(),n(!1)}}),p.jsxs("div",{className:"cuadra-absolute cuadra-right-0 cuadra-top-full cuadra-mt-1 cuadra-z-[60] cuadra-w-36 cuadra-rounded-xl cuadra-py-1 cuadra-overflow-hidden",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 4px 24px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)"},children:[p.jsxs("button",{type:"button",className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-gap-2.5 cuadra-px-3 cuadra-py-2.5 cuadra-text-sm cuadra-text-foreground hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:a=>{a.stopPropagation(),n(!1),e()},children:[p.jsx(Ss,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"Rename"]}),p.jsxs("button",{type:"button",className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-gap-2.5 cuadra-px-3 cuadra-py-2.5 cuadra-text-sm cuadra-text-destructive hover:cuadra-bg-destructive/10 cuadra-transition-colors font-brand",onClick:a=>{a.stopPropagation(),n(!1),t(a)},children:[p.jsx(_s,{className:"cuadra-h-4 cuadra-w-4"}),"Delete"]})]})]})]})}const ms=({children:e,className:t="",paddingX:r="px-0",paddingY:n="py-0",borderSizePx:a=2,style:s,contentStyle:i})=>p.jsx("div",{className:`cuadra-relative cuadra-bg-background md:cuadra-rounded-lg cuadra-overflow-hidden cuadra-flex cuadra-flex-col ${r} ${n} ${t}`,style:m(m({border:a>0?`${a}px solid var(--cuadra-primary)`:"none"},s),i),children:e}),Tv=b.createContext(void 0),gs=({children:e,value:t})=>p.jsx(Tv.Provider,{value:t,children:e});function Cv(){b.useEffect(()=>{if(document.querySelector("style[data-cuadra-uikit]"))return;const t=document.createElement("div");t.className="cuadra-flex",document.body.appendChild(t);const r=window.getComputedStyle(t).display==="flex";if(document.body.removeChild(t),r)return;const n=document.createElement("link");n.setAttribute("data-cuadra-uikit","true"),n.rel="stylesheet",n.type="text/css";const a=["/node_modules/@cuadra-ai/uikit/dist/uikit.css",new URL("../dist/uikit.css",typeof document=="undefined"&&typeof location=="undefined"?require("url").pathToFileURL(__filename).href:typeof document=="undefined"?location.href:$e&&$e.tagName.toUpperCase()==="SCRIPT"&&$e.src||new URL("cuadra-uikit.umd.js",document.baseURI).href).href];let s=!1;for(const i of a)if(n.href=i,n.onload=()=>{s=!0},n.onerror=()=>{},document.head.appendChild(n),s)break},[])}const Lu=b.forwardRef(function({config:t},r){Cv();const n=b.useRef(null),a=b.useRef(!1),{baseUrl:s,proxyUrl:i,sessionToken:o,mode:l="multiChat",modelMode:u="fixed",modelId:d,onModelChange:c,ephemeral:f=!1,systemPrompt:h,enableReasoning:g=!1,initialThreadId:w,welcomeTitle:x,welcomeSubtitle:y,extraTopPadding:E,suggestions:_,inputPlaceholder:O,preMadeResponseDelay:z=1e3,streamingSpeed:C=50,initialMessage:U,initialPreMadeQA:V,theme:R="system",onError:S,onChatCreated:D,onUserMessage:N,onThreadIdUpdate:K,enableAttachments:B=!1,supportsVision:P,onBeforeRequest:q,mockResponseOnBlocked:J}=t;b.useImperativeHandle(r,()=>({sendMessage:G=>{var be;(be=n.current)==null||be.sendMessage(G)},sendPreMadeQA:(G,be,me)=>{var Dt;(Dt=n.current)==null||Dt.sendPreMadeQA(G,be,me)},clearChat:()=>{var G;(G=n.current)==null||G.clearChat()}}),[]),b.useEffect(()=>{if(a.current)return;const G=setTimeout(()=>{var be,me;V?(a.current=!0,(be=n.current)==null||be.sendPreMadeQA(V.question,V.answer,{delay:z,streamingSpeed:C})):U&&(a.current=!0,(me=n.current)==null||me.sendMessage(U))},500);return()=>clearTimeout(G)},[U,V,z,C]);const ue=i||s||"",ie=!!i,v=b.useMemo(()=>new Io(ue,o||void 0,ie),[ue,o,ie]),[Y,we]=b.useState(null),[k,Se]=b.useState(!1),[Ye,_e]=b.useState(null),[j,re]=b.useState(!1);b.useEffect(()=>{l==="multiChat"&&re(!0)},[l]);const le=b.useCallback(()=>M(null,null,function*(){if(u==="selector"){Se(!0),_e(null);try{const G=yield v.listModels();we(G)}catch(G){_e(G instanceof Error?G:new Error("Failed to load models"))}finally{Se(!1)}}}),[v,u]);b.useEffect(()=>{u==="selector"&&le()},[u,le]),b.useEffect(()=>(typeof window!="undefined"&&(window.__cuadraUIKitRefetchModels=le),()=>{typeof window!="undefined"&&delete window.__cuadraUIKitRefetchModels}),[le]);const[oe,Ee]=b.useState(u==="fixed"&&d||null),ne=b.useRef(oe),xe=b.useCallback(G=>{const be=ne.current;Ee(G),ne.current=G,c==null||c(G),be!==null&&be!==G&&l==="multiChat"&&setTimeout(()=>{var Dt,Tn;const me=window.__cuadraThreadListRuntime;if((Dt=me==null?void 0:me.threads)!=null&&Dt.switchToNewThread)try{me.threads.switchToNewThread()}catch(Cn){}else if((Tn=me==null?void 0:me.threads)!=null&&Tn.createThread)try{me.threads.createThread()}catch(Cn){}else if(me!=null&&me.switchToNewThread)try{me.switchToNewThread()}catch(Cn){}},100)},[c,l]);b.useEffect(()=>{if(u==="selector"&&(Y!=null&&Y.items)&&Y.items.length>0&&!oe){const G=Y.items[0];if(G!=null&&G.id){const be=G.id;Ee(be),c==null||c(be)}}},[u,Y==null?void 0:Y.items,oe,c]);const ot=u==="fixed"?!!d:!!oe,lt=b.useMemo(()=>{var G;if(P!==void 0)return P;if(u==="selector"&&oe&&(Y!=null&&Y.items)){const be=Y.items.find(me=>me.id===oe);return(G=be==null?void 0:be.supportsVision)!=null?G:!0}return!0},[P,u,oe,Y==null?void 0:Y.items]),ht=b.useMemo(()=>((Y==null?void 0:Y.items)||[]).filter(G=>(G==null?void 0:G.id)&&(G==null?void 0:G.displayName)).map(G=>{var be,me;return{id:G.id,name:G.displayName,supportsVision:(be=G.supportsVision)!=null?be:!1,supportsReasoning:(me=G.supportsReasoning)!=null?me:!1}}),[Y]),St=b.useMemo(()=>({currentModelId:oe||"",models:ht,modelsLoading:k,modelsError:Ye,onModelChange:xe,refetchModels:le}),[oe,ht,k,Ye,xe,le]);return u==="selector"&&k||l==="multiChat"&&j?p.jsx(gs,{value:St,children:p.jsx(ms,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",borderSizePx:t.borderless?0:2,children:p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:p.jsx(vs,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"})})})}):u==="selector"&&!ot&&Ye?p.jsx(gs,{value:St,children:p.jsx(ms,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",children:p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2",children:p.jsx("p",{className:"cuadra-text-sm cuadra-text-destructive font-brand",children:"Failed to load models"})})})})}):p.jsx("div",{className:"cuadra-uikit cuadra-h-full cuadra-w-full",style:{height:"100%",width:"100%"},children:p.jsx(gs,{value:St,children:p.jsx(Sp,{baseUrl:ie?ue:s||ue,sessionToken:o,isProxyMode:ie,mode:l,modelMode:u,modelId:oe||d||void 0,onModelChange:xe,ephemeral:f,systemPrompt:h,enableReasoning:g,initialThreadId:w,enableAttachments:B,supportsVision:lt,onError:S,onChatCreated:D,onUserMessage:N,onThreadIdUpdate:K,onBeforeRequest:q,mockResponseOnBlocked:J,onChatsLoaded:()=>{l==="multiChat"&&re(!1)},children:p.jsx(ms,{paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",className:`cuadra-h-full ${t.containerClass||""}`,borderSizePx:t.borderless?0:2,style:{height:"100%"},children:p.jsx("div",{className:"cuadra-h-full cuadra-flex cuadra-relative",style:{height:"100%"},children:p.jsx("div",{className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:p.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0",children:p.jsx(pv,{ref:n,welcomeTitle:x,welcomeSubtitle:y,extraTopPadding:E,suggestions:_,inputPlaceholder:O,enableAttachments:B,preMadeResponseDelay:z,streamingSpeed:C,safeArea:t.safeArea,showChatHeader:l==="multiChat",models:u==="selector"?ht:void 0,selectedModelId:oe||void 0,onModelChange:u==="selector"?xe:void 0,theme:R})})})})})})})})});class _n{constructor(){T(this,"config",null);T(this,"root",null);T(this,"container",null);T(this,"instances",new Map)}init(t){if(!t.baseUrl&&!t.proxyUrl)throw new Error("Either baseUrl or proxyUrl is required");if(t.modelMode==="fixed"&&t.modelId!==void 0&&(!t.modelId||t.modelId.trim()===""))throw new Error("modelId cannot be empty when explicitly provided. Omit modelId to let backend resolve it.");const r=t.containerId||"cuadra-chat";let n=document.getElementById(r);n||(n=document.createElement("div"),n.id=r,document.body.appendChild(n)),t.containerClass&&n.classList.add(...t.containerClass.split(" ")),this.config=I(m({},t),{containerId:r}),this.container=n,this.root=ge.createRoot(n),this.root.render(b.createElement(Du,{config:this.config})),this.instances.set(r,this)}destroy(t){var a;const r=t||((a=this.config)==null?void 0:a.containerId);if(!r)return;const n=this.instances.get(r);n!=null&&n.root&&(n.root.unmount(),n.root=null),n!=null&&n.container&&n.container.parentNode&&n.container.parentNode.removeChild(n.container),this.instances.delete(r)}updateConfig(t,r){var i;const n=r||((i=this.config)==null?void 0:i.containerId);if(!n)return;const a=this.instances.get(n);if(!(a!=null&&a.config))return;const s=m(m({},a.config),t);a.config=s,a.root&&a.container&&a.root.render(b.createElement(Du,{config:s}))}getInstance(t){var n;const r=t||((n=this.config)==null?void 0:n.containerId);return r&&this.instances.get(r)||null}static parseConfigFromAttributes(t,r){const n={};return t.dataset.baseUrl&&(n.baseUrl=t.dataset.baseUrl),t.dataset.proxyUrl&&(n.proxyUrl=t.dataset.proxyUrl),t.dataset.sessionToken&&(n.sessionToken=t.dataset.sessionToken),t.dataset.containerId&&(n.containerId=t.dataset.containerId),t.dataset.containerClass&&(n.containerClass=t.dataset.containerClass),t.dataset.mode&&(n.mode=t.dataset.mode),t.dataset.modelMode&&(n.modelMode=t.dataset.modelMode),t.dataset.modelId&&(n.modelId=t.dataset.modelId),t.dataset.ephemeral&&(n.ephemeral=t.dataset.ephemeral==="true"),t.dataset.systemPrompt&&(n.systemPrompt=t.dataset.systemPrompt),r&&(r.dataset.baseUrl&&(n.baseUrl=r.dataset.baseUrl),r.dataset.proxyUrl&&(n.proxyUrl=r.dataset.proxyUrl),r.dataset.sessionToken&&(n.sessionToken=r.dataset.sessionToken),r.dataset.mode&&(n.mode=r.dataset.mode),r.dataset.modelMode&&(n.modelMode=r.dataset.modelMode),r.dataset.modelId&&(n.modelId=r.dataset.modelId)),n}}const Du=({config:e})=>p.jsx(Lu,{config:e});let ze=null;typeof window!="undefined"&&(ze=new _n);const Ou={init:e=>(ze||(ze=new _n),ze.init(e)),destroy:e=>ze==null?void 0:ze.destroy(e),updateConfig:(e,t)=>ze==null?void 0:ze.updateConfig(e,t),getInstance:e=>ze==null?void 0:ze.getInstance(e),refetchModels:()=>{if(typeof window!="undefined"){const e=window.__cuadraUIKitRefetchModels;e&&e()}},version:"0.1.0"};if(typeof window!="undefined"){window.CuadraUIKit=Ou;const e=()=>{const t=document.querySelectorAll('script[src*="cuadra-uikit"]'),r=Array.from(t).find(n=>(n.getAttribute("src")||"").includes("cuadra-uikit.umd.js"));r&&r.dataset.autoInit!=="false"&&Iv(r)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):setTimeout(e,0)}function Iv(e){if(!e||!ze)return;const t=_n.parseConfigFromAttributes(e),r=t.containerId||"cuadra-chat",n=document.getElementById(r);if(n){const a=_n.parseConfigFromAttributes(e,n);Object.assign(t,a)}(t.baseUrl||t.proxyUrl)&&ze.init(t)}$.WidgetContent=Lu,$.default=Ou,Object.defineProperties($,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
|
36
36
|
//# sourceMappingURL=cuadra-uikit.umd.js.map
|