@cuadra-ai/uikit 0.1.23 → 0.1.25

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.
Files changed (36) hide show
  1. package/dist/adapters/attachmentAdapter.d.ts.map +1 -1
  2. package/dist/adapters/chatModelAdapter.d.ts +4 -1
  3. package/dist/adapters/chatModelAdapter.d.ts.map +1 -1
  4. package/dist/adapters/streamingMetadataStore.d.ts +55 -0
  5. package/dist/adapters/streamingMetadataStore.d.ts.map +1 -0
  6. package/dist/adapters/threadListAdapter.d.ts +1 -1
  7. package/dist/adapters/threadListAdapter.d.ts.map +1 -1
  8. package/dist/components/CuadraChat.d.ts.map +1 -1
  9. package/dist/components/CuadraRuntimeProvider.d.ts +3 -1
  10. package/dist/components/CuadraRuntimeProvider.d.ts.map +1 -1
  11. package/dist/components/SimpleThread.d.ts.map +1 -1
  12. package/dist/components/SourceCitations.d.ts +14 -0
  13. package/dist/components/SourceCitations.d.ts.map +1 -0
  14. package/dist/components/WidgetContent.d.ts +2 -0
  15. package/dist/components/WidgetContent.d.ts.map +1 -1
  16. package/dist/components/ui/badge.d.ts +10 -0
  17. package/dist/components/ui/badge.d.ts.map +1 -0
  18. package/dist/index.cjs +13 -13
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.ts +7 -0
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.mjs +1855 -1586
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/lib/cuadraChatClient.d.ts +17 -7
  25. package/dist/lib/cuadraChatClient.d.ts.map +1 -1
  26. package/dist/types/cuadra.d.ts +17 -0
  27. package/dist/types/cuadra.d.ts.map +1 -1
  28. package/dist/uikit.css +1 -1
  29. package/dist/utils/applyTheme.d.ts +1 -1
  30. package/dist/utils/applyTheme.d.ts.map +1 -1
  31. package/dist/widget/cuadra-uikit.css +1 -1
  32. package/dist/widget/cuadra-uikit.umd.js +26 -26
  33. package/dist/widget/cuadra-uikit.umd.js.map +1 -1
  34. package/package.json +1 -1
  35. package/dist/components/FakeReasoningLoader.d.ts +0 -4
  36. package/dist/components/FakeReasoningLoader.d.ts.map +0 -1
@@ -1,40 +1,40 @@
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,$.ReactDOM))})(this,(function($,p,g,he,Le){"use strict";var rv=Object.defineProperty,nv=Object.defineProperties;var av=Object.getOwnPropertyDescriptors;var xn=Object.getOwnPropertySymbols;var _u=Object.prototype.hasOwnProperty,Tu=Object.prototype.propertyIsEnumerable;var ei=($,p)=>(p=Symbol[$])?p:Symbol.for("Symbol."+$),Cu=$=>{throw TypeError($)},Iu=Math.pow,ti=($,p,g)=>p in $?rv($,p,{enumerable:!0,configurable:!0,writable:!0,value:g}):$[p]=g,m=($,p)=>{for(var g in p||(p={}))_u.call(p,g)&&ti($,g,p[g]);if(xn)for(var g of xn(p))Tu.call(p,g)&&ti($,g,p[g]);return $},E=($,p)=>nv($,av(p));var W=($,p)=>{var g={};for(var he in $)_u.call($,he)&&p.indexOf(he)<0&&(g[he]=$[he]);if($!=null&&xn)for(var he of xn($))p.indexOf(he)<0&&Tu.call($,he)&&(g[he]=$[he]);return g};var C=($,p,g)=>ti($,typeof p!="symbol"?p+"":p,g),Eu=($,p,g)=>p.has($)||Cu("Cannot "+g);var Be=($,p,g)=>(Eu($,p,"read from private field"),g?g.call($):p.get($)),Yt=($,p,g)=>p.has($)?Cu("Cannot add the same private member more than once"):p instanceof WeakSet?p.add($):p.set($,g),Xt=($,p,g,he)=>(Eu($,p,"write to private field"),he?he.call($,g):p.set($,g),g);var P=($,p,g)=>new Promise((he,Le)=>{var Te=we=>{try{Y(g.next(we))}catch(De){Le(De)}},ze=we=>{try{Y(g.throw(we))}catch(De){Le(De)}},Y=we=>we.done?he(we.value):Promise.resolve(we.value).then(Te,ze);Y((g=g.apply($,p)).next())}),qe=function($,p){this[0]=$,this[1]=p},Er=($,p,g)=>{var he=(ze,Y,we,De)=>{try{var Qt=g[ze](Y),Zt=(Y=Qt.value)instanceof qe,kn=Qt.done;Promise.resolve(Zt?Y[0]:Y).then(et=>Zt?he(ze==="return"?ze:"next",Y[1]?{done:et.done,value:et.value}:et,we,De):we({value:et,done:kn})).catch(et=>he("throw",et,we,De))}catch(et){De(et)}},Le=ze=>Te[ze]=Y=>new Promise((we,De)=>he(ze,Y,we,De)),Te={};return g=g.apply($,p),Te[ei("asyncIterator")]=()=>Te,Le("next"),Le("throw"),Le("return"),Te};var Mt=($,p,g)=>(p=$[ei("asyncIterator")])?p.call($):($=$[ei("iterator")](),p={},g=(he,Le)=>(Le=$[he])&&(p[he]=Te=>new Promise((ze,Y,we)=>(Te=Le.call($,Te),we=Te.done,Promise.resolve(Te.value).then(De=>ze({value:De,done:we}),Y)))),g("next"),g("return"),p);var Ye,Pt,$e,xu,kr,vu,_r,Tr,Cr,Su,ku;var Te=typeof document!="undefined"?document.currentScript:null;function ze(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 Y=ze(g);const we=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),De=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,r,n)=>n?n.toUpperCase():r.toLowerCase()),Qt=e=>{const t=De(e);return t.charAt(0).toUpperCase()+t.slice(1)},Zt=(...e)=>e.filter((t,r,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===r).join(" ").trim(),kn=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var et={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 Pu=g.forwardRef((u,l)=>{var d=u,{color:e="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:a="",children:i,iconNode:s}=d,o=W(d,["color","size","strokeWidth","absoluteStrokeWidth","className","children","iconNode"]);return g.createElement("svg",m(m(E(m({ref:l},et),{width:t,height:t,stroke:e,strokeWidth:n?Number(r)*24/Number(t):r,className:Zt("lucide",a)}),!i&&!kn(o)&&{"aria-hidden":"true"}),o),[...s.map(([c,f])=>g.createElement(c,f)),...Array.isArray(i)?i:[i]])});const Re=(e,t)=>{const r=g.forwardRef((s,i)=>{var o=s,{className:n}=o,a=W(o,["className"]);return g.createElement(Pu,m({ref:i,iconNode:t,className:Zt(`lucide-${we(Qt(e))}`,`lucide-${e}`,n)},a))});return r.displayName=Qt(e),r};const Mu=Re("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);const Nu=Re("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);const ni=Re("chevron-down",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);const Lu=Re("contrast",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 18a6 6 0 0 0 0-12v12z",key:"j4l70d"}]]);const Du=Re("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 Ou=Re("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 ai=Re("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);const Fu=Re("log-out",[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]]);const Bu=Re("menu",[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]]);const ii=Re("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 zu=Re("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);const _n=Re("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);var Ru=e=>Array.from(e).map(r=>r.getModelContext()).sort((r,n)=>{var a,i;return((a=n.priority)!=null?a:0)-((i=r.priority)!=null?i:0)}).reduce((r,n)=>{var a;if(n.system&&(r.system?r.system+=`
1
+ (function(H,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):(H=typeof globalThis!="undefined"?globalThis:H||self,p(H.CuadraUIKit={},H.React,H.React,H.ReactDOM,H.ReactDOM))})(this,(function(H,p,y,fe,Re){"use strict";var dv=Object.defineProperty,hv=Object.defineProperties;var fv=Object.getOwnPropertyDescriptors;var xn=Object.getOwnPropertySymbols;var Tu=Object.prototype.hasOwnProperty,Cu=Object.prototype.propertyIsEnumerable;var ni=(H,p)=>(p=Symbol[H])?p:Symbol.for("Symbol."+H),Iu=H=>{throw TypeError(H)},Eu=Math.pow,ai=(H,p,y)=>p in H?dv(H,p,{enumerable:!0,configurable:!0,writable:!0,value:y}):H[p]=y,m=(H,p)=>{for(var y in p||(p={}))Tu.call(p,y)&&ai(H,y,p[y]);if(xn)for(var y of xn(p))Cu.call(p,y)&&ai(H,y,p[y]);return H},E=(H,p)=>hv(H,fv(p));var V=(H,p)=>{var y={};for(var fe in H)Tu.call(H,fe)&&p.indexOf(fe)<0&&(y[fe]=H[fe]);if(H!=null&&xn)for(var fe of xn(H))p.indexOf(fe)<0&&Cu.call(H,fe)&&(y[fe]=H[fe]);return y};var C=(H,p,y)=>ai(H,typeof p!="symbol"?p+"":p,y),Au=(H,p,y)=>p.has(H)||Iu("Cannot "+y);var qe=(H,p,y)=>(Au(H,p,"read from private field"),y?y.call(H):p.get(H)),Xt=(H,p,y)=>p.has(H)?Iu("Cannot add the same private member more than once"):p instanceof WeakSet?p.add(H):p.set(H,y),Qt=(H,p,y,fe)=>(Au(H,p,"write to private field"),fe?fe.call(H,y):p.set(H,y),y);var P=(H,p,y)=>new Promise((fe,Re)=>{var Me=ke=>{try{G(y.next(ke))}catch(je){Re(je)}},Ve=ke=>{try{G(y.throw(ke))}catch(je){Re(je)}},G=ke=>ke.done?fe(ke.value):Promise.resolve(ke.value).then(Me,Ve);G((y=y.apply(H,p)).next())}),Ge=function(H,p){this[0]=H,this[1]=p},Mr=(H,p,y)=>{var fe=(Ve,G,ke,je)=>{try{var Zt=y[Ve](G),er=(G=Zt.value)instanceof Ge,Sn=Zt.done;Promise.resolve(er?G[0]:G).then(at=>er?fe(Ve==="return"?Ve:"next",G[1]?{done:at.done,value:at.value}:at,ke,je):ke({value:at,done:Sn})).catch(at=>fe("throw",at,ke,je))}catch(at){je(at)}},Re=Ve=>Me[Ve]=G=>new Promise((ke,je)=>fe(Ve,G,ke,je)),Me={};return y=y.apply(H,p),Me[ni("asyncIterator")]=()=>Me,Re("next"),Re("throw"),Re("return"),Me};var Nt=(H,p,y)=>(p=H[ni("asyncIterator")])?p.call(H):(H=H[ni("iterator")](),p={},y=(fe,Re)=>(Re=H[fe])&&(p[fe]=Me=>new Promise((Ve,G,ke)=>(Me=Re.call(H,Me),ke=Me.done,Promise.resolve(Me.value).then(je=>Ve({value:je,done:ke}),G)))),y("next"),y("return"),p);var rt,Mt,Je,vu,_r,ku,Tr,Cr,Ir,Su,_u;var Me=typeof document!="undefined"?document.currentScript:null;function Ve(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 G=Ve(y);const ke=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),je=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,r,n)=>n?n.toUpperCase():r.toLowerCase()),Zt=e=>{const t=je(e);return t.charAt(0).toUpperCase()+t.slice(1)},er=(...e)=>e.filter((t,r,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===r).join(" ").trim(),Sn=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var at={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 Pu=y.forwardRef((u,l)=>{var c=u,{color:e="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:a="",children:i,iconNode:s}=c,o=V(c,["color","size","strokeWidth","absoluteStrokeWidth","className","children","iconNode"]);return y.createElement("svg",m(m(E(m({ref:l},at),{width:t,height:t,stroke:e,strokeWidth:n?Number(r)*24/Number(t):r,className:er("lucide",a)}),!i&&!Sn(o)&&{"aria-hidden":"true"}),o),[...s.map(([d,f])=>y.createElement(d,f)),...Array.isArray(i)?i:[i]])});const Ce=(e,t)=>{const r=y.forwardRef((s,i)=>{var o=s,{className:n}=o,a=V(o,["className"]);return y.createElement(Pu,m({ref:i,iconNode:t,className:er(`lucide-${ke(Zt(e))}`,`lucide-${e}`,n)},a))});return r.displayName=Zt(e),r};const Nu=Ce("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);const Lu=Ce("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 Du=Ce("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);const _n=Ce("chevron-down",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);const Ou=Ce("contrast",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 18a6 6 0 0 0 0-12v12z",key:"j4l70d"}]]);const Fu=Ce("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 Bu=Ce("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 zu=Ce("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 si=Ce("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 Ru=Ce("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 oi=Ce("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);const ju=Ce("log-out",[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]]);const $u=Ce("menu",[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]]);const li=Ce("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 Uu=Ce("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);const Tn=Ce("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);var Hu=e=>Array.from(e).map(r=>r.getModelContext()).sort((r,n)=>{var a,i;return((a=n.priority)!=null?a:0)-((i=r.priority)!=null?i: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[i,s]of Object.entries(n.tools)){const o=(a=r.tools)==null?void 0:a[i];if(o&&o!==s)throw new Error(`You tried to define a tool with the name ${i}, but it already exists.`);r.tools||(r.tools={}),r.tools[i]=s}return n.config&&(r.config=m(m({},r.config),n.config)),n.callSettings&&(r.callSettings=m(m({},r.callSettings),n.callSettings)),r},{}),Tn=class{constructor(){C(this,"_providers",new Set);C(this,"_subscribers",new Set)}getModelContext(){return Ru(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)}},Cn=class{constructor(){C(this,"_contextProvider",new Tn)}registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}},er=class{constructor(){C(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)}},ju=e=>e.status.type==="complete",si=class extends er{constructor(){super(...arguments);C(this,"isEditing",!0);C(this,"_attachments",[]);C(this,"_text","");C(this,"_role","user");C(this,"_runConfig",{});C(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 P(this,null,function*(){const t=this.getAttachmentAdapter();t&&(yield Promise.all(this._attachments.map(r=>t.remove(r))))})}reset(){return P(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 P(this,null,function*(){const t=this._onClearAttachments();this.setAttachments([]),yield t})}send(){return P(this,null,function*(){const t=this.getAttachmentAdapter(),r=t&&this.attachments.length>0?Promise.all(this.attachments.map(i=>P(this,null,function*(){return ju(i)?i:yield t.send(i)}))):[],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 P(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 i=Mt(a),s,o,l;s=!(o=yield i.next()).done;s=!1){const u=o.value;n(u)}}catch(o){l=[o]}finally{try{s&&(o=i.return)&&(yield o.call(i))}finally{if(l)throw l[0]}}else n(yield a);this._notifyEventSubscribers("attachment-add"),this._notifySubscribers()})}removeAttachment(t){return P(this,null,function*(){const r=this.getAttachmentAdapter();if(!r)throw new Error("Attachments are not supported");const n=this._attachments.findIndex(i=>i.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)}}},oi=class extends si{constructor(t){super();C(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 P(this,null,function*(){var r,n;this.runtime.append(E(m({},t),{parentId:(n=(r=this.runtime.messages.at(-1))==null?void 0:r.id)!=null?n:null,sourceId:null}))})}handleCancel(){return P(this,null,function*(){this.runtime.cancelRun()})}};let li=(e,t=21)=>(r=t)=>{let n="",a=r|0;for(;a--;)n+=e[Math.random()*e.length|0];return n};var vt=li("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),$u="__optimistic__",Uu=()=>`${$u}${vt()}`,tr=Symbol("autoStatus"),Hu=Object.freeze(Object.assign({type:"running"},{[tr]:!0})),qu=Object.freeze(Object.assign({type:"complete",reason:"unknown"},{[tr]:!0})),Vu=Object.freeze(Object.assign({type:"requires-action",reason:"tool-calls"},{[tr]:!0})),Wu=Object.freeze(Object.assign({type:"requires-action",reason:"interrupt"},{[tr]:!0})),ui=(e,t,r,n,a)=>e&&a?Object.assign({type:"incomplete",reason:"error",error:a},{[tr]:!0}):e&&t?Hu:r?Wu:n?Vu:qu;function Ar(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var St={exports:{}},ci;function Ju(){if(ci)return St.exports;ci=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 y in h){const S=h[y];S&&typeof S=="object"&&c.push(S)}}}return o}function i(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 St.exports=i,St.exports.default=i,St.exports.parse=i,St.exports.safeParse=s,St.exports.scan=a,St.exports}var Ku=Ju();const In=Ar(Ku);function Gu(e){const t=["ROOT"];let r=-1,n=null;const a=[];let i;function s(){i!==void 0&&(a.push(JSON.parse(`"${i}"`)),i=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(),i=a.pop();break}}}function u(c,f){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),i=(Number(i)+1).toString();break}case"]":{r=f,t.pop(),i=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"),i="";break}case"}":{r=c,t.pop(),i=a.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),i="";break}}break}case"INSIDE_OBJECT_KEY":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}case"\\":{t.push("INSIDE_STRING_ESCAPE"),i+=f;break}default:{i+=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,i=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(),i=a.pop();break}default:{r=c,i="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"),i=(Number(i)+1).toString();break}case"]":{r=c,t.pop(),i=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"&&(i+=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(),i=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(),i=a.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(f,c);break}case"]":{t.pop(),i=a.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,c);break}default:{t.pop(),i=a.pop();break}}break}case"INSIDE_LITERAL":{const y=e.substring(n,c+1);!"false".startsWith(y)&&!"true".startsWith(y)&&!"null".startsWith(y)?(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 Pr=Symbol("aui.parse-partial-json-object.meta"),Yu=e=>e==null?void 0:e[Pr],Mr=e=>{if(e.length===0)return{[Pr]:{state:"partial",partialPath:[]}};try{const t=In.parse(e);if(typeof t!="object"||t===null)throw new Error("argsText is expected to be an object");return t[Pr]={state:"complete",partialPath:[]},t}catch(t){try{const[r,n]=Gu(e),a=In.parse(r);if(typeof a!="object"||a===null)throw new Error("argsText is expected to be an object");return a[Pr]={state:"partial",partialPath:n},a}catch(r){return}}},di=(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[i,...s]=t.partialPath;if(n!==i)return"complete";const o=e[n];return di(o,{state:"partial",partialPath:s},a)},Nt=(e,t)=>{const r=Yu(e);if(!r)throw new Error("unable to determine object state");return di(e,r,t.map(String))};function Xu(){return Er(this,null,function*(){const e=this.getReader();try{for(;;){const{done:t,value:r}=yield new qe(e.read());if(t)break;yield r}}finally{e.releaseLock()}})}function En(e){var t,r;return(r=e[t=Symbol.asyncIterator])!=null||(e[t]=Xu),e}var An={toResponse(e,t){var r;return new Response(An.toByteStream(e,t),{headers:(r=t.headers)!=null?r:{}})},fromResponse(e,t){return An.fromByteStream(e.body,t)},toByteStream(e,t){return e.pipeThrough(t)},fromByteStream(e,t){return e.pipeThrough(t)}},Pn=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}},Qu=()=>{const e=[];let t=!1,r,n;const a=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=Pn(),e.forEach(s=>{a(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),a(o)},enqueue(s){this.addStream(new ReadableStream({start(o){o.enqueue(s),o.close()}}))}}},hi=class{constructor(e){C(this,"_controller");C(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())}},fi=e=>new ReadableStream({start(t){var r;return(r=e.start)==null?void 0:r.call(e,new hi(t))},pull(t){var r;return(r=e.pull)==null?void 0:r.call(e,new hi(t))},cancel(t){var r;return(r=e.cancel)==null?void 0:r.call(e,t)}}),pi=()=>{let e;return[fi({start(r){e=r}}),e]},mi=class{constructor(e){C(this,"_isClosed",!1);C(this,"_mergeTask");C(this,"_argsTextController");this._controller=e;const t=fi({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 P(this,null,function*(){var t;this._argsTextController.close(),yield Promise.resolve(),this._controller.enqueue(E(m({type:"result",path:[]},e.artifact!==void 0?{artifact:e.artifact}:{}),{result:e.result,isError:(t=e.isError)!=null?t:!1}))})}close(){return P(this,null,function*(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),yield this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())})}},Zu=e=>new ReadableStream({start(t){var r;return(r=e.start)==null?void 0:r.call(e,new mi(t))},pull(t){var r;return(r=e.pull)==null?void 0:r.call(e,new mi(t))},cancel(t){var r;return(r=e.cancel)==null?void 0:r.call(e,t)}}),ec=()=>{let e;return[Zu({start(r){e=r}}),e]},gi=class{constructor(){C(this,"value",-1)}up(){return++this.value}},tc=class extends TransformStream{constructor(e){super({transform(t,r){r.enqueue(E(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(E(m({},t),{path:a}))}})}});var rc=class extends TransformStream{constructor(e){const t=new gi,r=new Map;super({transform(n,a){n.type==="part-start"&&n.path.length===0&&r.set(t.up(),e.up());const[i,...s]=n.path;if(i===void 0){a.enqueue(n);return}const o=r.get(i);if(o===void 0)throw new Error("Path not found");a.enqueue(E(m({},n),{path:[o,...s]}))}})}},yi=class extends TransformStream{constructor(e){super();const t=e(super.readable);Object.defineProperty(this,"readable",{value:t,writable:!1})}},bi=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(E(m({},t),{meta:a}));return}r.enqueue(t)}})}},wi=li("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),nc=class Au{constructor(t){C(this,"_state");C(this,"_parentId");this._state=t||{merger:Qu(),contentCounter:new gi}}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 tc(this._state.contentCounter.value)))}merge(t){this._state.merger.addStream(t.pipeThrough(new rc(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]=pi();return this._addPart({type:"text"},t),r}addReasoningPart(){const[t,r]=pi();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:wi(),[i,s]=ec();return this._addPart(m({type:"tool-call",toolName:n,toolCallId:a},this._parentId&&{parentId:this._parentId}),i),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 Au(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 ac(e){const t=new nc;return P(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 xi(){const{resolve:e,promise:t}=Pn();let r;return[ac(a=>(r=a,r.__internal_subscribeToClose(e),t)),r]}var ic=class extends TransformStream{constructor(e,t,r){const[n,a]=xi();let i;super({start(o){var l;return i=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 P(this,null,function*(){var o;yield(o=e.flush)==null?void 0:o.call(e,a),a.close(),yield i})}},t,r)}},rr=(e,t,r)=>{var f,h,y,S,x,b,_;const{role:n,id:a,createdAt:i,attachments:s,status:o,metadata:l}=e,u={id:a!=null?a:t,createdAt:i!=null?i:new Date},d=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content,c=z=>{var I=z,{image:T}=I,L=W(I,["image"]);return T.match(/^data:image\/(png|jpeg|jpg|gif|webp);base64,(.*)$/)?E(m({},L),{image:T}):(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 E(m({},u),{role:n,content:d.map(T=>{var I,q,B,U,k;const L=T.type;switch(L){case"text":case"reasoning":return T.text.trim().length===0?null:T;case"file":case"source":return T;case"image":return c(T);case"data":return T;case"tool-call":{const z=T,{parentId:D,messages:M}=z,H=W(z,["parentId","messages"]),R=m(m(E(m({},H),{toolCallId:(I=T.toolCallId)!=null?I:`tool-${vt()}`}),D!==void 0&&{parentId:D}),M!==void 0&&{messages:M});return T.args?E(m({},R),{args:T.args,argsText:(q=T.argsText)!=null?q:JSON.stringify(T.args)}):E(m({},R),{args:(U=Mr((B=T.argsText)!=null?B:""))!=null?U:{},argsText:(k=T.argsText)!=null?k:""})}default:{const D=L;throw new Error(`Unsupported assistant message part type: ${D}`)}}}).filter(T=>!!T),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:(y=l==null?void 0:l.unstable_data)!=null?y:[],custom:(S=l==null?void 0:l.custom)!=null?S:{},steps:(x=l==null?void 0:l.steps)!=null?x:[]},(l==null?void 0:l.submittedFeedback)&&{submittedFeedback:l.submittedFeedback})});case"user":return E(m({},u),{role:n,content:d.map(T=>{const L=T.type;switch(L){case"text":case"image":case"audio":case"file":return T;default:{const z=L;throw new Error(`Unsupported user message part type: ${z}`)}}}),attachments:s!=null?s:[],metadata:{custom:(b=l==null?void 0:l.custom)!=null?b:{}}});case"system":if(d.length!==1||d[0].type!=="text")throw new Error("System messages must have exactly one text message part.");return E(m({},u),{role:n,content:d,metadata:{custom:(_=l==null?void 0:l.custom)!=null?_:{}}});default:{const T=n;throw new Error(`Unknown message role: ${T}`)}}},Mn={fromArray:e=>{const t=e.map(r=>rr(r,vt(),ui(!1,!1,!1,!1,void 0)));return{messages:t.map((r,n)=>({parentId:n>0?t[n-1].id:null,message:r}))}}},Nr=e=>e.next?Nr(e.next):"current"in e?e:null,sc=class{constructor(e){C(this,"_value",null);this.func=e}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},vi=class{constructor(){C(this,"messages",new Map);C(this,"head",null);C(this,"root",{children:[],next:null});C(this,"_messages",new sc(()=>{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 i;const n=(i=t.prev)!=null?i:this.root,a=e!=null?e:this.root;if(!(r==="relink"&&n===a)){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.");a.children=[...a.children,t.current.id],(Nr(t)===this.head||a.next===null)&&(a.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 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=Uu();while(this.messages.has(r));return this.addOrUpdateMessage(e,rr(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 i=this.messages.get(a);if(!i)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(n,i,"relink")}this.performOp(null,r,"cut"),this.messages.delete(e),this.head===r&&(this.head=Nr(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=Nr(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 i=this.messages.get(a);i&&(r(i),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[,i]of this.messages)e.push({message:i.current,parentId:(r=(t=i.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:i}of t)this.addOrUpdateMessage(i,a);this.resetHead((n=e!=null?e:(r=t.at(-1))==null?void 0:r.message.id)!=null?n:null)}},Lr=class{constructor(){C(this,"_subscriptions",new Set);C(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()}}},Ve=Symbol("skip-update"),Nn=class extends Lr{constructor(t){super();C(this,"_previousStateDirty",!0);C(this,"_previousState");C(this,"getState",()=>{if(!this.isConnected||this._previousStateDirty){const t=this.binding.getState();t!==Ve&&(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)}},Dr=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(),i=a.isMain,s=a.id;r===i&&n===s||(r=i,n=s,!(e==="switched-to"&&!i)&&(e==="switched-away"&&i||t()))})}subscribe(e){return this._core.subscribe(e)}detach(){const e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}};function oc(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 We=class extends Lr{constructor(t){super();C(this,"_previousState");C(this,"getState",()=>(this.isConnected||this._syncState(),this._previousState));this.binding=t;const r=t.getState();if(r===Ve)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===Ve||oc(t,this._previousState)?!1:(this._previousState=t,!0)}_connect(){const t=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(t)}},Or=Symbol("innerMessage"),Fr=e=>e.content.filter(r=>r.type==="text").map(r=>r.text).join(`
3
+ ${n.system}`:r.system=n.system),n.tools)for(const[i,s]of Object.entries(n.tools)){const o=(a=r.tools)==null?void 0:a[i];if(o&&o!==s)throw new Error(`You tried to define a tool with the name ${i}, but it already exists.`);r.tools||(r.tools={}),r.tools[i]=s}return n.config&&(r.config=m(m({},r.config),n.config)),n.callSettings&&(r.callSettings=m(m({},r.callSettings),n.callSettings)),r},{}),Cn=class{constructor(){C(this,"_providers",new Set);C(this,"_subscribers",new Set)}getModelContext(){return Hu(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)}},In=class{constructor(){C(this,"_contextProvider",new Cn)}registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}},tr=class{constructor(){C(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)}},qu=e=>e.status.type==="complete",ui=class extends tr{constructor(){super(...arguments);C(this,"isEditing",!0);C(this,"_attachments",[]);C(this,"_text","");C(this,"_role","user");C(this,"_runConfig",{});C(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 P(this,null,function*(){const t=this.getAttachmentAdapter();t&&(yield Promise.all(this._attachments.map(r=>t.remove(r))))})}reset(){return P(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 P(this,null,function*(){const t=this._onClearAttachments();this.setAttachments([]),yield t})}send(){return P(this,null,function*(){const t=this.getAttachmentAdapter(),r=t&&this.attachments.length>0?Promise.all(this.attachments.map(i=>P(this,null,function*(){return qu(i)?i:yield t.send(i)}))):[],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 P(this,null,function*(){const r=this.getAttachmentAdapter();if(!r)throw new Error("Attachments are not supported");const n=u=>{const c=this._attachments.findIndex(d=>d.id===u.id);c!==-1?this._attachments=[...this._attachments.slice(0,c),u,...this._attachments.slice(c+1)]:this._attachments=[...this._attachments,u],this._notifySubscribers()},a=r.add({file:t});if(Symbol.asyncIterator in a)try{for(var i=Nt(a),s,o,l;s=!(o=yield i.next()).done;s=!1){const u=o.value;n(u)}}catch(o){l=[o]}finally{try{s&&(o=i.return)&&(yield o.call(i))}finally{if(l)throw l[0]}}else n(yield a);this._notifyEventSubscribers("attachment-add"),this._notifySubscribers()})}removeAttachment(t){return P(this,null,function*(){const r=this.getAttachmentAdapter();if(!r)throw new Error("Attachments are not supported");const n=this._attachments.findIndex(i=>i.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)}}},ci=class extends ui{constructor(t){super();C(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 P(this,null,function*(){var r,n;this.runtime.append(E(m({},t),{parentId:(n=(r=this.runtime.messages.at(-1))==null?void 0:r.id)!=null?n:null,sourceId:null}))})}handleCancel(){return P(this,null,function*(){this.runtime.cancelRun()})}};let di=(e,t=21)=>(r=t)=>{let n="",a=r|0;for(;a--;)n+=e[Math.random()*e.length|0];return n};var xt=di("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),Vu="__optimistic__",Wu=()=>`${Vu}${xt()}`,rr=Symbol("autoStatus"),Ju=Object.freeze(Object.assign({type:"running"},{[rr]:!0})),Ku=Object.freeze(Object.assign({type:"complete",reason:"unknown"},{[rr]:!0})),Yu=Object.freeze(Object.assign({type:"requires-action",reason:"tool-calls"},{[rr]:!0})),Gu=Object.freeze(Object.assign({type:"requires-action",reason:"interrupt"},{[rr]:!0})),hi=(e,t,r,n,a)=>e&&a?Object.assign({type:"incomplete",reason:"error",error:a},{[rr]:!0}):e&&t?Ju:r?Gu:n?Yu:Ku;function Pr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var vt={exports:{}},fi;function Xu(){if(fi)return vt.exports;fi=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 c=JSON.parse(o,l);if(c===null||typeof c!="object")return c;const d=u&&u.protoAction||"error",f=u&&u.constructorAction||"error";if(d==="ignore"&&f==="ignore")return c;if(d!=="ignore"&&f!=="ignore"){if(t.test(o)===!1&&r.test(o)===!1)return c}else if(d!=="ignore"&&f==="ignore"){if(t.test(o)===!1)return c}else if(r.test(o)===!1)return c;return a(c,{protoAction:d,constructorAction:f,safe:u&&u.safe})}function a(o,{protoAction:l="error",constructorAction:u="error",safe:c}={}){let d=[o];for(;d.length;){const f=d;d=[];for(const h of f){if(l!=="ignore"&&Object.prototype.hasOwnProperty.call(h,"__proto__")){if(c===!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(c===!0)return null;if(u==="error")throw new SyntaxError("Object contains forbidden prototype property");delete h.constructor}for(const g in h){const k=h[g];k&&typeof k=="object"&&d.push(k)}}}return o}function i(o,l,u){const{stackTraceLimit:c}=Error;Error.stackTraceLimit=0;try{return n(o,l,u)}finally{Error.stackTraceLimit=c}}function s(o,l){const{stackTraceLimit:u}=Error;Error.stackTraceLimit=0;try{return n(o,l,{safe:!0})}catch(c){return}finally{Error.stackTraceLimit=u}}return vt.exports=i,vt.exports.default=i,vt.exports.parse=i,vt.exports.safeParse=s,vt.exports.scan=a,vt.exports}var Qu=Xu();const En=Pr(Qu);function Zu(e){const t=["ROOT"];let r=-1,n=null;const a=[];let i;function s(){i!==void 0&&(a.push(JSON.parse(`"${i}"`)),i=void 0)}function o(d,f,h){switch(d){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(d,f){switch(d){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=f,t.pop(),i=a.pop();break}}}function u(d,f){switch(d){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),i=(Number(i)+1).toString();break}case"]":{r=f,t.pop(),i=a.pop();break}}}for(let d=0;d<e.length;d++){const f=e[d];switch(t[t.length-1]){case"ROOT":o(f,d,"FINISH");break;case"INSIDE_OBJECT_START":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),i="";break}case"}":{r=d,t.pop(),i=a.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),i="";break}}break}case"INSIDE_OBJECT_KEY":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}case"\\":{t.push("INSIDE_STRING_ESCAPE"),i+=f;break}default:{i+=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,d,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{l(f,d);break}case"INSIDE_STRING":{switch(f){case'"':{t.pop(),r=d,i=a.pop();break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=d}break}case"INSIDE_ARRAY_START":{switch(f){case"]":{r=d,t.pop(),i=a.pop();break}default:{r=d,i="0",o(f,d,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(f){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),i=(Number(i)+1).toString();break}case"]":{r=d,t.pop(),i=a.pop();break}default:{r=d;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(f,d,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),t[t.length-1]==="INSIDE_STRING"?r=d:t[t.length-1]==="INSIDE_OBJECT_KEY"&&(i+=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=d;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),i=a.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,d),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(f,d);break}case"}":{t.pop(),i=a.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(f,d);break}case"]":{t.pop(),i=a.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,d);break}default:{t.pop(),i=a.pop();break}}break}case"INSIDE_LITERAL":{const g=e.substring(n,d+1);!"false".startsWith(g)&&!"true".startsWith(g)&&!"null".startsWith(g)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?l(f,d):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(f,d)):r=d;break}}}let c=e.slice(0,r+1);for(let d=t.length-1;d>=0;d--)switch(t[d]){case"INSIDE_STRING":{c+='"';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":{c+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{c+="]";break}case"INSIDE_LITERAL":{const h=e.substring(n,e.length);"true".startsWith(h)?c+="true".slice(h.length):"false".startsWith(h)?c+="false".slice(h.length):"null".startsWith(h)&&(c+="null".slice(h.length))}}return[c,a]}var Nr=Symbol("aui.parse-partial-json-object.meta"),ec=e=>e==null?void 0:e[Nr],Lr=e=>{if(e.length===0)return{[Nr]:{state:"partial",partialPath:[]}};try{const t=En.parse(e);if(typeof t!="object"||t===null)throw new Error("argsText is expected to be an object");return t[Nr]={state:"complete",partialPath:[]},t}catch(t){try{const[r,n]=Zu(e),a=En.parse(r);if(typeof a!="object"||a===null)throw new Error("argsText is expected to be an object");return a[Nr]={state:"partial",partialPath:n},a}catch(r){return}}},pi=(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[i,...s]=t.partialPath;if(n!==i)return"complete";const o=e[n];return pi(o,{state:"partial",partialPath:s},a)},Lt=(e,t)=>{const r=ec(e);if(!r)throw new Error("unable to determine object state");return pi(e,r,t.map(String))};function tc(){return Mr(this,null,function*(){const e=this.getReader();try{for(;;){const{done:t,value:r}=yield new Ge(e.read());if(t)break;yield r}}finally{e.releaseLock()}})}function An(e){var t,r;return(r=e[t=Symbol.asyncIterator])!=null||(e[t]=tc),e}var Mn={toResponse(e,t){var r;return new Response(Mn.toByteStream(e,t),{headers:(r=t.headers)!=null?r:{}})},fromResponse(e,t){return Mn.fromByteStream(e.body,t)},toByteStream(e,t){return e.pipeThrough(t)},fromByteStream(e,t){return e.pipeThrough(t)}},Pn=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}},rc=()=>{const e=[];let t=!1,r,n;const a=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=Pn(),e.forEach(s=>{a(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),a(o)},enqueue(s){this.addStream(new ReadableStream({start(o){o.enqueue(s),o.close()}}))}}},mi=class{constructor(e){C(this,"_controller");C(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())}},gi=e=>new ReadableStream({start(t){var r;return(r=e.start)==null?void 0:r.call(e,new mi(t))},pull(t){var r;return(r=e.pull)==null?void 0:r.call(e,new mi(t))},cancel(t){var r;return(r=e.cancel)==null?void 0:r.call(e,t)}}),yi=()=>{let e;return[gi({start(r){e=r}}),e]},bi=class{constructor(e){C(this,"_isClosed",!1);C(this,"_mergeTask");C(this,"_argsTextController");this._controller=e;const t=gi({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 P(this,null,function*(){var t;this._argsTextController.close(),yield Promise.resolve(),this._controller.enqueue(E(m({type:"result",path:[]},e.artifact!==void 0?{artifact:e.artifact}:{}),{result:e.result,isError:(t=e.isError)!=null?t:!1}))})}close(){return P(this,null,function*(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),yield this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())})}},nc=e=>new ReadableStream({start(t){var r;return(r=e.start)==null?void 0:r.call(e,new bi(t))},pull(t){var r;return(r=e.pull)==null?void 0:r.call(e,new bi(t))},cancel(t){var r;return(r=e.cancel)==null?void 0:r.call(e,t)}}),ac=()=>{let e;return[nc({start(r){e=r}}),e]},wi=class{constructor(){C(this,"value",-1)}up(){return++this.value}},ic=class extends TransformStream{constructor(e){super({transform(t,r){r.enqueue(E(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(E(m({},t),{path:a}))}})}});var sc=class extends TransformStream{constructor(e){const t=new wi,r=new Map;super({transform(n,a){n.type==="part-start"&&n.path.length===0&&r.set(t.up(),e.up());const[i,...s]=n.path;if(i===void 0){a.enqueue(n);return}const o=r.get(i);if(o===void 0)throw new Error("Path not found");a.enqueue(E(m({},n),{path:[o,...s]}))}})}},xi=class extends TransformStream{constructor(e){super();const t=e(super.readable);Object.defineProperty(this,"readable",{value:t,writable:!1})}},vi=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(E(m({},t),{meta:a}));return}r.enqueue(t)}})}},ki=di("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),oc=class Mu{constructor(t){C(this,"_state");C(this,"_parentId");this._state=t||{merger:rc(),contentCounter:new wi}}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 ic(this._state.contentCounter.value)))}merge(t){this._state.merger.addStream(t.pipeThrough(new sc(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]=yi();return this._addPart({type:"text"},t),r}addReasoningPart(){const[t,r]=yi();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:ki(),[i,s]=ac();return this._addPart(m({type:"tool-call",toolName:n,toolCallId:a},this._parentId&&{parentId:this._parentId}),i),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 Mu(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 lc(e){const t=new oc;return P(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 Si(){const{resolve:e,promise:t}=Pn();let r;return[lc(a=>(r=a,r.__internal_subscribeToClose(e),t)),r]}var uc=class extends TransformStream{constructor(e,t,r){const[n,a]=Si();let i;super({start(o){var l;return i=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 P(this,null,function*(){var o;yield(o=e.flush)==null?void 0:o.call(e,a),a.close(),yield i})}},t,r)}},nr=(e,t,r)=>{var f,h,g,k,w,b,I;const{role:n,id:a,createdAt:i,attachments:s,status:o,metadata:l}=e,u={id:a!=null?a:t,createdAt:i!=null?i:new Date},c=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content,d=F=>{var _=F,{image:T}=_,B=V(_,["image"]);return T.match(/^data:image\/(png|jpeg|jpg|gif|webp);base64,(.*)$/)?E(m({},B),{image:T}):(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 E(m({},u),{role:n,content:c.map(T=>{var _,$,R,j,S;const B=T.type;switch(B){case"text":case"reasoning":return T.text.trim().length===0?null:T;case"file":case"source":return T;case"image":return d(T);case"data":return T;case"tool-call":{const F=T,{parentId:N,messages:M}=F,J=V(F,["parentId","messages"]),z=m(m(E(m({},J),{toolCallId:(_=T.toolCallId)!=null?_:`tool-${xt()}`}),N!==void 0&&{parentId:N}),M!==void 0&&{messages:M});return T.args?E(m({},z),{args:T.args,argsText:($=T.argsText)!=null?$:JSON.stringify(T.args)}):E(m({},z),{args:(j=Lr((R=T.argsText)!=null?R:""))!=null?j:{},argsText:(S=T.argsText)!=null?S:""})}default:{const N=B;throw new Error(`Unsupported assistant message part type: ${N}`)}}}).filter(T=>!!T),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:(k=l==null?void 0:l.custom)!=null?k:{},steps:(w=l==null?void 0:l.steps)!=null?w:[]},(l==null?void 0:l.submittedFeedback)&&{submittedFeedback:l.submittedFeedback})});case"user":return E(m({},u),{role:n,content:c.map(T=>{const B=T.type;switch(B){case"text":case"image":case"audio":case"file":return T;default:{const F=B;throw new Error(`Unsupported user message part type: ${F}`)}}}),attachments:s!=null?s:[],metadata:{custom:(b=l==null?void 0:l.custom)!=null?b:{}}});case"system":if(c.length!==1||c[0].type!=="text")throw new Error("System messages must have exactly one text message part.");return E(m({},u),{role:n,content:c,metadata:{custom:(I=l==null?void 0:l.custom)!=null?I:{}}});default:{const T=n;throw new Error(`Unknown message role: ${T}`)}}},Nn={fromArray:e=>{const t=e.map(r=>nr(r,xt(),hi(!1,!1,!1,!1,void 0)));return{messages:t.map((r,n)=>({parentId:n>0?t[n-1].id:null,message:r}))}}},Dr=e=>e.next?Dr(e.next):"current"in e?e:null,cc=class{constructor(e){C(this,"_value",null);this.func=e}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},_i=class{constructor(){C(this,"messages",new Map);C(this,"head",null);C(this,"root",{children:[],next:null});C(this,"_messages",new cc(()=>{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 i;const n=(i=t.prev)!=null?i:this.root,a=e!=null?e:this.root;if(!(r==="relink"&&n===a)){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.");a.children=[...a.children,t.current.id],(Dr(t)===this.head||a.next===null)&&(a.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 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=Wu();while(this.messages.has(r));return this.addOrUpdateMessage(e,nr(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 i=this.messages.get(a);if(!i)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(n,i,"relink")}this.performOp(null,r,"cut"),this.messages.delete(e),this.head===r&&(this.head=Dr(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=Dr(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 i=this.messages.get(a);i&&(r(i),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[,i]of this.messages)e.push({message:i.current,parentId:(r=(t=i.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:i}of t)this.addOrUpdateMessage(i,a);this.resetHead((n=e!=null?e:(r=t.at(-1))==null?void 0:r.message.id)!=null?n:null)}},Or=class{constructor(){C(this,"_subscriptions",new Set);C(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()}}},Xe=Symbol("skip-update"),Ln=class extends Or{constructor(t){super();C(this,"_previousStateDirty",!0);C(this,"_previousState");C(this,"getState",()=>{if(!this.isConnected||this._previousStateDirty){const t=this.binding.getState();t!==Xe&&(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)}},Fr=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(),i=a.isMain,s=a.id;r===i&&n===s||(r=i,n=s,!(e==="switched-to"&&!i)&&(e==="switched-away"&&i||t()))})}subscribe(e){return this._core.subscribe(e)}detach(){const e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}};function dc(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 Qe=class extends Or{constructor(t){super();C(this,"_previousState");C(this,"getState",()=>(this.isConnected||this._syncState(),this._previousState));this.binding=t;const r=t.getState();if(r===Xe)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===Xe||dc(t,this._previousState)?!1:(this._previousState=t,!0)}_connect(){const t=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(t)}},Br=Symbol("innerMessage"),zr=e=>e.content.filter(r=>r.type==="text").map(r=>r.text).join(`
4
4
 
5
- `),Si=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)}},ki=class extends Si{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)}},lc=class extends ki{get source(){return"thread-composer"}},uc=class extends ki{get source(){return"edit-composer"}},cc=class extends Si{get source(){return"message"}constructor(e){super(e)}remove(){throw new Error("Message attachments cannot be removed")}},_i=class extends Lr{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 i=this.config.binding.getState();i!==t&&(t=i,r==null||r(),r=(s=this.config.binding.getState())==null?void 0:s.unstable_on(this.config.event,e))},a=this.outerSubscribe(n);return()=>{a==null||a(),r==null||r()}}},Ti=Object.freeze([]),Ci=Object.freeze({}),dc=e=>{var t,r,n,a,i,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:(a=e==null?void 0:e.attachments)!=null?a:Ti,text:(i=e==null?void 0:e.text)!=null?i:"",role:(s=e==null?void 0:e.role)!=null?s:"user",runConfig:(o=e==null?void 0:e.runConfig)!=null?o:Ci,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},hc=e=>{var t,r,n,a,i,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:(a=e==null?void 0:e.text)!=null?a:"",role:(i=e==null?void 0:e.role)!=null?i:"user",attachments:(s=e==null?void 0:e.attachments)!=null?s:Ti,runConfig:(o=e==null?void 0:e.runConfig)!=null?o:Ci,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},Ii=class{constructor(e){C(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 _i({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}},fc=class extends Ii{constructor(t){const r=new Nn({path:t.path,getState:()=>dc(t.getState()),subscribe:n=>t.subscribe(n)});super({path:t.path,getState:()=>t.getState(),subscribe:n=>r.subscribe(n)});C(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 lc(new We({path:E(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?E(m({},n),{source:"thread-composer"}):Ve},subscribe:r=>this._core.subscribe(r)}),this._core)}},pc=class extends Ii{constructor(t,r){const n=new Nn({path:t.path,getState:()=>hc(t.getState()),subscribe:a=>t.subscribe(a)});super({path:t.path,getState:()=>t.getState(),subscribe:a=>n.subscribe(a)});C(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 uc(new We({path:E(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?E(m({},n),{source:"edit-composer"}):Ve},subscribe:r=>this._core.subscribe(r)}),this._core)}},mc=class vn{constructor(t=null){C(this,"_state");this._state=t}get state(){return this._state}append(t){this._state=t.reduce((r,n)=>vn.apply(r,n),this._state)}static apply(t,r){const n=r.type;switch(n){case"set":return vn.updatePath(t,r.path,()=>r.value);case"append-text":return vn.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,...i]=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],i,n),l}const s=m({},t);return s[a]=this.updatePath(s[a],i,n),s}},gc=({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:{}}}),Br=(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 E(m({},e),{parts:[...e.parts.slice(0,n),a,...e.parts.slice(n+1)],get content(){return this.parts}})},yc=(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 E(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 E(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 E(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 E(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else throw new Error(`Unsupported part type: ${r.type}`)},bc=(e,t)=>Br(e,t,r=>{if(r.type!=="tool-call")throw new Error("Last is not a tool call");return r.state!=="partial-call"?r:E(m({},r),{state:"call"})}),wc=(e,t)=>Br(e,t,r=>E(m({},r),{status:{type:"complete",reason:"unknown"}})),xc=(e,t)=>Br(e,t,r=>{var n;if(r.type==="text"||r.type==="reasoning")return E(m({},r),{text:r.text+t.textDelta});if(r.type==="tool-call"){const a=r.argsText+t.textDelta,i=(n=Mr(a))!=null?n:r.args;return E(m({},r),{argsText:a,args:i})}else throw new Error("text-delta received but part is neither text nor tool-call")}),vc=(e,t)=>Br(e,t,r=>{var n;if(r.type==="tool-call")return E(m(E(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")}),Ei=(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=Sc(t);return E(m({},e),{status:r})},Sc=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},kc=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]})}),_c=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{unstable_data:[...e.metadata.unstable_data,...t.data]})}),Tc=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{steps:[...e.metadata.steps,{state:"started",messageId:t.messageId}]})}),Cc=(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]=E(m({},r[n]),{state:"finished",finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}):r.push({state:"finished",messageId:wi(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),E(m({},e),{metadata:E(m({},e.metadata),{steps:r})})},Ic=(e,t)=>E(m({},e),{status:{type:"incomplete",reason:"error",error:t.error}}),Ec=(e,t)=>{const r=new mc(e.metadata.unstable_state);return r.append(t.operations),E(m({},e),{metadata:E(m({},e.metadata),{unstable_state:r.state})})},Ac=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}},Pc=class extends TransformStream{constructor({initialMessage:e,throttle:t,onError:r}={}){let n=e!=null?e:gc(),a;const i=t?Ac(()=>{a==null||a.enqueue(n)}):()=>{a==null||a.enqueue(n)};super({start(s){a=s},transform(s){const o=s.type;switch(o){case"part-start":n=yc(n,s);break;case"tool-call-args-text-finish":n=bc(n,s);break;case"part-finish":n=wc(n,s);break;case"text-delta":n=xc(n,s);break;case"result":n=vc(n,s);break;case"message-finish":n=Ei(n,s);break;case"annotations":n=kc(n,s);break;case"data":n=_c(n,s);break;case"step-start":n=Tc(n,s);break;case"step-finish":n=Cc(n,s);break;case"error":n=Ic(n,s),r==null||r(s.error);break;case"update-state":n=Ec(n,s);break;default:{const l=o;throw new Error(`Unsupported chunk type: ${l}`)}}i()},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=Ei(n,{finishReason:d?"tool-calls":"unknown"}),s.enqueue(n)}}})}},Mc=class extends yi{constructor(){super(e=>{const t=new ic({transform(r,n){n.appendText(r)}});return e.pipeThrough(new TextDecoderStream).pipeThrough(t)})}},Nc=class Sn{constructor(t){this.readable=t,this.readable=t}static fromAssistantStream(t){return new Sn(t.pipeThrough(new Pc))}unstable_result(){return P(this,null,function*(){let t;try{for(var r=Mt(this),n,a,i;n=!(a=yield r.next()).done;n=!1){const s=a.value;t=s}}catch(a){i=[a]}finally{try{n&&(a=r.return)&&(yield a.call(r))}finally{if(i)throw i[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 P(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 Sn(t),new Sn(r)]}},Ai=Symbol.for("aui.tool-response"),ct=class ri{constructor(t){C(this,"artifact");C(this,"result");C(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[Ai](){return!0}static[Symbol.hasInstance](t){return typeof t=="object"&&t!==null&&Ai in t}static toResponse(t){return t instanceof ri?t:new ri({result:t===void 0?"<no result>":t})}};function Lc(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 nr(e,t){let r=e;for(const n of t){if(r==null)return;r=r[n]}return r}var Dc=class{constructor(e,t,r){C(this,"resolve");C(this,"reject");C(this,"disposed",!1);C(this,"fieldPath");this.resolve=e,this.reject=t,this.fieldPath=r}update(e){if(!this.disposed)try{if(Nt(e,this.fieldPath)==="complete"){const t=nr(e,this.fieldPath);t!==void 0&&(this.resolve(t),this.dispose())}}catch(t){this.reject(t),this.dispose()}}dispose(){this.disposed=!0}},Pi=class{constructor(e,t){C(this,"controller");C(this,"disposed",!1);C(this,"fieldPath");this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=nr(e,this.fieldPath);t!==void 0&&this.controller.enqueue(t),Nt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},Mi=class{constructor(e,t){C(this,"controller");C(this,"disposed",!1);C(this,"fieldPath");C(this,"lastValue");this.controller=e,this.fieldPath=t}update(e){var t;if(!this.disposed)try{const r=nr(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)}Nt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(r){this.controller.error(r),this.dispose()}}dispose(){this.disposed=!0}},Ni=class{constructor(e,t){C(this,"controller");C(this,"disposed",!1);C(this,"fieldPath");C(this,"processedIndexes",new Set);this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=nr(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];Nt(e,n)==="complete"&&(this.controller.enqueue(t[r]),this.processedIndexes.add(r))}Nt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},Oc=class{constructor(e){C(this,"argTextDeltas");C(this,"handles",new Set);C(this,"args",Mr(""));this.argTextDeltas=e,this.processStream()}processStream(){return P(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=Mr(e);if(a!==void 0){this.args=a;for(const i of this.handles)i.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 Dc(t,r,e);if(this.args&&Nt(this.args,e)==="complete"){const a=nr(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 Pi(n,t);this.handles.add(a),a.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Pi){n.dispose(),this.handles.delete(n);break}}});return En(r)}streamText(...e){const t=e,r=new ReadableStream({start:n=>{const a=new Mi(n,t);this.handles.add(a),a.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Mi){n.dispose(),this.handles.delete(n);break}}});return En(r)}forEach(...e){const t=e,r=new ReadableStream({start:n=>{const a=new Ni(n,t);this.handles.add(a),a.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Ni){n.dispose(),this.handles.delete(n);break}}});return En(r)}},Fc=class{constructor(e){this.promise=e}get(){return this.promise}},Bc=class{constructor(){C(this,"args");C(this,"response");C(this,"writable");C(this,"resolve");C(this,"argsText","");C(this,"result",{get:()=>P(this,null,function*(){return(yield this.response.get()).result})});const e=new TransformStream;this.writable=e.writable,this.args=new Oc(e.readable);const{promise:t,resolve:r}=Pn();this.resolve=r,this.response=new Fc(t)}appendArgsTextDelta(e){return P(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)}},zc=class extends yi{constructor(e){const t=new Map,r=new Map;super(n=>{const a=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 Bc;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 ct({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=Lc(()=>{var x;let y;try{y=In.parse(c.argsText)}catch(b){throw new Error(`Function parameter parsing failed. ${JSON.stringify(b.message)}`)}const S=e.execute({toolCallId:u,toolName:d,args:y});return S!==void 0&&(f=!0,(x=e.onExecutionStart)==null||x.call(e,u,d)),S},y=>{var x;if(f&&((x=e.onExecutionEnd)==null||x.call(e,u,d)),y===void 0)return;const S=new ct({artifact:y.artifact,result:y.result,isError:y.isError});c.setResponse(S),o.enqueue(m({type:"result",path:s.path},S))},y=>{var x;f&&((x=e.onExecutionEnd)==null||x.call(e,u,d));const S=new ct({result:String(y),isError:!0});c.setResponse(S),o.enqueue(m({type:"result",path:s.path},S))});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 P(this,null,function*(){yield Promise.all(t.values())})}});return n.pipeThrough(new bi).pipeThrough(a)})}},Rc=e=>typeof e=="object"&&e!==null&&"~standard"in e&&e["~standard"].version===1;function jc(e,t,r,n){const a=e==null?void 0:e[r.toolName];return!a||!a.execute?void 0:(s=>P(null,null,function*(){var d;if(t.aborted)return new ct({result:"Tool execution was cancelled.",isError:!0});let o=s;if(Rc(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 ct({result:"Tool execution was cancelled.",isError:!0}))})})};t.aborted?f():t.addEventListener("abort",f,{once:!0})}),u=P(null,null,function*(){const c=yield o(r.args,{toolCallId:r.toolCallId,abortSignal:t,human:f=>n(r.toolCallId,f)});return ct.toResponse(c)});return Promise.race([u,l])}))(a.execute)}function $c(e,t,r,n,a){var i,s;(s=(i=e==null?void 0:e[n.toolName])==null?void 0:i.streamCall)==null||s.call(i,r,{toolCallId:n.toolCallId,abortSignal:t,human:o=>a(n.toolCallId,o)})}function Uc(e,t,r,n){const a=typeof e=="function"?e:()=>e,i=typeof t=="function"?t:()=>t;return new zc({execute:s=>jc(a(),i(),s,r),streamCall:l=>{var u=l,{reader:s}=u,o=W(u,["reader"]);return $c(a(),i(),s,o,r)},onExecutionStart:n==null?void 0:n.onExecutionStart,onExecutionEnd:n==null?void 0:n.onExecutionEnd})}var Li=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,i=ct.toResponse(e);this.threadApi.getState().addToolResult({messageId:r.id,toolName:n,toolCallId:a,result:i.result,artifact:i.artifact,isError:i.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)}},zr=class extends Lr{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 i=this.binding.getState();i!==t&&(t=i,r==null||r(),r=(s=this.binding.getState())==null?void 0:s.subscribe(e),e())},a=this.outerSubscribe(n);return()=>{a==null||a(),r==null||r()}}},Rr=Object.freeze({type:"complete"}),Hc=(e,t,r)=>{if(e.role!=="assistant")return Rr;if(r.type==="tool-call")return r.result?Rr:e.status;const n=t===Math.max(0,e.content.length-1);return e.status.type==="requires-action"?Rr:n?e.status:Rr},Di=(e,t)=>{const r=e.content[t];if(!r)return Ve;const n=Hc(e,t,r);return Object.freeze(E(m({},r),{[Or]:r[Or],status:n}))},qc=class{constructor(e,t){C(this,"composer");C(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=e,this._threadBinding=t,this.composer=new pc(new zr({path:E(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,i=this._core.getState();if(i.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:i.parentId,sourceId:i.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 i=t;if(e==="previous"?i=a[r.branchNumber-2]:e==="next"&&(i=a[r.branchNumber]),!i)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(i)}unstable_getCopyText(){return Fr(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 Li(new We({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.content[${e}]`,messagePartSelector:{type:"index",index:e}}),getState:()=>Di(this.getState(),e),subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new Li(new We({path:E(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?Ve:Di(t,r)},subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new cc(new We({path:E(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?E(m({},r),{source:"message"}):Ve},subscribe:t=>this._core.subscribe(t)}))}},Vc=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}:{})},Wc=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:{}}},Jc=(e,t)=>{var r,n,a,i,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:(a=t.createdAt)!=null?a:new Date,parentId:(o=(s=t.parentId)!=null?s:(i=e.at(-1))==null?void 0:i.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}},Kc=(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})},Oi=class{constructor(e,t){C(this,"_threadBinding");C(this,"composer");C(this,"_eventSubscriptionSubjects",new Map);const r=new We({path:e.path,getState:()=>Kc(e.getState(),t.getState()),subscribe:n=>{const a=e.subscribe(n),i=t.subscribe(n);return()=>{a(),i()}}});this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>r.getState(),outerSubscribe:n=>e.outerSubscribe(n),subscribe:n=>e.subscribe(n)},this.composer=new fc(new zr({path:E(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(Jc(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(Wc(t))}unstable_resumeRun(e){return this._threadBinding.getState().resumeRun(Vc(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(E(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(E(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 qc(new We({path:e,getState:()=>{var d,c;const{message:r,parentId:n,index:a}=(d=t())!=null?d:{},{messages:i,speech:s}=this._threadBinding.getState();if(!r||n===void 0||a===void 0)return Ve;const l=this._threadBinding.getState().getBranches(r.id),u=r.metadata.submittedFeedback;return E(m({},r),{[Or]:r[Or],index:a,isLast:((c=i.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 _i({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}},Gc=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 Ve;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}:Ve},Yc=class{constructor(e,t=Oi){C(this,"_getState");C(this,"_mainThreadListItemRuntime");C(this,"main");this._core=e,this._runtimeFactory=t;const r=new Nn({path:{},getState:()=>Gc(e),subscribe:n=>e.subscribe(n)});this._getState=r.getState.bind(r),this._mainThreadListItemRuntime=new Dr(new We({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 zr({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 zr({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 Dr(new We({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 Dr(new We({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 Dr(new We({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>jr(this._core,e),subscribe:t=>this._core.subscribe(t)}),this._core)}},Xc=e=>e.startsWith("image/")?"image":e.startsWith("text/")?"document":"file",Qc=class{constructor(e){C(this,"accept","*");C(this,"uploadedUrls",new Map);this.cloud=e}add(t){return Er(this,arguments,function*({file:e}){const r=crypto.randomUUID(),n=Xc(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:i,publicUrl:s}=yield new qe(this.cloud.files.generatePresignedUploadUrl({filename:e.name}));yield new qe(fetch(i,{method:"PUT",body:e,headers:{"Content-Type":e.type},mode:"cors"})),this.uploadedUrls.set(r,s),a=E(m({},a),{status:{type:"requires-action",reason:"composer-send"}}),yield a}catch(i){a=E(m({},a),{status:{type:"incomplete",reason:"error"}}),yield a}})}remove(e){return P(this,null,function*(){this.uploadedUrls.delete(e.id)})}send(e){return P(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}],E(m({},e),{status:{type:"complete"},content:r})})}},Ln=g.createContext(null),Dn=({adapters:e,children:t})=>{const r=g.useContext(Ln);return p.jsx(Ln.Provider,{value:m(m({},r),e),children:t})},Zc=()=>g.useContext(Ln),ed=class extends si{constructor(t,r,{parentId:n,message:a}){var i;super();C(this,"_nonTextParts");C(this,"_previousText");C(this,"_parentId");C(this,"_sourceId");this.runtime=t,this.endEditCallback=r,this._parentId=n,this._sourceId=a.id,this._previousText=Fr(a),this.setText(this._previousText),this.setRole(a.role),this.setAttachments((i=a.attachments)!=null?i:[]),this._nonTextParts=a.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 P(this,null,function*(){Fr(t)!==this._previousText&&this.runtime.append(E(m({},t),{content:[...t.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId})),this.handleCancel()})}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},td=class{constructor(e){C(this,"_subscriptions",new Set);C(this,"_isInitialized",!1);C(this,"repository",new vi);C(this,"composer",new oi(this));C(this,"_editComposers",new Map);C(this,"_stopSpeaking");C(this,"speech");C(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 ed(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 i;const r=(i=this.adapters)==null?void 0:i.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 s=E(m({},n),{metadata:E(m({},n.metadata),{submittedFeedback:{type:t}})});this.repository.addOrUpdateMessage(a,s)}this._notifySubscribers()}speak(e){var i,s;const t=(i=this.adapters)==null?void 0:i.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(Fr(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(Mn.fromArray(e!=null?e:[]))}unstable_on(e,t){var n,a,i;if(e==="model-context-update")return(i=(a=(n=this._contextProvider).subscribe)==null?void 0:a.call(n,t))!=null?i:(()=>{});const r=this._eventSubscribers.get(e);return r?r.add(t):this._eventSubscribers.set(e,new Set([t])),()=>{this._eventSubscribers.get(e).delete(t)}}},rd=e=>{try{return JSON.parse(e),!0}catch(t){return!1}};function nd({state:e,getTools:t,onResult:r,setToolStatuses:n}){const a=g.useRef({}),i=g.useRef(new Map),s=g.useRef(new AbortController),o=g.useRef(0),l=g.useRef([]),[u]=g.useState(()=>{const[h,y]=xi(),S=Uc(t,()=>{var x,b;return(b=(x=s.current)==null?void 0:x.signal)!=null?b:new AbortController().signal},(x,b)=>new Promise((_,T)=>{const L=i.current.get(x);L&&L.reject(new Error("Human input request was superseded by a new request")),i.current.set(x,{resolve:_,reject:T}),n(z=>E(m({},z),{[x]:{type:"interrupt",payload:{type:"human",payload:b}}}))}),{onExecutionStart:x=>{o.current++,n(b=>E(m({},b),{[x]:{type:"executing"}}))},onExecutionEnd:x=>{o.current--,n(b=>{const _=m({},b);return delete _[x],_}),o.current===0&&(l.current.forEach(b=>b()),l.current=[])}});return h.pipeThrough(S).pipeThrough(new bi).pipeTo(new WritableStream({write(x){var b;if(x.type==="result"){if((b=a.current[x.meta.toolCallId])!=null&&b.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}))}}})),y}),d=g.useRef(new Set),c=g.useRef(!0);g.useEffect(()=>{const h=y=>{y.forEach(S=>{S.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 b=a.current[x.toolCallId];if(b||(b={argsText:"",hasResult:!1,argsComplete:!1,controller:u.addToolCallPart({toolName:x.toolName,toolCallId:x.toolCallId})},a.current[x.toolCallId]=b),x.argsText!==b.argsText)if(b.argsComplete)process.env.NODE_ENV!=="production"&&console.warn("argsText updated after controller was closed:",{previous:b.argsText,next:x.argsText});else{if(!x.argsText.startsWith(b.argsText))throw new Error(`Tool call argsText can only be appended, not updated: ${x.argsText} does not start with ${b.argsText}`);const _=x.argsText.slice(b.argsText.length);b.controller.argsText.append(_);const T=rd(x.argsText);T&&b.controller.argsText.close(),a.current[x.toolCallId]={argsText:x.argsText,hasResult:b.hasResult,argsComplete:T,controller:b.controller}}x.result!==void 0&&!b.hasResult&&(b.controller.setResponse(new ct({result:x.result,artifact:x.artifact,isError:x.isError})),b.controller.close(),a.current[x.toolCallId]={hasResult:!0,argsComplete:!0,argsText:b.argsText,controller:b.controller})}x.messages&&h(x.messages)}})})};h(e.messages),c.current&&(c.current=!1)},[e,u,r]);const f=()=>(i.current.forEach(({reject:h})=>{h(new Error("Tool execution aborted"))}),i.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,y)=>{const S=i.current.get(h);if(S)i.current.delete(h),n(x=>E(m({},x),{[h]:{type:"executing"}})),S.resolve(y);else throw new Error(`Tool call ${h} is not waiting for human input`)}}}var ad=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 id(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 i=!0;if(a.deps!==void 0&&r.deps!==void 0&&(i=a.deps.length!==r.deps.length||a.deps.some((s,o)=>!Object.is(s,r.deps[o]))),i){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 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}`);a.mounted=!0,a.cleanup=typeof s=="function"?s:void 0,a.deps=r.deps}catch(s){throw s}}})}function sd(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 ar=null;function od(e,t){e.currentIndex=0;const r=ar;ar=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{ar=r}}function On(){if(!ar)throw new Error("No resource fiber available");return ar}function Fi(e,t){const r=e[Bi];if(!r)throw new Error("ResourceElement.type is not a valid Resource");return r(t)}var Bi=Symbol("fnSymbol");function $r(e,t){return{resource:e,scheduleRerender:t,cells:[],currentIndex:0,renderContext:void 0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function Lt(e){e.isMounted=!1,sd(e)}function ir(e,t){const r={commitTasks:[],props:t,state:void 0};return od(e,()=>{e.renderContext=r;try{r.state=Fi(e.resource,t)}finally{e.renderContext=void 0}}),r}function Dt(e,t){e.isMounted=!0,e.isNeverMounted=!1,id(t,e)}var ld=globalThis.__ASSISTANT_UI_DISABLE_LAYOUT_EFFECT__===!0,zi=ld?g.useEffect:g.useLayoutEffect;function Fn(e){const[,t]=g.useState({}),r=g.useMemo(()=>$r(e.type,()=>t({})),[e.type,t]),n=ir(r,e.props);return zi(()=>()=>Lt(r),[]),zi(()=>{Dt(r,n)}),n.state}var Ot=e=>typeof e=="string"?{scope:e.split(".")[0],event:e}:{scope:e.scope,event:e.event},kt=(e,t,r)=>t===e,Ft,Bn=()=>{if(Ft)return Ft;const e=()=>({apis:new Map,nextId:0,listeners:new Set});if(typeof window=="undefined")return Ft=e(),Ft;const t=window.__ASSISTANT_UI_DEVTOOLS_HOOK__;if(t)return Ft=t,t;const r=e();return window.__ASSISTANT_UI_DEVTOOLS_HOOK__=r,Ft=r,r},ud=(Ye=class{static register(t){var o,l;const r=Bn();for(const u of r.apis.values())if(u.api===t)return()=>{};const n=r.nextId++,a={api:t,logs:[]},i=(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>Ye.MAX_EVENT_LOGS_PER_API&&(d.logs=d.logs.slice(-200)),Ye.notifyListeners(n))}),s=(l=t.subscribe)==null?void 0:l.call(t,()=>{Ye.notifyListeners(n)});return r.apis.set(n,a),Ye.notifyListeners(n),()=>{const u=Bn();u.apis.get(n)&&(i==null||i(),s==null||s(),u.apis.delete(n),Ye.notifyListeners(n))}}static notifyListeners(t){Bn().listeners.forEach(n=>n(t))}},C(Ye,"MAX_EVENT_LOGS_PER_API",200),Ye);function fe(e){const t=(r,n)=>m({type:t,props:r},(n==null?void 0:n.key)!==void 0&&{key:n.key});return t[Bi]=e,t}var cd=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 dd(e){const t=On(),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 i={type:"state",value:typeof e=="function"?e():e,set:s=>{const o=i.value,l=typeof s=="function"?s(o):s;Object.is(o,l)||(i.value=l,cd(t))}};t.cells[r]=i}const n=t.cells[r];if(n.type!=="state")throw new Error("Hook order changed between renders");return n}function tt(e){const t=dd(e);return[t.value,t.set]}function hd(){const e=On(),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 Ce(e,t){const r=On(),n=hd();r.renderContext.commitTasks.push({effect:e,deps:t,cellIndex:n})}function Bt(e){const[t]=tt(()=>({current:e}));return t}var fd=(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},le=(e,t)=>{const r=Bt();return r.current||(r.current={value:e(),deps:t}),fd(r.current.deps,t)||(r.current.value=e(),r.current.deps=t),r.current.value};function Ur(e,t){const[r,n]=tt({}),a=le(()=>$r(e.type,()=>n({})),[e.type]),i=t?le(()=>e.props,t):e.props,s=le(()=>ir(a,i),[a,i,r]);return Ce(()=>()=>Lt(a),[a]),Ce(()=>{Dt(a,s)},[a,s]),s.state}function Je(e){return Fi(e.type,e.props)}function Ri(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]=tt({}),a=le(()=>new Map(e.map(o=>[o.key,o])),[e]),[i]=tt(()=>new Map),s=le(()=>{const o=new Map,l=new Set;return a.forEach((u,d)=>{l.add(d);let c=i.get(d);(!c||c.resource!==u.type)&&(c&&Lt(c),c=$r(u.type,()=>n({})),i.set(d,c));const f=ir(c,u.props);o.set(d,f)}),i.forEach((u,d)=>{l.has(d)||(Lt(u),i.delete(d))}),o},[a,r]);return Ce(()=>{s.forEach((o,l)=>{const u=i.get(l);u&&Dt(u,o)})},[s,i]),Ce(()=>()=>{i.forEach(o=>{Lt(o)}),i.clear()},[i]),le(()=>e.map(o=>{var l;return(l=s.get(o.key))==null?void 0:l.state}),[e,s])}var zn=[],Rn=!1;function pd(){Rn=!1;const e=zn;zn=[];for(const t of e)try{t()}catch(r){console.error("Error in scheduled task:",r)}}function md(e){zn.push(e),Rn||(Rn=!0,queueMicrotask(pd))}var gd=(Pt=class{constructor(t){C(this,"_isDirty",!1);C(this,"_hasScheduledTask",!1);C(this,"_isFlushing",!1);this._task=t}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,!(this._hasScheduledTask||this._isFlushing)&&(this._hasScheduledTask=!0,md(()=>{this._hasScheduledTask=!1,this.flushSync()}))}flushSync(){if(this._isFlushing)return;this._isFlushing=!0;let t=0;try{for(;this._isDirty;){if(t++,t>Pt.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}}},C(Pt,"MAX_FLUSH_DEPTH",50),Pt),yd=fe(({element:e,onUpdateInput:t,onFlushSync:r,onDispose:n})=>{const[a,i]=tt(e.props),s=Je({type:e.type,props:a}),o=Bt(new Set).current,l=Bt(s);return Ce(()=>{s!==l.current&&(l.current=s,o.forEach(d=>d()))}),le(()=>({getState:()=>l.current,subscribe:d=>(o.add(d),()=>o.delete(d)),updateInput:d=>{t(),i(()=>d)},flushSync:r,dispose:n}),[])}),bd=(e,t=!1)=>{let r=!t;const n={element:e,onUpdateInput:()=>{r||(r=!0,Dt(i,s))},onFlushSync:()=>{a.flushSync()},onDispose:()=>Lt(i)},a=new gd(()=>{s=ir(i,n),r&&Dt(i,s)}),i=$r(yd,()=>a.markDirty());let s=ir(i,n);return r&&Dt(i,s),s.state},sr=Symbol("tap.Context"),ji=e=>({[sr]:e}),$i=(e,t,r)=>{const n=e[sr];e[sr]=t;try{return r()}finally{e[sr]=n}},Ui=e=>e[sr];const Hi=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},wd=(e=>e?Hi(e):Hi),xd=e=>e;function vd(e,t=xd){const r=g.useSyncExternalStore(e.subscribe,g.useCallback(()=>t(e.getState()),[e,t]),g.useCallback(()=>t(e.getInitialState()),[e,t]));return g.useDebugValue(r),r}const qi=e=>{const t=wd(e),r=n=>vd(t,n);return Object.assign(r,t),r},zt=(e=>e?qi(e):qi);function Vi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Wi(...e){return t=>{let r=!1;const n=e.map(a=>{const i=Vi(a,t);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let a=0;a<n.length;a++){const i=n[a];typeof i=="function"?i():Vi(e[a],null)}}}}function Hr(...e){return Y.useCallback(Wi(...e),e)}var Ji=fe(e=>{const t=le(()=>bd(e,!0),[e.type]);return Ce(()=>{t.updateInput(e.props)}),t}),Sd=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}},Ke=(e,t)=>{const r=Bt(e);Ce(()=>{r.current=e});const n=le(()=>new Proxy({},new Sd(()=>r.current)),[]),a=t==null?void 0:t.key,i=e.getState();return le(()=>({key:a,state:i,api:n}),[i,a])},dt=fe(e=>{const t=Bt(e.get);return Ce(()=>{t.current=e.get}),le(()=>Se({source:e.source,query:e.query,get:()=>t.current()}),[e.source,JSON.stringify(e.query)])}),kd=fe(e=>{const t=Ur(e.scopeElement);return le(()=>[e.fieldName,t],[e.fieldName,t])}),_d=fe(e=>{const o=e,{on:t,subscribe:r,flushSync:n}=o,a=W(o,["on","subscribe","flushSync"]),i=Bt({on:t,subscribe:r,flushSync:n});Ce(()=>{i.current={on:t,subscribe:r,flushSync:n}});const s=Ri(Object.entries(a).map(([l,u])=>kd({fieldName:l,scopeElement:u},{key:l})));return le(()=>{const l=Object.fromEntries(s),{on:u,subscribe:d,flushSync:c}=i.current;return u&&(l.on=(f,h)=>u(f,h)),d&&(l.subscribe=f=>d(f)),c&&(l.flushSync=()=>c()),l},[...s])}),Ki=ji(null),Td=(e,t)=>$i(Ki,e,t),Gi=()=>{const e=Ui(Ki);if(!e)throw new Error("Model context is not available in this context");return e},Cd=fe(({toolkit:e})=>{const[t,r]=tt(()=>({tools:{}})),n=Gi();Ce(()=>{if(!e)return;const i=[];for(const[l,u]of Object.entries(e))u.render&&i.push(a(l,u.render));const s=Object.entries(e).reduce((l,[u,d])=>{const h=d,{render:c}=h,f=W(h,["render"]);return l[u]=f,l},{}),o={getModelContext:()=>({tools:s})};return i.push(n.register(o)),()=>{i.forEach(l=>l())}},[e,n]);const a=(i,s)=>(r(o=>{var l;return E(m({},o),{tools:E(m({},o.tools),{[i]:[...(l=o.tools[i])!=null?l:[],s]})})}),()=>{r(o=>{var l,u;return E(m({},o),{tools:E(m({},o.tools),{[i]:(u=(l=o.tools[i])==null?void 0:l.filter(d=>d!==s))!=null?u:[]})})})});return Ke({getState:()=>t,setToolUI:a})}),Id=fe(()=>le(()=>{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),i=t.get("*");!a&&!i||queueMicrotask(()=>{if(a)for(const s of a)s(n);if(i)for(const s of i)s({event:r,payload:n})})}}},[])),Yi=ji(null),Ed=(e,t)=>$i(Yi,e,t),jn=()=>{const e=Ui(Yi);if(!e)throw new Error("Events context is not available");return e},Ad=fe(()=>{const[e]=tt(()=>({})),t=new Tn;return Ke({getState:()=>e,getModelContext:()=>t.getModelContext(),subscribe:r=>t.subscribe(r),register:r=>t.registerModelContextProvider(r)})}),Pd=fe(({threads:e,modelContext:t,tools:r})=>{const n=Je(Id()),{threads:a,tools:i,modelContext:s}=Ed(n,()=>{const l=Ur(t!=null?t:Ad(),[t]);return Td(l.api,()=>({modelContext:l,tools:Ur(r!=null?r:Cd({}),[r]),threads:Ur(e,[e])}))}),o=le(()=>({threads:a.state,tools:i.state,modelContext:s.state}),[a.state,i.state,s.state]);return Ke({getState:()=>o,threads:a.api,tools:i.api,modelContext:s.api,on:n.on})}),Md=e=>{const t=()=>e.getState().api.threads.item("main");return{threads:Se({source:"root",query:{},get:()=>e.getState().api.threads}),tools:Se({source:"root",query:{},get:()=>e.getState().api.tools}),modelContext:Se({source:"root",query:{},get:()=>e.getState().api.modelContext}),thread:Se({source:"threads",query:{type:"main"},get:()=>e.getState().api.threads.thread("main")}),threadListItem:Se({source:"threads",query:{type:"main"},get:()=>t()}),composer:Se({source:"thread",query:{},get:()=>e.getState().api.threads.thread("main").composer}),on(r,n){const{event:a,scope:i}=Ot(r);if(i==="*")return e.getState().api.on(a,n);if(kt("thread",i)||kt("thread-list-item",i)||kt("composer",i))return e.getState().api.on(a,s=>{s.threadId===t().getState().id&&n(s)});throw new Error(`Event scope is not available in this component: ${i}`)},subscribe:e.subscribe,flushSync:e.flushSync}},Nd=e=>{const t=qr(),r=Fn(Ji(Pd(e))),n=g.useMemo(()=>Md(r),[r]);return g.useMemo(()=>Qi(t,n),[t,n])},Se=e=>{const t=e.get;return t.source=e.source,t.query=e.query,t},ht=()=>()=>{},Xi=g.createContext({threads:Se({source:null,query:{},get:()=>{throw new Error("Threads is only available inside <AssistantProvider />")}}),tools:Se({source:null,query:{},get:()=>{throw new Error("Tools is only available inside <AssistantProvider />")}}),modelContext:Se({source:null,query:{},get:()=>{throw new Error("ModelContext is only available inside <AssistantProvider />")}}),threadListItem:Se({source:null,query:{},get:()=>{throw new Error("ThreadListItem is only available inside <AssistantProvider />")}}),thread:Se({source:null,query:{},get:()=>{throw new Error("Thread is only available inside <AssistantProvider />")}}),composer:Se({source:null,query:{},get:()=>{throw new Error("Composer is only available inside <AssistantProvider />")}}),message:Se({source:null,query:{},get:()=>{throw new Error("Message is only available inside <ThreadPrimitive.Messages />")}}),part:Se({source:null,query:{},get:()=>{throw new Error("Part is only available inside <MessagePrimitive.Parts />")}}),attachment:Se({source:null,query:{},get:()=>{throw new Error("Attachment is only available inside <MessagePrimitive.Attachments /> or <ComposerPrimitive.Attachments />")}}),subscribe:ht,flushSync:ht,on:e=>{const{scope:t}=Ot(e);throw new Error(`Event scope is not available in this component: ${t}`)}}),qr=()=>g.useContext(Xi),_t=e=>{const t=qr(),r=Fn(_d(e));return g.useMemo(()=>Qi(t,r),[t,r])},Ld=e=>Nd(e);function de(e){return e?Ld(e):qr()}var Dd=(e,t)=>e===ht?t:t===ht?e:(...r)=>{e(...r),t(...r)},Od=(e,t)=>e===ht?t:t===ht?e:(...r)=>{const n=e(...r),a=t(...r);return()=>{n(),a()}},Qi=(e,t)=>{const r=t.subscribe,n=t.flushSync;return E(m(m({},e),t),{subscribe:Od(e.subscribe,r!=null?r:ht),flushSync:Dd(e.flushSync,n!=null?n:ht)})},ft=({api:e,children:t,devToolsVisible:r=!0})=>(g.useEffect(()=>{if(!(!r||!e.subscribe))return ud.register(e)},[e,r]),p.jsx(Xi.Provider,{value:e,children:t})),Zi=(xu=class{constructor(e){Yt(this,$e);Xt(this,$e,e)}get threads(){return Be(this,$e).threads().getState()}get tools(){return Be(this,$e).tools().getState()}get threadListItem(){return Be(this,$e).threadListItem().getState()}get thread(){return Be(this,$e).thread().getState()}get composer(){return Be(this,$e).composer().getState()}get message(){return Be(this,$e).message().getState()}get part(){return Be(this,$e).part().getState()}get attachment(){return Be(this,$e).attachment().getState()}},$e=new WeakMap,xu),se=e=>{const t=de(),r=g.useMemo(()=>new Zi(t),[t]),n=g.useSyncExternalStore(t.subscribe,()=>e(r),()=>e(r));if(g.useDebugValue(n),n instanceof Zi)throw new Error("You tried to return the entire AssistantState. This is not supported due to technical limitations.");return n},$n=(e,t)=>{const r=de(),n=g.useRef(t);g.useEffect(()=>{n.current=t});const{scope:a,event:i}=Ot(e);g.useEffect(()=>r.on({scope:a,event:i},s=>n.current(s)),[r,a,i])};function Fd(e,t){function r(n){const a=g.useContext(e);if(!(n!=null&&n.optional)&&!a)throw new Error(`This component must be used within ${t}.`);return a}return r}function es(e,t){function r(a){const i=e(a);return i?i[t]:null}function n(a){let i=!1,s;typeof a=="function"?s=a:a&&typeof a=="object"&&(i=!!a.optional,s=a.selector);const o=r({optional:i});return o?s?o(s):o():null}return{[t]:n,[`${t}Store`]:r}}var ts=g.createContext(null),Bd=Fd(ts,"ThreadPrimitive.Viewport"),{useThreadViewport:Vr,useThreadViewportStore:Un}=es(Bd,"useThreadViewport"),zd=e=>{var r;const t=e;t.__isBound||((r=t.__internal_bindMethods)==null||r.call(t),t.__isBound=!0)};function Rd(e,t=jd){zd(e);const r=g.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getState()));return g.useDebugValue(r),r}var jd=e=>e;function rs(e){function t(r){let n=!1,a;typeof r=="function"?a=r:r&&(n=!!r.optional,a=r.selector);const i=e({optional:n});return i?Rd(i,a):null}return t}function ns(e){const t=de(),r=se(()=>{var n,a,i;return t.thread.source&&(i=(a=(n=t.thread()).__internal_getRuntime)==null?void 0:a.call(n))!=null?i:null});if(!r&&!(e!=null&&e.optional))throw new Error("ThreadRuntime is not available");return r}var $d=rs(ns);function Ud(e){const t=de(),r=se(()=>{var n,a,i;return t.threadListItem.source&&(i=(a=(n=t.threadListItem()).__internal_getRuntime)==null?void 0:a.call(n))!=null?i:null});if(!r&&!(e!=null&&e.optional))throw new Error("ThreadListItemRuntime is not available");return r}var as=rs(Ud),Tt=e=>{const[,t]=tt(e.getState);return Ce(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},Hd=fe(({runtime:e})=>{const t=Tt(e),r=jn();return Ce(()=>{const n=[],a=["switched-to","switched-away"];for(const i of a){const s=e.unstable_on(i,()=>{r.emit(`thread-list-item.${i}`,{threadId:e.getState().id})});n.push(s)}return()=>{for(const i of n)i()}},[e,r]),Ke({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})}),or=e=>{const t=Ri(e);return{state:t.map(r=>r.state),api:r=>{var a,i;const n="index"in r?(a=t[r.index])==null?void 0:a.api:(i=t.find(s=>s.key===r.key))==null?void 0:i.api;if(!n)throw new Error(`tapLookupResources: Resource not found for lookup: ${JSON.stringify(r)}`);return n}}},is=fe(({runtime:e})=>{const t=Tt(e);return Ke({getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e},{key:t.id})}),qd=fe(({runtime:e,index:t})=>{const r=le(()=>e.getAttachmentByIndex(t),[e,t]);return Je(is({runtime:r}))}),ss=fe(({threadIdRef:e,messageIdRef:t,runtime:r})=>{var o;const n=Tt(r),a=jn();Ce(()=>{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 i=or(n.attachments.map((l,u)=>qd({runtime:r,index:u},{key:u}))),s=le(()=>{var l;return{text:n.text,role:n.role,attachments:i.state,runConfig:n.runConfig,isEditing:n.isEditing,canCancel:n.canCancel,attachmentAccept:n.attachmentAccept,isEmpty:n.isEmpty,type:(l=n.type)!=null?l:"thread"}},[n,i.state]);return Ke({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?i.api({key:l.id}):i.api(l),__internal_getRuntime:()=>r})}),Vd=fe(({runtime:e})=>{const t=Tt(e);return Ke({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})}),Wd=fe(({runtime:e,index:t})=>{const r=le(()=>e.getAttachmentByIndex(t),[e,t]);return Je(is({runtime:r}))}),Jd=fe(({runtime:e,index:t})=>{const r=le(()=>e.getMessagePartByIndex(t),[e,t]);return Je(Vd({runtime:r}))}),Kd=fe(({runtime:e,threadIdRef:t})=>{var f,h;const r=Tt(e),[n,a]=tt(!1),[i,s]=tt(!1),o=le(()=>({get current(){return e.getState().id}}),[e]),l=Je(ss({runtime:e.composer,threadIdRef:t,messageIdRef:o})),u=or(r.content.map((y,S)=>Jd({runtime:e,index:S},{key:S}))),d=or((h=(f=r.attachments)==null?void 0:f.map((y,S)=>Wd({runtime:e,index:S},{key:S})))!=null?h:[]),c=le(()=>E(m({},r),{parts:u.state,composer:l.state,isCopied:n,isHovering:i}),[r,u.state,l.state,n,i]);return Ke({getState:()=>c,composer:l.api,reload:y=>e.reload(y),speak:()=>e.speak(),stopSpeaking:()=>e.stopSpeaking(),submitFeedback:y=>e.submitFeedback(y),switchToBranch:y=>e.switchToBranch(y),getCopyText:()=>e.unstable_getCopyText(),part:y=>"index"in y?u.api({index:y.index}):u.api({key:`toolCallId-${y.toolCallId}`}),attachment:y=>"id"in y?d.api({key:y.id}):d.api(y),setIsCopied:a,setIsHovering:s,__internal_getRuntime:()=>e},{key:r.id})}),Gd=fe(({runtime:e,id:t,threadIdRef:r})=>{const n=le(()=>e.getMessageById(t),[e,t]);return Je(Kd({runtime:n,threadIdRef:r}))}),Yd=fe(({runtime:e})=>{const t=Tt(e),r=jn();Ce(()=>{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=le(()=>({get current(){return e.getState().threadId}}),[e]),a=Je(ss({runtime:e.composer,threadIdRef:n})),i=or(t.messages.map(o=>Gd({runtime:e,id:o.id,threadIdRef:n},{key:o.id}))),s=le(()=>({isEmpty:i.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:i.state}),[t,i,a.state]);return Ke({getState:()=>s,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:()=>P(null,null,function*(){throw new Error("startVoice is not supported in this runtime")}),stopVoice:()=>P(null,null,function*(){throw new Error("stopVoice is not supported in this runtime")}),message:o=>"id"in o?i.api({key:o.id}):i.api(o),__internal_getRuntime:()=>e})}),Xd=fe(({runtime:e,id:t})=>{const r=le(()=>e.getItemById(t),[e,t]);return Je(Hd({runtime:r}))}),Qd=fe(({runtime:e,__internal_assistantRuntime:t})=>{const r=Tt(e),n=Je(Yd({runtime:e.main})),a=or(Object.keys(r.threadItems).map(s=>Xd({runtime:e,id:s},{key:s}))),i=le(()=>{var s;return{mainThreadId:r.mainThreadId,newThreadId:(s=r.newThread)!=null?s:null,isLoading:r.isLoading,threadIds:r.threads,archivedThreadIds:r.archivedThreads,threadItems:a.state,main:n.state}},[r,a.state,n.state]);return Ke({getState:()=>i,thread:()=>n.api,item:s=>{if(s==="main")return a.api({key:i.mainThreadId});if("id"in s)return a.api({key:s.id});const{index:o,archived:l=!1}=s,u=l?i.archivedThreadIds[o]:i.threadIds[o];return a.api({key:u})},switchToThread:s=>{e.switchToThread(s)},switchToNewThread:()=>{e.switchToNewThread()},__internal_getAssistantRuntime:()=>t})}),Zd=fe(e=>{const t=Gi();return Ce(()=>e.registerModelContextProvider(t),[e,t]),Je(Qd({runtime:e.threads,__internal_assistantRuntime:e}))}),Hn=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()}}}}},eh=(e={})=>{const t=new Set,r=Hn(s=>{i.setState({height:E(m({},i.getState().height),{viewport:s})})}),n=Hn(s=>{i.setState({height:E(m({},i.getState().height),{inset:s})})}),a=Hn(s=>{i.setState({height:E(m({},i.getState().height),{userMessage:s})})}),i=zt(()=>{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:a.register}});return i},lr=e=>e,th=e=>{const t=Un({optional:!0}),[r]=g.useState(()=>eh(e));return g.useEffect(()=>t==null?void 0:t.getState().onScrollToBottom(()=>{r.getState().scrollToBottom()}),[t,r]),g.useEffect(()=>{if(t)return r.subscribe(n=>{t.getState().isAtBottom!==n.isAtBottom&&lr(t).setState({isAtBottom:n.isAtBottom})})},[r,t]),g.useEffect(()=>{var i;const n={turnAnchor:(i=e.turnAnchor)!=null?i:"bottom"};r.getState().turnAnchor!==n.turnAnchor&&lr(r).setState(n)},[r,e.turnAnchor]),r},os=({children:e,options:t={}})=>{const r=th(t),[n]=g.useState(()=>({useThreadViewport:r}));return p.jsx(ts.Provider,{value:n,children:e})},rh=e=>{var t;return(t=e._core)==null?void 0:t.RenderComponent},nh=({children:e,runtime:t})=>{const r=de({threads:Zd(t)}),n=rh(t);return p.jsxs(ft,{api:r,children:[n&&p.jsx(n,{}),p.jsx(os,{children:e})]})},ls=g.memo(nh),ah=({index:e,archived:t,children:r})=>{const n=de(),a=_t({threadListItem:dt({source:"threads",query:{type:"index",index:e,archived:t},get:()=>n.threads().item({index:e,archived:t})}),on(i,s){const o=()=>n.threads().item({index:e,archived:t}),{event:l,scope:u}=Ot(i);return kt("thread-list-item",u)?n.on({scope:"*",event:l},d=>{d.threadId===o().getState().id&&s(d)}):n.on(i,s)}});return p.jsx(ft,{api:a,children:r})},ih=({id:e,children:t})=>{const r=de(),n=_t({threadListItem:dt({source:"threads",query:{type:"id",id:e},get:()=>r.threads().item({id:e})}),on(a,i){const s=()=>r.threads().item({id:e}),{event:o,scope:l}=Ot(a);return kt("thread-list-item",l)?r.on({scope:"*",event:o},u=>{u.threadId===s().getState().id&&i(u)}):r.on(a,i)}});return p.jsx(ft,{api:n,children:t})},sh=({index:e,children:t})=>{const r=de(),n=_t({message:dt({source:"thread",query:{type:"index",index:e},get:()=>r.thread().message({index:e})}),composer:dt({source:"message",query:{},get:()=>r.thread().message({index:e}).composer}),on(a,i){const s=()=>r.thread().message({index:e}),{event:o,scope:l}=Ot(a);return!kt("composer",l)&&!kt("message",l)?r.on(a,i):r.on({scope:"thread",event:o},u=>{u.messageId===s().getState().id&&i(u)})}});return p.jsx(ft,{api:n,children:t})},oh=({index:e,children:t})=>{const r=de(),n=_t({part:dt({source:"message",query:{type:"index",index:e},get:()=>r.message().part({index:e})})});return p.jsx(ft,{api:n,children:t})},lh=({index:e,children:t})=>{const r=de(),n=_t({attachment:dt({source:"message",query:{type:"index",index:e},get:()=>r.message().attachment({index:e})})});return p.jsx(ft,{api:n,children:t})},uh=({index:e,children:t})=>{const r=de(),n=_t({attachment:dt({source:"composer",query:{type:"index",index:e},get:()=>r.composer().attachment({index:e})})});return p.jsx(ft,{api:n,children:t})},ch=fe(({text:e,isRunning:t})=>{const r=le(()=>({type:"text",text:e,status:t?{type:"running"}:{type:"complete"}}),[e,t]);return Ke({getState:()=>r,addToolResult:()=>{throw new Error("Not supported")},resumeToolCall:()=>{throw new Error("Not supported")}})}),dh=({text:e,isRunning:t=!1,children:r})=>{const n=Fn(Ji(ch({text:e,isRunning:t}))),a=_t({part:dt({source:"root",query:{},get:()=>n.getState().api}),subscribe:n.subscribe,flushSync:n.flushSync});return p.jsx(ft,{api:a,children:r})},us=(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))},qn=class extends Error{constructor(t,r){super(r);C(this,"name","AbortError");C(this,"detach");this.detach=t}},hh=class extends td{constructor(t,r){super(t);C(this,"capabilities",{switchToBranch:!0,switchBranchDuringRun:!0,edit:!0,reload:!0,cancel:!0,unstable_copy:!0,speech:!1,attachments:!1,feedback:!1});C(this,"abortController",null);C(this,"isDisabled",!1);C(this,"_isLoading",!1);C(this,"_suggestions",[]);C(this,"_suggestionsController",null);C(this,"_options");C(this,"_lastRunConfig",{});C(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 a=((o=t.adapters)==null?void 0:o.attachments)!==void 0;this.capabilities.attachments!==a&&(this.capabilities.attachments=a,r=!0);const i=((l=t.adapters)==null?void 0:l.feedback)!==void 0;this.capabilities.feedback!==i&&(this.capabilities.feedback=i,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 s,o;if(!a)return;this.repository.import(a),this._notifySubscribers();const i=(o=(s=this.adapters.history)==null?void 0:s.resume)==null?void 0:o.bind(this.adapters.history);a.unstable_resume&&i&&this.startRun({parentId:this.repository.headId,sourceId:this.repository.headId,runConfig:this._lastRunConfig},i)}).finally(()=>{this._isLoading=!1,this._notifySubscribers()}),this._loadPromise}append(t){return P(this,null,function*(){var a,i,s;this.ensureInitialized();const r=rr(t,vt(),{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})),((i=t.startRun)!=null?i: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 a=n,{stream:t}=a,r=W(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,i){return P(this,arguments,function*({parentId:t,runConfig:r},n){var u,d,c;this.ensureInitialized();let o={id:vt(),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(us(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=Mt(x),h,y,S;h=!(y=yield f.next()).done;h=!1){const b=y.value;if(l.aborted)break;this._suggestions=b,this._notifySubscribers()}}catch(y){S=[y]}finally{try{h&&(y=f.return)&&(yield y.call(f))}finally{if(S)throw S[0]}}else{const b=yield x;if(l.aborted)return;this._suggestions=b,this._notifySubscribers()}}})}performRoundtrip(t,r,n,a){return P(this,null,function*(){var y,S,x,b,_,T,L,z,I,D;const i=t?this.repository.getMessages(t):[];(y=this.abortController)==null||y.abort(),this.abortController=new AbortController;const s=r.content,o=(S=r.metadata)==null?void 0:S.unstable_annotations,l=(x=r.metadata)==null?void 0:x.unstable_data,u=(b=r.metadata)==null?void 0:b.steps,d=(_=r.metadata)==null?void 0:_.custom,c=M=>{var Z,w,ae,xe,v,ve;const H=(Z=M.metadata)==null?void 0:Z.steps,R=H?[...u!=null?u:[],...H]:void 0,F=(w=M.metadata)==null?void 0:w.unstable_annotations,j=(ae=M.metadata)==null?void 0:ae.unstable_data,J=F?[...o!=null?o:[],...F]:void 0,re=j?[...l!=null?l:[],...j]:void 0;r=m(E(m(m({},r),M.content?{content:[...s,...(xe=M.content)!=null?xe:[]]}:void 0),{status:(v=M.status)!=null?v:r.status}),M.metadata?{metadata:m(m(m(m(m(m({},r.metadata),M.metadata.unstable_state?{unstable_state:M.metadata.unstable_state}:void 0),J?{unstable_annotations:J}:void 0),re?{unstable_data:re}:void 0),R?{steps:R}:void 0),(ve=M.metadata)!=null&&ve.custom?{custom:m(m({},d!=null?d:{}),M.metadata.custom)}:void 0)}:void 0),this.repository.addOrUpdateMessage(t,r),this._notifySubscribers()},f=(T=this._options.maxSteps)!=null?T:2;if(((I=(z=(L=r.metadata)==null?void 0:L.steps)==null?void 0:z.length)!=null?I: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 M=this.getModelContext();a=a!=null?a:this.adapters.chatModel.run.bind(this.adapters.chatModel);const H=this.abortController.signal,R=a({messages:i,runConfig:this._lastRunConfig,abortSignal:H,context:M,config:M,unstable_assistantMessageId:r.id,unstable_getMessage(){return r}});if(Symbol.asyncIterator in R)try{for(var q=Mt(R),B,U,k;B=!(U=yield q.next()).done;B=!1){const F=U.value;if(H.aborted){c({status:{type:"incomplete",reason:"cancelled"}});break}c(F)}}catch(U){k=[U]}finally{try{B&&(U=q.return)&&(yield U.call(q))}finally{if(k)throw k[0]}}else c(yield R);r.status.type==="running"&&c({status:{type:"complete",reason:"unknown"}})}catch(M){if(M instanceof qn)c({status:{type:"incomplete",reason:"cancelled"}});else throw c({status:{type:"incomplete",reason:"error",error:M instanceof Error?M.message:`[${typeof M}] ${new String(M).toString()}`}}),M}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 qn(!0);(r=this.abortController)==null||r.abort(t),this.abortController=null}cancelRun(){var r;const t=new qn(!1);(r=this.abortController)==null||r.abort(t),this.abortController=null}addToolResult({messageId:t,toolCallId:r,result:n,isError:a,artifact:i}){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),E(m({},f),{result:n,artifact:i,isError:a})));if(!d)throw new Error("Tried to add tool result to non-existing tool call");l=E(m({},l),{content:c}),this.repository.addOrUpdateMessage(o,l),u&&us(l,this._options.unstable_humanToolNames)&&this.performRoundtrip(o,l,this._lastRunConfig)}resumeToolCall(t){throw new Error("Local runtime does not support resuming tool calls.")}},cs=Object.freeze([]),Vn="__DEFAULT_ID__",fh=Object.freeze({[Vn]:{id:Vn,remoteId:void 0,externalId:void 0,status:"regular",title:void 0}}),ph=class extends er{constructor(t){super();C(this,"_mainThread");this._mainThread=t()}get isLoading(){return!1}getMainThreadRuntimeCore(){return this._mainThread}get newThreadId(){throw new Error("Method not implemented.")}get threadIds(){throw cs}get archivedThreadIds(){throw cs}get mainThreadId(){return Vn}get threadData(){return fh}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 P(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.")}},mh=class extends Cn{constructor(t,r){super();C(this,"threads");C(this,"Provider");C(this,"_options");this._options=t,this.threads=new ph(()=>new hh(this._contextProvider,this._options)),r&&this.threads.getMainThreadRuntimeCore().import(Mn.fromArray(r))}},ds=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),s=JSON.parse(a).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}`)}},hs=(vu=class{constructor(e){C(this,"strategy","jwt");C(this,"cachedToken",null);C(this,"tokenExpiry",null);Yt(this,kr);Xt(this,kr,e)}getAuthHeaders(){return P(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 Be(this,kr).call(this);return t?(this.cachedToken=t,this.tokenExpiry=ds(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=ds(n)}},kr=new WeakMap,vu),gh=(Su=class{constructor(e,t,r){C(this,"strategy","api-key");Yt(this,_r);Yt(this,Tr);Yt(this,Cr);Xt(this,_r,e),Xt(this,Tr,t),Xt(this,Cr,r)}getAuthHeaders(){return P(this,null,function*(){return{Authorization:`Bearer ${Be(this,_r)}`,"Aui-User-Id":Be(this,Tr),"Aui-Workspace-Id":Be(this,Cr)}})}readAuthHeaders(){}},_r=new WeakMap,Tr=new WeakMap,Cr=new WeakMap,Su),Wr="aui:refresh_token",yh=class{constructor(e){C(this,"strategy","anon");C(this,"baseUrl");C(this,"jwtStrategy");this.baseUrl=e,this.jwtStrategy=new hs(()=>P(this,null,function*(){const t=Date.now(),r=localStorage.getItem(Wr),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(Wr,JSON.stringify(f)),c}}else localStorage.removeItem(Wr);const a=yield fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:"POST"});if(!a.ok)return null;const i=yield a.json(),{access_token:s,refresh_token:o}=i;return!s||!o?null:(localStorage.setItem(Wr,JSON.stringify(o)),s)}))}getAuthHeaders(){return P(this,null,function*(){return this.jwtStrategy.getAuthHeaders()})}readAuthHeaders(e){this.jwtStrategy.readAuthHeaders(e)}},bh=class extends Error{constructor(e){super(e),this.name="APIError"}},wh=class{constructor(e){C(this,"_auth");C(this,"_baseUrl");if("authToken"in e)this._baseUrl=e.baseUrl,this._auth=new hs(e.authToken);else if("apiKey"in e)this._baseUrl="https://backend.assistant-api.com",this._auth=new gh(e.apiKey,e.userId,e.workspaceId);else if("anonymous"in e)this._baseUrl=e.baseUrl,this._auth=new yh(e.baseUrl);else throw new Error("Invalid configuration: Must provide authToken, apiKey, or anonymous configuration")}initializeAuth(){return P(this,null,function*(){return!!this._auth.getAuthHeaders()})}makeRawRequest(r){return P(this,arguments,function*(e,t={}){var l;const n=yield this._auth.getAuthHeaders();if(!n)throw new Error("Authorization failed");const a=E(m(m({},n),t.headers),{"Content-Type":"application/json"}),i=new URLSearchParams;if(t.query)for(const[u,d]of Object.entries(t.query))d!==!1&&(d===!0?i.set(u,"true"):i.set(u,d.toString()));const s=new URL(`${this._baseUrl}/v1${e}`);s.search=i.toString();const o=yield fetch(s,{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 bh(d.message)}catch(d){throw new Error(`Request failed with status ${o.status}, ${u}`)}}return o})}makeRequest(r){return P(this,arguments,function*(e,t={}){return(yield this.makeRawRequest(e,t)).json()})}},xh=class{constructor(e){this.cloud=e}create(){return P(this,null,function*(){return this.cloud.makeRequest("/auth/tokens",{method:"POST"})})}},vh=class{constructor(e){this.cloud=e}__internal_getAssistantOptions(e){return{api:`${this.cloud._baseUrl}/v1/runs/stream`,headers:()=>P(this,null,function*(){const t=yield this.cloud._auth.getAuthHeaders();if(!t)throw new Error("Authorization failed");return E(m({},t),{Accept:"text/plain"})}),body:{assistant_id:e,response_format:"vercel-ai-data-stream/v1",thread_id:"unstable_todo"}}}stream(e){return P(this,null,function*(){const t=yield this.cloud.makeRawRequest("/runs/stream",{method:"POST",headers:{Accept:"text/plain"},body:e});return An.fromResponse(t,new Mc)})}},Sh=class{constructor(e){this.cloud=e}list(e,t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{query:t})})}create(e,t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{method:"POST",body:t})})}},kh=class{constructor(e){C(this,"messages");this.cloud=e,this.messages=new Sh(e)}list(e){return P(this,null,function*(){return this.cloud.makeRequest("/threads",{query:e})})}get(e){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`)})}create(e){return P(this,null,function*(){return this.cloud.makeRequest("/threads",{method:"POST",body:e})})}update(e,t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"PUT",body:t})})}delete(e){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"DELETE"})})}},_h=class{constructor(e){this.cloud=e}pdfToImages(e){return P(this,null,function*(){return this.cloud.makeRequest("/files/pdf-to-images",{method:"POST",body:e})})}generatePresignedUploadUrl(e){return P(this,null,function*(){return this.cloud.makeRequest("/files/attachments/generate-presigned-upload-url",{method:"POST",body:e})})}},Th=class{constructor(e){C(this,"threads");C(this,"auth");C(this,"runs");C(this,"files");const t=new wh(e);this.threads=new kh(t),this.auth={tokens:new xh(t)},this.runs=new vh(t),this.files=new _h(t)}};function Wn(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=>Wn(r,t+1)):typeof e=="object"?Object.entries(e).every(([r,n])=>typeof r=="string"&&Wn(n,t+1)):!1}var Ch=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 Wn(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)},Ih=e=>{const t=e.content,r=rr(m({id:e.id,createdAt:e.created_at},t),e.id,{type:"complete",reason:"unknown"});return{parentId:e.parent_id,message:r}},Jn=new WeakMap,Eh=class{constructor(e,t){this.parent=e,this.formatAdapter=t}append(e){return P(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 P(this,null,function*(){return this.parent._loadWithFormat(this.formatAdapter.format,e=>this.formatAdapter.decode(e))})}},Ah=class{constructor(e,t){this.cloudRef=e,this.store=t}get _getIdForLocalId(){return Jn.has(this.store.threadListItem())||Jn.set(this.store.threadListItem(),{}),Jn.get(this.store.threadListItem())}withFormat(e){return new Eh(this,e)}append(r){return P(this,arguments,function*({parentId:e,message:t}){var i;const{remoteId:n}=yield this.store.threadListItem().initialize(),a=this.cloudRef.current.threads.messages.create(n,{parent_id:e?(i=yield this._getIdForLocalId[e])!=null?i:e:null,format:"aui/v0",content:Ch(t)}).then(({message_id:s})=>(this._getIdForLocalId[t.id]=s,s));return this._getIdForLocalId[t.id]=a,a.then(()=>{})})}load(){return P(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(Ih).reverse()}})}_appendWithFormat(e,t,r,n){return P(this,null,function*(){var s;const{remoteId:a}=yield this.store.threadListItem().initialize(),i=this.cloudRef.current.threads.messages.create(a,{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]=i,i.then(()=>{})})}_loadWithFormat(e,t){return P(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()}})}},Ph=e=>{const t=de(),[r]=g.useState(()=>new Ah(e,t));return r},fs=typeof process!="undefined"&&((ku=process==null?void 0:process.env)==null?void 0:ku.NEXT_PUBLIC_ASSISTANT_BASE_URL),Kn=fs?new Th({baseUrl:fs,anonymous:!0}):void 0,Mh=e=>{var a;const t=g.useRef(e);g.useEffect(()=>{t.current=e},[e]);const r=g.useCallback(function({children:s}){var c;const o=Ph({get current(){var f;return(f=t.current.cloud)!=null?f:Kn}}),l=(c=t.current.cloud)!=null?c:Kn,u=g.useMemo(()=>new Qc(l),[l]),d=g.useMemo(()=>({history:o,attachments:u}),[o,u]);return p.jsx(Dn,{adapters:d,children:s})},[]),n=(a=e.cloud)!=null?a:Kn;return n?{list:()=>P(null,null,function*(){const{threads:i}=yield n.threads.list();return{threads:i.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:()=>P(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:(i,s)=>P(null,null,function*(){return n.threads.update(i,{title:s})}),archive:i=>P(null,null,function*(){return n.threads.update(i,{is_archived:!0})}),unarchive:i=>P(null,null,function*(){return n.threads.update(i,{is_archived:!1})}),delete:i=>P(null,null,function*(){var s;return yield(s=e.delete)==null?void 0:s.call(e,i),n.threads.delete(i)}),generateTitle:(i,s)=>P(null,null,function*(){return n.runs.stream({thread_id:i,assistant_id:"system/thread_title",messages:s})}),fetch:i=>P(null,null,function*(){var o;const s=yield n.threads.get(i);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 ad},Nh=(e,n)=>{var a=n,{initialMessages:t}=a,r=W(a,["initialMessages"]);var u;const d=(u=Zc())!=null?u:{},{modelContext:i}=d,s=W(d,["modelContext"]),o=g.useMemo(()=>E(m({},r),{adapters:E(m(m({},s),r.adapters),{chatModel:e})}),[e,r,s]),[l]=g.useState(()=>new mh(o,t));return g.useEffect(()=>()=>{l.threads.getMainThreadRuntimeCore().detach()},[l]),g.useEffect(()=>{l.threads.getMainThreadRuntimeCore().__internal_setOptions(o),l.threads.getMainThreadRuntimeCore().__internal_load()},[l,o]),g.useEffect(()=>{if(i)return l.registerModelContextProvider(i)},[i,l]),g.useMemo(()=>new Gn(l),[l])},ps=(e,n={})=>{var a=n,{cloud:t}=a,r=W(a,["cloud"]);const i=Mh({cloud:t});return ws({runtimeHook:function(){return Nh(e,r)},adapter:i,allowNesting:!0})},Gn=class{constructor(e){C(this,"threads");C(this,"_thread");this._core=e,this.threads=new Yc(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(Mn.fromArray(e!=null?e:[]))}},Lh=e=>{const o=e,{cloud:t,initialMessages:r,maxSteps:n,adapters:a,unstable_humanToolNames:i}=o,s=W(o,["cloud","initialMessages","maxSteps","adapters","unstable_humanToolNames"]);return{localRuntimeOptions:{cloud:t,initialMessages:r,maxSteps:n,adapters:a,unstable_humanToolNames:i},otherOptions:s}};function Ct(e){const t=Y.useRef(e);return Y.useEffect(()=>{t.current=e}),Y.useMemo(()=>(...r)=>{var n;return(n=t.current)==null?void 0:n.call(t,...r)},[])}var ms=g.createContext(null),Dh=e=>({useSmoothStatus:zt(()=>e)}),Oh=({children:e})=>{const t=gs({optional:!0}),r=de(),[n]=g.useState(()=>Dh(r.part().getState().status));return t?e:p.jsx(ms.Provider,{value:n,children:e})},Fh=e=>{const t=g.forwardRef((r,n)=>p.jsx(Oh,{children:p.jsx(e,E(m({},r),{ref:n}))}));return t.displayName=e.displayName,t};function gs(e){const t=g.useContext(ms);if(!(e!=null&&e.optional)&&!t)throw new Error("This component must be used within a SmoothContextProvider.");return t}var{useSmoothStatus:Bh,useSmoothStatusStore:zh}=es(gs,"useSmoothStatus"),Rh=class{constructor(e,t){C(this,"animationFrameId",null);C(this,"lastUpdateTime",Date.now());C(this,"targetText","");C(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 i=0;for(;r>=a&&i<n;)i++,r-=a;i!==n?this.animationFrameId=requestAnimationFrame(this.animate):this.animationFrameId=null,i!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+i),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)}},Yn=Object.freeze({type:"running"}),ys=(e,t=!1)=>{const{text:r}=e,n=se(({message:d})=>d.id),a=g.useRef(n),[i,s]=g.useState(r),o=zh({optional:!0}),l=Ct(d=>{if(s(d),o){const c=i!==d||e.status.type==="running"?Yn:e.status;lr(o).setState(c,!0)}});g.useEffect(()=>{if(o){const d=t&&(i!==r||e.status.type==="running")?Yn:e.status;lr(o).setState(d,!0)}},[o,t,r,i,e.status]);const[u]=g.useState(new Rh(r,l));return g.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]),g.useEffect(()=>()=>{u.stop()},[u]),g.useMemo(()=>t?{type:"text",text:i,status:r===i?e.status:Yn}:e,[t,i,e,r])};const jh=Object.freeze(Object.defineProperty({__proto__:null,AssistantRuntimeImpl:Gn,BaseAssistantRuntimeCore:Cn,CompositeContextProvider:Tn,DefaultThreadComposerRuntimeCore:oi,MessageRepository:vi,ThreadRuntimeImpl:Oi,fromThreadMessageLike:rr,generateId:vt,getAutoStatus:ui,splitLocalRuntimeOptions:Lh,useSmooth:ys,useSmoothStatus:Bh,useToolInvocations:nd,withSmoothContextProvider:Fh},Symbol.toStringTag,{value:"Module"}));var $h=class extends er{constructor(t){super();C(this,"useRuntimeHook");C(this,"instances",new Map);C(this,"useAliveThreadsKeysChanged",zt(()=>({})));C(this,"_InnerActiveThreadProvider",({threadId:t})=>{const{useRuntime:r}=this.useRuntimeHook(),n=r(),a=n.thread.__internal_threadBinding,i=g.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]),s=g.useRef(!1);s.current||i(),g.useEffect(()=>(s.current=!0,i(),a.outerSubscribe(i)),[a,i]);const o=de();return g.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});C(this,"_OuterActiveThreadProvider",g.memo(({threadId:t,provider:r})=>p.jsx(ih,{id:t,children:p.jsx(r,{children:p.jsx(this._InnerActiveThreadProvider,{threadId:t})})})));C(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=zt(()=>({useRuntime:t}))}startThreadRuntime(t){return this.instances.has(t)||(this.instances.set(t,{}),this.useAliveThreadsKeysChanged.setState({},!0)),new Promise((r,n)=>{const a=()=>{const s=this.instances.get(t);if(!s)i(),n(new Error("Thread was deleted before runtime was started"));else if(s.runtime)i(),r(s.runtime);else return},i=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)}},me=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."),Uh={getMessageById(){},getBranches(){return[]},switchToBranch(){throw me},append(){throw me},startRun(){throw me},resumeRun(){throw me},cancelRun(){throw me},addToolResult(){throw me},resumeToolCall(){throw me},speak(){throw me},stopSpeaking(){throw me},submitFeedback(){throw me},getModelContext(){return{}},unstable_loadExternalState(){throw me},composer:{attachments:[],attachmentAccept:"*",addAttachment(){return P(this,null,function*(){throw me})},removeAttachment(){return P(this,null,function*(){throw me})},isEditing:!0,canCancel:!1,isEmpty:!0,text:"",setText(){throw me},role:"user",setRole(){throw me},runConfig:{},setRunConfig(){throw me},reset(){return P(this,null,function*(){})},clearAttachments(){return P(this,null,function*(){})},send(){throw me},cancel(){},subscribe(){return()=>{}},unstable_on(){return()=>{}}},getEditComposer(){},beginEdit(){throw me},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 me},export(){return{messages:[]}},reset(){throw me},unstable_on(){return()=>{}}},bs=(e,t,r)=>r.reduce((n,a)=>{var i;return(i=a==null?void 0:a(n,t))!=null?i:n},e),Hh=class extends er{constructor(t){super();C(this,"_pendingTransforms",[]);C(this,"_baseValue");C(this,"_cachedValue");this._baseValue=t,this._cachedValue=t}_updateState(){this._cachedValue=this._pendingTransforms.reduce((t,r)=>bs(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 P(this,null,function*(){const r=t.execute(),n=E(m({},t),{task:r});try{this._pendingTransforms.push(n),this._updateState();const a=yield r;return this._baseValue=bs(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 yv(e){return e}var Jr=(e,t)=>{const r=e.threadIdMap[t];if(r!==void 0)return e.threadData[r]},Kr=(e,t,r)=>{const n=Jr(e,t);if(!n)return e;const{id:a,remoteId:i,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!==a);break;case"archived":o.archivedThreadIds=o.archivedThreadIds.filter(l=>l!==a);break;default:{const l=s;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!==i));break;default:{const l=r;throw new Error(`Unsupported state: ${l}`)}}return r!=="deleted"&&(o.threadData=E(m({},o.threadData),{[a]:E(m({},n),{status:r})})),o},qh=class extends er{constructor(t,r){super();C(this,"_options");C(this,"_hookManager");C(this,"_loadThreadsPromise");C(this,"_mainThreadId");C(this,"_state",new Hh({isLoading:!1,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}}));C(this,"useProvider");C(this,"initialize",t=>P(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=>Kr(r,t,"regular"),loading:(r,n)=>{const a=t;return E(m({},r),{threadData:E(m({},r.threadData),{[a]:E(m({},r.threadData[a]),{initializeTask:n})})})},then:(r,{remoteId:n,externalId:a})=>{const i=Jr(r,t);if(!i)return r;const s=t;return E(m({},r),{threadIdMap:E(m({},r.threadIdMap),{[n]:s}),threadData:E(m({},r.threadData),{[s]:E(m({},i),{initializeTask:Promise.resolve({remoteId:n,externalId:a}),remoteId:n,externalId:a})})})}})}));C(this,"generateTitle",t=>P(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 i=a.messages,s=yield this._options.adapter.generateTitle(n,i),o=Nc.fromAssistantStream(s);try{for(var u=Mt(o),d,c,f;d=!(c=yield u.next()).done;d=!1){const h=c.value;const y=(l=h.parts.filter(x=>x.type==="text")[0])==null?void 0:l.text,S=this._state.baseValue;this._state.update(E(m({},S),{threadData:E(m({},S.threadData),{[r.id]:E(m({},r),{title:y})})}))}}catch(c){f=[c]}finally{try{d&&(c=u.return)&&(yield c.call(u))}finally{if(f)throw f[0]}}}));C(this,"useBoundIds",zt(()=>[]));C(this,"__internal_RenderComponent",()=>{const t=g.useId();g.useEffect(()=>(this.useBoundIds.setState(i=>[...i,t],!0),()=>{this.useBoundIds.setState(i=>i.filter(s=>s!==t),!0)}),[t]);const r=this.useBoundIds(),{Provider:n}=this.useProvider(),a={modelContext:this.contextProvider};return(r.length===0||r[0]===t)&&p.jsx(Dn,{adapters:a,children:p.jsx(this._hookManager.__internal_RenderThreadRuntimes,{provider:n})})});this.contextProvider=r,this._state.subscribe(()=>this._notifySubscribers()),this._hookManager=new $h(t.runtimeHook),this.useProvider=zt(()=>{var n;return{Provider:(n=t.adapter.unstable_Provider)!=null?n:g.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=>E(m({},t),{isLoading:!0}),then:(t,r)=>{const n=[],a=[],i={},s={};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;i[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 E(m({},t),{threadIds:n,archivedThreadIds:a,threadIdMap:m(m({},t.threadIdMap),i),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:g.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||Uh}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 Jr(this._state.value,t)}switchToThread(t){return P(this,null,function*(){let r=this.getItemById(t);if(!r){const a=yield this._options.adapter.fetch(t),i=this._state.value,s=a.remoteId,o=E(m({},i.threadData),{[s]:{id:s,initializeTask:Promise.resolve({remoteId:a.remoteId,externalId:a.externalId}),remoteId:a.remoteId,externalId:a.externalId,status:a.status,title:a.title}}),l=E(m({},i.threadIdMap),{[a.remoteId]:s}),u=a.status==="regular"?[...i.threadIds,a.remoteId]:i.threadIds,d=a.status==="archived"?[...i.archivedThreadIds,a.remoteId]:i.archivedThreadIds;this._state.update(E(m({},i),{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 P(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_${vt()}`;while(t.threadIdMap[r]);const n=r;this._state.update(E(m({},t),{newThreadId:r,threadIdMap:E(m({},t.threadIdMap),{[r]:n}),threadData:E(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:()=>P(this,null,function*(){const{remoteId:a}=yield n.initializeTask;return this._options.adapter.rename(a,r)}),optimistic:a=>{const i=Jr(a,t);return i?E(m({},a),{threadData:E(m({},a.threadData),{[i.id]:E(m({},i),{title:r})})}):a}})}_ensureThreadIsNotMain(t){return P(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 P(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:()=>P(this,null,function*(){yield this._ensureThreadIsNotMain(r.id);const{remoteId:n}=yield r.initializeTask;return this._options.adapter.archive(n)}),optimistic:n=>Kr(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:()=>P(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=>Kr(n,r.id,"regular")})}delete(t){return P(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:()=>P(this,null,function*(){yield this._ensureThreadIsNotMain(r.id);const{remoteId:n}=yield r.initializeTask;return yield this._options.adapter.delete(n)}),optimistic:n=>Kr(n,r.id,"deleted")})})}detach(t){return P(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)})}},Vh=class extends Cn{constructor(t){super();C(this,"threads");this.threads=new qh(t,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}},Wh=e=>{const[t]=g.useState(()=>new Vh(e));return g.useEffect(()=>{t.threads.__internal_setOptions(e),t.threads.__internal_load()},[t,e]),g.useMemo(()=>new Gn(t),[t])},ws=e=>{if(qr().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 Wh(e)},Jh=Symbol.for("react.lazy"),Gr=Y[" use ".trim().toString()];function Kh(e){return typeof e=="object"&&e!==null&&"then"in e}function xs(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Jh&&"_payload"in e&&Kh(e._payload)}function vs(e){const t=Gh(e),r=Y.forwardRef((n,a)=>{let u=n,{children:i}=u,s=W(u,["children"]);xs(i)&&typeof Gr=="function"&&(i=Gr(i._payload));const o=Y.Children.toArray(i),l=o.find(Xh);if(l){const d=l.props.children,c=o.map(f=>f===l?Y.Children.count(d)>1?Y.Children.only(null):Y.isValidElement(d)?d.props.children:null:f);return p.jsx(t,E(m({},s),{ref:a,children:Y.isValidElement(d)?Y.cloneElement(d,void 0,c):null}))}return p.jsx(t,E(m({},s),{ref:a,children:i}))});return r.displayName=`${e}.Slot`,r}var Ss=vs("Slot");function Gh(e){const t=Y.forwardRef((r,n)=>{let s=r,{children:a}=s,i=W(s,["children"]);if(xs(a)&&typeof Gr=="function"&&(a=Gr(a._payload)),Y.isValidElement(a)){const o=Zh(a),l=Qh(i,a.props);return a.type!==Y.Fragment&&(l.ref=n?Wi(n,o):o),Y.cloneElement(a,l)}return Y.Children.count(a)>1?Y.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Yh=Symbol("radix.slottable");function Xh(e){return Y.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Yh}function Qh(e,t){const r=m({},t);for(const n in t){const a=e[n],i=t[n];/^on[A-Z]/.test(n)?a&&i?r[n]=(...o)=>{const l=i(...o);return a(...o),l}:a&&(r[n]=a):n==="style"?r[n]=m(m({},a),i):n==="className"&&(r[n]=[a,i].filter(Boolean).join(" "))}return m(m({},e),r)}function Zh(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 ef=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],at=ef.reduce((e,t)=>{const r=vs(`Primitive.${t}`),n=Y.forwardRef((a,i)=>{const u=a,{asChild:s}=u,o=W(u,["asChild"]),l=s?r:t;return typeof window!="undefined"&&(window[Symbol.for("radix-ui")]=!0),p.jsx(l,E(m({},o),{ref:i}))});return n.displayName=`Primitive.${t}`,E(m({},e),{[t]:n})},{});function Rt(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 ur=(e,t,r=[])=>{const n=g.forwardRef((a,i)=>{var u;const s={},o={};Object.keys(a).forEach(d=>{r.includes(d)?s[d]=a[d]:o[d]=a[d]});const l=(u=t(s))!=null?u:void 0;return p.jsx(at.button,E(m({type:"button"},o),{ref:i,disabled:o.disabled||!l,onClick:Rt(o.onClick,l)}))});return n.displayName=e,n};function tf(e,t=globalThis==null?void 0:globalThis.document){const r=Ct(e);Y.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 rf=()=>{const e=de();return g.useCallback(()=>{e.attachment().remove()},[e])},nf=ur("AttachmentPrimitive.Remove",rf),cr=e=>{const t=g.useRef(void 0);return g.useCallback(n=>{t.current&&t.current(),n&&(t.current=e(n))},[e])},ks=(e,t)=>{const r=g.useCallback(n=>{if(!e)return;const a=e(),i=()=>{const o=t?t(n):n.offsetHeight;a.setHeight(o)},s=new ResizeObserver(i);return s.observe(n),i(),()=>{s.disconnect(),a.unregister()}},[e,t]);return cr(r)},_s=g.createContext(!1),Ts=(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 i=parseFloat(getComputedStyle(t).fontSize)||16;return n*i}if(a==="rem"){const i=parseFloat(getComputedStyle(document.documentElement).fontSize)||16;return n*i}return 0},Cs=({children:e,fillClampThreshold:t="10em",fillClampOffset:r="6em"})=>{const n=se(({message:l})=>l.isLast&&l.index>=2),a=Un({optional:!0}),i=g.useContext(_s),s=g.useCallback(l=>{if(!a||i)return;const u=()=>{const d=a.getState();if(d.turnAnchor==="top"&&n){const{viewport:c,inset:f,userMessage:h}=d.height,y=Ts(t,l),S=Ts(r,l),x=h<=y?h:S,b=Math.max(0,c-f-x);l.style.minHeight=`${b}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,i,t,r]),o=cr(s);return p.jsx(_s.Provider,{value:!0,children:p.jsx(Ss,{ref:o,children:e})})};Cs.displayName="ThreadPrimitive.ViewportSlack";var af=()=>{const e=de(),t=se(()=>e.message()),r=g.useCallback(n=>{const a=()=>{t.setIsHovering(!0)},i=()=>{t.setIsHovering(!1)};return n.addEventListener("mouseenter",a),n.addEventListener("mouseleave",i),n.matches(":hover")&&t.setIsHovering(!0),()=>{n.removeEventListener("mouseenter",a),n.removeEventListener("mouseleave",i),t.setIsHovering(!1)}},[t]);return cr(r)},sf=()=>{const e=Vr(a=>a.turnAnchor),t=Vr(a=>a.registerUserMessageHeight),r=se(({thread:a,message:i})=>{var s;return e==="top"&&i.role==="user"&&i.index===a.messages.length-2&&((s=a.messages.at(-1))==null?void 0:s.role)==="assistant"}),n=g.useCallback(a=>a.offsetHeight,[]);return ks(r?t:null,n)},Xn=g.forwardRef((e,t)=>{const r=af(),n=sf(),a=Hr(t,r,n);return p.jsx(Cs,{children:p.jsx(at.div,E(m({},e),{ref:a}))})});Xn.displayName="MessagePrimitive.Root";var Is=()=>se(({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}),Es=g.forwardRef((a,n)=>{var i=a,{smooth:e=!0,component:t="span"}=i,r=W(i,["smooth","component"]);const{text:s,status:o}=ys(Is(),e);return p.jsx(t,E(m({"data-status":o.type},r),{ref:n,children:s}))});Es.displayName="MessagePartPrimitive.Text";var of=()=>se(({part:t})=>{if(t.type!=="image")throw new Error("MessagePartImage can only be used inside image message parts.");return t}),As=g.forwardRef((e,t)=>{const{image:r}=of();return p.jsx(at.img,E(m({src:r},e),{ref:t}))});As.displayName="MessagePartPrimitive.Image";var Ps=({children:e})=>se(({part:r})=>r.status.type==="running")?e:null;Ps.displayName="MessagePartPrimitive.InProgress";const Ms=e=>Symbol.iterator in e,Ns=e=>"entries"in e,Ls=(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,i]of r)if(!n.has(a)||!Object.is(i,n.get(a)))return!1;return!0},lf=(e,t)=>{const r=e[Symbol.iterator](),n=t[Symbol.iterator]();let a=r.next(),i=n.next();for(;!a.done&&!i.done;){if(!Object.is(a.value,i.value))return!1;a=r.next(),i=n.next()}return!!a.done&&!!i.done};function uf(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:Ms(e)&&Ms(t)?Ns(e)&&Ns(t)?Ls(e,t):lf(e,t):Ls({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function cf(e){const t=g.useRef(void 0);return r=>{const n=e(r);return uf(t.current,n)?t.current:t.current=n}}var Ds=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})}}},df=e=>{const t=[],r=Ds("toolGroup"),n=Ds("reasoningGroup");for(let a=0;a<e.length;a++){const i=e[a];i==="tool-call"?(n.endGroup(a-1,t),r.startGroup(a)):i==="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},hf=()=>{const e=se(cf(t=>t.message.parts.map(r=>r.type)));return g.useMemo(()=>e.length===0?[]:df(e),[e])},ff=r=>{var n=r,{Fallback:e}=n,t=W(n,["Fallback"]);const a=se(({tools:i})=>{var o,l;const s=(o=i.tools[t.toolName])!=null?o:e;return Array.isArray(s)?(l=s[0])!=null?l:e:s});return a?p.jsx(a,m({},t)):null},it={Text:()=>p.jsxs("p",{style:{whiteSpace:"pre-line"},children:[p.jsx(Es,{}),p.jsx(Ps,{children:p.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>p.jsx(As,{}),File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},pf=({components:{Text:e=it.Text,Reasoning:t=it.Reasoning,Image:r=it.Image,Source:n=it.Source,File:a=it.File,Unstable_Audio:i=it.Unstable_Audio,tools:s={}}={}})=>{var d,c,f;const o=de(),l=se(({part:h})=>h),u=l.type;if(u==="tool-call"){const h=o.part().addToolResult,y=o.part().resumeToolCall;if("Override"in s)return p.jsx(s.Override,E(m({},l),{addResult:h,resume:y}));const S=(c=(d=s.by_name)==null?void 0:d[l.toolName])!=null?c:s.Fallback;return p.jsx(ff,E(m({},l),{Fallback:S,addResult:h,resume:y}))}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(i,m({},l));case"data":return null;default:const h=u;throw new Error(`Unknown message part type: ${h}`)}},Yr=g.memo(({index:e,components:t})=>p.jsx(oh,{index:e,children:p.jsx(pf,{components:t})}),(e,t)=>{var r,n,a,i,s,o,l,u,d,c,f,h,y,S,x,b,_,T;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)===((i=t.components)==null?void 0:i.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)&&((y=e.components)==null?void 0:y.tools)===((S=t.components)==null?void 0:S.tools)&&((x=e.components)==null?void 0:x.ToolGroup)===((b=t.components)==null?void 0:b.ToolGroup)&&((_=e.components)==null?void 0:_.ReasoningGroup)===((T=t.components)==null?void 0:T.ReasoningGroup)});Yr.displayName="MessagePrimitive.PartByIndex";var mf=({status:e,component:t})=>p.jsx(dh,{text:"",isRunning:e.type==="running",children:p.jsx(t,{type:"text",text:"",status:e})}),gf=Object.freeze({type:"complete"}),yf=({components:e})=>{var r;const t=se(n=>{var a;return(a=n.message.status)!=null?a:gf});return e!=null&&e.Empty?p.jsx(e.Empty,{status:t}):p.jsx(mf,{status:t,component:(r=e==null?void 0:e.Text)!=null?r:it.Text})},bf=g.memo(yf,(e,t)=>{var r,n,a,i;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)===((i=t.components)==null?void 0:i.Text)}),Qn=({components:e})=>{const t=se(({message:a})=>a.parts.length),r=hf(),n=g.useMemo(()=>t===0?p.jsx(bf,{components:e}):r.map(a=>{var i,s;if(a.type==="single")return p.jsx(Yr,{index:a.index,components:e},a.index);if(a.type==="toolGroup"){const o=(i=e==null?void 0:e.ToolGroup)!=null?i:it.ToolGroup;return p.jsx(o,{startIndex:a.startIndex,endIndex:a.endIndex,children:Array.from({length:a.endIndex-a.startIndex+1},(l,u)=>p.jsx(Yr,{index:a.startIndex+u,components:e},u))},`tool-${a.startIndex}`)}else{const o=(s=e==null?void 0:e.ReasoningGroup)!=null?s:it.ReasoningGroup;return p.jsx(o,{startIndex:a.startIndex,endIndex:a.endIndex,children:Array.from({length:a.endIndex-a.startIndex+1},(l,u)=>p.jsx(Yr,{index:a.startIndex+u,components:e},u))},`reasoning-${a.startIndex}`)}}),[r,e,t]);return p.jsx(p.Fragment,{children:n})};Qn.displayName="MessagePrimitive.Parts";var wf=(e,t)=>{var n,a,i;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(i=e==null?void 0:e.File)!=null?i:e==null?void 0:e.Attachment;default:const s=r;throw new Error(`Unknown attachment type: ${s}`)}},xf=({components:e})=>{const t=se(({attachment:n})=>n);if(!t)return null;const r=wf(e,t);return r?p.jsx(r,{}):null},Os=g.memo(({index:e,components:t})=>p.jsx(lh,{index:e,children:p.jsx(xf,{components:t})}),(e,t)=>{var r,n,a,i,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)&&((a=e.components)==null?void 0:a.Document)===((i=t.components)==null?void 0:i.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)});Os.displayName="MessagePrimitive.AttachmentByIndex";var Fs=({components:e})=>{const t=se(({message:n})=>n.role!=="user"?0:n.attachments.length);return g.useMemo(()=>Array.from({length:t},(n,a)=>p.jsx(Os,{index:a,components:e},a)),[t,e])};Fs.displayName="MessagePrimitive.Attachments";var Bs=()=>{const e=de(),t=se(n=>n.thread.isRunning||!n.composer.isEditing||n.composer.isEmpty),r=g.useCallback(()=>{e.composer().send()},[e]);return t?null:r},vf=ur("ComposerPrimitive.Send",Bs),zs=g.forwardRef((n,r)=>{var a=n,{onSubmit:e}=a,t=W(a,["onSubmit"]);const i=Bs(),s=o=>{o.preventDefault(),i&&i()};return p.jsx(at.form,E(m({},t),{ref:r,onSubmit:Rt(e,s)}))});zs.displayName="ComposerPrimitive.Root";function Zn(){return Zn=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},Zn.apply(null,arguments)}function Sf(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 kf=g.useLayoutEffect,_f=function(t){var r=g.useRef(t);return kf(function(){r.current=t}),r},Rs=function(t,r){if(typeof t=="function"){t(r);return}t.current=r},Tf=function(t,r){var n=g.useRef();return g.useCallback(function(a){t.current=a,n.current&&Rs(n.current,null),n.current=r,r&&Rs(r,a)},[r])},js={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},Cf=function(t){Object.keys(js).forEach(function(r){t.style.setProperty(r,js[r],"important")})},$s=Cf,Ie=null,Us=function(t,r){var n=t.scrollHeight;return r.sizingStyle.boxSizing==="border-box"?n+r.borderSize:n-r.paddingSize};function If(e,t,r,n){r===void 0&&(r=1),n===void 0&&(n=1/0),Ie||(Ie=document.createElement("textarea"),Ie.setAttribute("tabindex","-1"),Ie.setAttribute("aria-hidden","true"),$s(Ie)),Ie.parentNode===null&&document.body.appendChild(Ie);var a=e.paddingSize,i=e.borderSize,s=e.sizingStyle,o=s.boxSizing;Object.keys(s).forEach(function(f){var h=f;Ie.style[h]=s[h]}),$s(Ie),Ie.value=t;var l=Us(Ie,e);Ie.value=t,l=Us(Ie,e),Ie.value="x";var u=Ie.scrollHeight-a,d=u*r;o==="border-box"&&(d=d+a+i),l=Math.max(d,l);var c=u*n;return o==="border-box"&&(c=c+a+i),l=Math.min(c,l),[l,u]}var Hs=function(){},Ef=function(t,r){return t.reduce(function(n,a){return n[a]=r[a],n},{})},Af=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],Pf=!!document.documentElement.currentStyle,Mf=function(t){var r=window.getComputedStyle(t);if(r===null)return null;var n=Ef(Af,r),a=n.boxSizing;if(a==="")return null;Pf&&a==="border-box"&&(n.width=parseFloat(n.width)+parseFloat(n.borderRightWidth)+parseFloat(n.borderLeftWidth)+parseFloat(n.paddingRight)+parseFloat(n.paddingLeft)+"px");var i=parseFloat(n.paddingBottom)+parseFloat(n.paddingTop),s=parseFloat(n.borderBottomWidth)+parseFloat(n.borderTopWidth);return{sizingStyle:n,paddingSize:i,borderSize:s}},Nf=Mf;function ea(e,t,r){var n=_f(r);Y.useLayoutEffect(function(){var a=function(s){return n.current(s)};if(e)return e.addEventListener(t,a),function(){return e.removeEventListener(t,a)}},[])}var Lf=function(t,r){ea(document.body,"reset",function(n){t.current.form===n.target&&r(n)})},Df=function(t){ea(window,"resize",t)},Of=function(t){ea(document.fonts,"loadingdone",t)},Ff=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],Bf=function(t,r){var n=t.cacheMeasurements,a=t.maxRows,i=t.minRows,s=t.onChange,o=s===void 0?Hs:s,l=t.onHeightChange,u=l===void 0?Hs:l,d=Sf(t,Ff),c=d.value!==void 0,f=Y.useRef(null),h=Tf(f,r),y=Y.useRef(0),S=Y.useRef(),x=function(){var T=f.current,L=n&&S.current?S.current:Nf(T);if(L){S.current=L;var z=If(L,T.value||T.placeholder||"x",i,a),I=z[0],q=z[1];y.current!==I&&(y.current=I,T.style.setProperty("height",I+"px","important"),u(I,{rowHeight:q}))}},b=function(T){c||x(),o(T)};return Y.useLayoutEffect(x),Lf(f,function(){if(!c){var _=f.current.value;requestAnimationFrame(function(){var T=f.current;T&&_!==T.value&&x()})}}),Df(x),Of(x),Y.createElement("textarea",Zn({},d,{onChange:b,ref:h}))},zf=Y.forwardRef(Bf),qs=e=>{const t=Ct(e),r=Vr(n=>n.onScrollToBottom);g.useEffect(()=>r(t),[r,t])},Vs=g.forwardRef((y,h)=>{var S=y,{autoFocus:e=!1,asChild:t,disabled:r,onChange:n,onKeyDown:a,onPaste:i,submitOnEnter:s=!0,cancelOnEscape:o=!0,unstable_focusOnRunStart:l=!0,unstable_focusOnScrollToBottom:u=!0,unstable_focusOnThreadSwitched:d=!0,addAttachmentOnPaste:c=!0}=S,f=W(S,["autoFocus","asChild","disabled","onChange","onKeyDown","onPaste","submitOnEnter","cancelOnEscape","unstable_focusOnRunStart","unstable_focusOnScrollToBottom","unstable_focusOnThreadSwitched","addAttachmentOnPaste"]);const x=de(),b=se(({composer:k})=>k.isEditing?k.text:""),_=t?Ss:zf,T=se(({thread:k})=>k.isDisabled)||r,L=g.useRef(null),z=Hr(h,L);tf(k=>{var M;if(!o||!((M=L.current)!=null&&M.contains(k.target)))return;const D=x.composer();D.getState().canCancel&&(D.cancel(),k.preventDefault())});const I=k=>{var D,M;T||!s||k.nativeEvent.isComposing||k.key==="Enter"&&k.shiftKey===!1&&(x.thread().getState().isRunning||(k.preventDefault(),(M=(D=L.current)==null?void 0:D.closest("form"))==null||M.requestSubmit()))},q=k=>P(null,null,function*(){var H;if(!c)return;const D=x.thread().getState().capabilities,M=Array.from(((H=k.clipboardData)==null?void 0:H.files)||[]);if(D.attachments&&M.length>0)try{k.preventDefault(),yield Promise.all(M.map(R=>x.composer().addAttachment(R)))}catch(R){console.error("Error adding attachment:",R)}}),B=e&&!T,U=g.useCallback(()=>{const k=L.current;!k||!B||(k.focus({preventScroll:!0}),k.setSelectionRange(k.value.length,k.value.length))},[B]);return g.useEffect(()=>U(),[U]),qs(()=>{x.composer().getState().type==="thread"&&u&&U()}),g.useEffect(()=>{if(!(x.composer().getState().type!=="thread"||!l))return x.on("thread.run-start",U)},[l,U,x]),g.useEffect(()=>{if(!(x.composer().getState().type!=="thread"||!d))return x.on("thread-list-item.switched-to",U)},[d,U,x]),p.jsx(_,E(m({name:"input",value:b},f),{ref:z,disabled:T,onChange:Rt(n,k=>{x.composer().getState().isEditing&&(x.composer().setText(k.target.value),x.flushSync())}),onKeyDown:Rt(a,I),onPaste:Rt(i,q)}))});Vs.displayName="ComposerPrimitive.Input";var Rf=({multiple:e=!0}={})=>{const t=se(({composer:a})=>!a.isEditing),r=de(),n=g.useCallback(()=>{const a=document.createElement("input");a.type="file",a.multiple=e,a.hidden=!0;const i=r.composer().getState().attachmentAccept;i!=="*"&&(a.accept=i),document.body.appendChild(a),a.onchange=s=>{const o=s.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},jf=ur("ComposerPrimitive.AddAttachment",Rf,["multiple"]),$f=(e,t)=>{var n,a,i;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(i=e==null?void 0:e.File)!=null?i:e==null?void 0:e.Attachment;default:const s=r;throw new Error(`Unknown attachment type: ${s}`)}},Uf=({components:e})=>{const t=se(({attachment:n})=>n);if(!t)return null;const r=$f(e,t);return r?p.jsx(r,{}):null},Ws=g.memo(({index:e,components:t})=>p.jsx(uh,{index:e,children:p.jsx(Uf,{components:t})}),(e,t)=>{var r,n,a,i,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)&&((a=e.components)==null?void 0:a.Document)===((i=t.components)==null?void 0:i.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)});Ws.displayName="ComposerPrimitive.AttachmentByIndex";var Js=({components:e})=>{const t=se(n=>n.composer.attachments.length);return g.useMemo(()=>Array.from({length:t},(n,a)=>p.jsx(Ws,{index:a,components:e},a)),[t,e])};Js.displayName="ComposerPrimitive.Attachments";var Ks=g.forwardRef((e,t)=>p.jsx(at.div,E(m({},e),{ref:t})));Ks.displayName="ThreadPrimitive.Root";var Gs=({children:e})=>se(({thread:r})=>r.messages.length===0&&!r.isLoading)?e:null;Gs.displayName="ThreadPrimitive.Empty";var Hf=e=>se(({thread:t})=>!(e.empty===!0&&!t.isEmpty||e.empty===!1&&t.isEmpty||e.running===!0&&!t.isRunning||e.running===!1&&t.isRunning||e.disabled===!0&&!t.isDisabled||e.disabled===!1&&t.isDisabled)),Ys=r=>{var n=r,{children:e}=n,t=W(n,["children"]);return Hf(t)?e:null};Ys.displayName="ThreadPrimitive.If";var qf=e=>{const t=Ct(e),r=g.useCallback(n=>{const a=new ResizeObserver(()=>{t()}),i=new MutationObserver(()=>{t()});return a.observe(n),i.observe(n,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{a.disconnect(),i.disconnect()}},[t]);return cr(r)},Vf=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:r=!0,scrollToBottomOnThreadSwitch:n=!0})=>{const a=g.useRef(null),i=Un();e===void 0&&(e=i.getState().turnAnchor!=="top");const s=g.useRef(0),o=g.useRef(null),l=g.useCallback(h=>{const y=a.current;y&&(o.current=h,y.scrollTo({top:y.scrollHeight,behavior:h}))},[]),u=()=>{const h=a.current;if(!h)return;const y=i.getState().isAtBottom,S=Math.abs(h.scrollHeight-h.scrollTop-h.clientHeight)<1||h.scrollHeight<=h.clientHeight;!S&&s.current<h.scrollTop||(S&&(o.current=null),(S||o.current===null)&&S!==y&&lr(i).setState({isAtBottom:S})),s.current=h.scrollTop},d=qf(()=>{const h=o.current;h?l(h):e&&i.getState().isAtBottom&&l("instant"),u()}),c=cr(h=>(h.addEventListener("scroll",u),()=>{h.removeEventListener("scroll",u)}));return qs(({behavior:h})=>{l(h)}),$n("thread.run-start",()=>{t&&(o.current="auto",requestAnimationFrame(()=>{l("auto")}))}),$n("thread.initialize",()=>{r&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),$n("thread-list-item.switched-to",()=>{n&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Hr(d,c,a)},Wf=()=>{const e=Vr(r=>r.registerViewport),t=g.useCallback(r=>r.clientHeight,[]);return ks(e,t)},Xs=g.forwardRef((o,s)=>{var l=o,{autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:r,scrollToBottomOnThreadSwitch:n,children:a}=l,i=W(l,["autoScroll","scrollToBottomOnRunStart","scrollToBottomOnInitialize","scrollToBottomOnThreadSwitch","children"]);const u=Vf({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:r,scrollToBottomOnThreadSwitch:n}),d=Wf(),c=Hr(s,u,d);return p.jsx(at.div,E(m({},i),{ref:c,children:a}))});Xs.displayName="ThreadPrimitive.ViewportScrollable";var Qs=g.forwardRef((n,r)=>{var a=n,{turnAnchor:e}=a,t=W(a,["turnAnchor"]);return p.jsx(os,{options:{turnAnchor:e},children:p.jsx(Xs,E(m({},t),{ref:r}))})});Qs.displayName="ThreadPrimitive.Viewport";var Zs=(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,Jf=()=>null,Kf=(e,t,r)=>{var n,a,i,s,o,l,u,d,c,f,h,y;switch(t){case"user":return r?(i=(a=(n=e.UserEditComposer)!=null?n:e.EditComposer)!=null?a:e.UserMessage)!=null?i: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:(y=e.SystemMessage)!=null?y:Jf;default:const S=t;throw new Error(`Unknown message role: ${S}`)}},Gf=({components:e})=>{const t=se(({message:a})=>a.role),r=se(({message:a})=>a.composer.isEditing),n=Kf(e,t,r);return p.jsx(n,{})},eo=g.memo(({index:e,components:t})=>p.jsx(sh,{index:e,children:p.jsx(Gf,{components:t})}),(e,t)=>e.index===t.index&&Zs(e.components,t.components));eo.displayName="ThreadPrimitive.MessageByIndex";var to=({components:e})=>{const t=se(({thread:n})=>n.messages.length);return g.useMemo(()=>t===0?null:Array.from({length:t},(n,a)=>p.jsx(eo,{index:a,components:e},a)),[t,e])};to.displayName="ThreadPrimitive.Messages";var Yf=g.memo(to,(e,t)=>Zs(e.components,t.components)),ro=g.forwardRef((a,n)=>{var i=a,{onClick:e,disabled:t}=i,r=W(i,["onClick","disabled"]);const s=se(({threads:l})=>l.newThreadId===l.mainThreadId),o=de();return p.jsx(at.button,E(m(m({type:"button"},s?{"data-active":"true","aria-current":"true"}:null),r),{ref:n,disabled:t,onClick:Rt(e,()=>{o.threads().switchToNewThread()})}))});ro.displayName="ThreadListPrimitive.New";var no=g.memo(({index:e,archived:t=!1,components:r})=>{const n=r.ThreadListItem;return p.jsx(ah,{index:e,archived:t,children:p.jsx(n,{})})},(e,t)=>e.index===t.index&&e.archived===t.archived&&e.components.ThreadListItem===t.components.ThreadListItem);no.displayName="ThreadListPrimitive.ItemByIndex";var ao=({archived:e=!1,components:t})=>{const r=se(({threads:a})=>e?a.archivedThreadIds.length:a.threadIds.length);return g.useMemo(()=>Array.from({length:r},(a,i)=>p.jsx(no,{index:i,archived:e,components:t},i)),[r,e,t])};ao.displayName="ThreadListPrimitive.Items";var io=g.forwardRef((e,t)=>p.jsx(at.div,E(m({},e),{ref:t})));io.displayName="ThreadListPrimitive.Root";var so=g.forwardRef((e,t)=>{const r=se(({threads:n,threadListItem:a})=>n.mainThreadId===a.id);return p.jsx(at.div,E(m(m({},r?{"data-active":"true","aria-current":"true"}:null),e),{ref:t}))});so.displayName="ThreadListItemPrimitive.Root";var Xf=()=>{const e=de();return g.useCallback(()=>{e.threadListItem().delete()},[e])},Qf=ur("ThreadListItemPrimitive.Delete",Xf),Zf=()=>{const e=de();return g.useCallback(()=>{e.threadListItem().switchTo()},[e])},ep=ur("ThreadListItemPrimitive.Trigger",Zf);class oo{constructor(t,r,n=!1){C(this,"baseUrl");C(this,"sessionToken",null);C(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 P(this,null,function*(){const n=this.getUrl("/v1/chats"),i={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const s=E(m({},t),{stream:!0}),o=yield fetch(n,{method:"POST",headers:i,body:JSON.stringify(s),signal:r});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 P(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 i=yield a.json().catch(()=>({}));throw new Error(i.detail||i.message||`API error: ${a.status} ${a.statusText}`)}return a.json()})}listChats(t){return P(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 a={"Content-Type":"application/json"};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(n.toString(),{method:"GET",headers:a});if(!i.ok){const s=yield i.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${i.status} ${i.statusText}`)}return i.json()})}generateIdempotencyKey(){try{if(typeof crypto!="undefined"&&crypto.randomUUID)return crypto.randomUUID()}catch(n){}const t=n=>Array.from({length:n},()=>Math.floor(Math.random()*16).toString(16)).join(""),r=()=>{const n=["8","9","a","b"];return n[Math.floor(Math.random()*n.length)]};return`${t(8)}-${t(4)}-4${t(3)}-${r()}${t(3)}-${t(12)}`}updateChat(t,r){return P(this,null,function*(){const n=`/v1/chats/${t}`,a=this.getUrl(n),i=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(i.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 P(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),s={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(s.Authorization=`Bearer ${this.sessionToken}`);const o=yield fetch(a.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}`)}})}listModels(t){return P(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 a={"Content-Type":"application/json"};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(n.toString(),{method:"GET",headers:a});if(!i.ok){const s=yield i.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${i.status} ${i.statusText}`)}return i.json()})}getModel(t){return P(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 i=yield a.json().catch(()=>({}));throw new Error(i.detail||i.message||`API error: ${a.status} ${a.statusText}`)}return a.json()})}uploadFile(t,r,n){return P(this,null,function*(){const a=this.getUrl("/v1/files"),i=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":i};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(a,{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 tp(e,t){return Er(this,null,function*(){const r=e.getReader(),n=new TextDecoder;let a="";try{for(;;){if(t!=null&&t.aborted){r.cancel();break}const{done:i,value:s}=yield new qe(r.read());if(i)break;a+=n.decode(s,{stream:!0});const o=a.split(`
5
+ `),Ti=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)}},Ci=class extends Ti{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)}},hc=class extends Ci{get source(){return"thread-composer"}},fc=class extends Ci{get source(){return"edit-composer"}},pc=class extends Ti{get source(){return"message"}constructor(e){super(e)}remove(){throw new Error("Message attachments cannot be removed")}},Ii=class extends Or{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 i=this.config.binding.getState();i!==t&&(t=i,r==null||r(),r=(s=this.config.binding.getState())==null?void 0:s.unstable_on(this.config.event,e))},a=this.outerSubscribe(n);return()=>{a==null||a(),r==null||r()}}},Ei=Object.freeze([]),Ai=Object.freeze({}),mc=e=>{var t,r,n,a,i,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:(a=e==null?void 0:e.attachments)!=null?a:Ei,text:(i=e==null?void 0:e.text)!=null?i:"",role:(s=e==null?void 0:e.role)!=null?s:"user",runConfig:(o=e==null?void 0:e.runConfig)!=null?o:Ai,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},gc=e=>{var t,r,n,a,i,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:(a=e==null?void 0:e.text)!=null?a:"",role:(i=e==null?void 0:e.role)!=null?i:"user",attachments:(s=e==null?void 0:e.attachments)!=null?s:Ei,runConfig:(o=e==null?void 0:e.runConfig)!=null?o:Ai,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},Mi=class{constructor(e){C(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 Ii({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}},yc=class extends Mi{constructor(t){const r=new Ln({path:t.path,getState:()=>mc(t.getState()),subscribe:n=>t.subscribe(n)});super({path:t.path,getState:()=>t.getState(),subscribe:n=>r.subscribe(n)});C(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 hc(new Qe({path:E(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?E(m({},n),{source:"thread-composer"}):Xe},subscribe:r=>this._core.subscribe(r)}),this._core)}},bc=class extends Mi{constructor(t,r){const n=new Ln({path:t.path,getState:()=>gc(t.getState()),subscribe:a=>t.subscribe(a)});super({path:t.path,getState:()=>t.getState(),subscribe:a=>n.subscribe(a)});C(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 fc(new Qe({path:E(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?E(m({},n),{source:"edit-composer"}):Xe},subscribe:r=>this._core.subscribe(r)}),this._core)}},wc=class vn{constructor(t=null){C(this,"_state");this._state=t}get state(){return this._state}append(t){this._state=t.reduce((r,n)=>vn.apply(r,n),this._state)}static apply(t,r){const n=r.type;switch(n){case"set":return vn.updatePath(t,r.path,()=>r.value);case"append-text":return vn.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,...i]=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],i,n),l}const s=m({},t);return s[a]=this.updatePath(s[a],i,n),s}},xc=({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:{}}}),Rr=(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 E(m({},e),{parts:[...e.parts.slice(0,n),a,...e.parts.slice(n+1)],get content(){return this.parts}})},vc=(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 E(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 E(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 E(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 E(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else throw new Error(`Unsupported part type: ${r.type}`)},kc=(e,t)=>Rr(e,t,r=>{if(r.type!=="tool-call")throw new Error("Last is not a tool call");return r.state!=="partial-call"?r:E(m({},r),{state:"call"})}),Sc=(e,t)=>Rr(e,t,r=>E(m({},r),{status:{type:"complete",reason:"unknown"}})),_c=(e,t)=>Rr(e,t,r=>{var n;if(r.type==="text"||r.type==="reasoning")return E(m({},r),{text:r.text+t.textDelta});if(r.type==="tool-call"){const a=r.argsText+t.textDelta,i=(n=Lr(a))!=null?n:r.args;return E(m({},r),{argsText:a,args:i})}else throw new Error("text-delta received but part is neither text nor tool-call")}),Tc=(e,t)=>Rr(e,t,r=>{var n;if(r.type==="tool-call")return E(m(E(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")}),Pi=(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=Cc(t);return E(m({},e),{status:r})},Cc=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},Ic=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]})}),Ec=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{unstable_data:[...e.metadata.unstable_data,...t.data]})}),Ac=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{steps:[...e.metadata.steps,{state:"started",messageId:t.messageId}]})}),Mc=(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]=E(m({},r[n]),{state:"finished",finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}):r.push({state:"finished",messageId:ki(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),E(m({},e),{metadata:E(m({},e.metadata),{steps:r})})},Pc=(e,t)=>E(m({},e),{status:{type:"incomplete",reason:"error",error:t.error}}),Nc=(e,t)=>{const r=new wc(e.metadata.unstable_state);return r.append(t.operations),E(m({},e),{metadata:E(m({},e.metadata),{unstable_state:r.state})})},Lc=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}},Dc=class extends TransformStream{constructor({initialMessage:e,throttle:t,onError:r}={}){let n=e!=null?e:xc(),a;const i=t?Lc(()=>{a==null||a.enqueue(n)}):()=>{a==null||a.enqueue(n)};super({start(s){a=s},transform(s){const o=s.type;switch(o){case"part-start":n=vc(n,s);break;case"tool-call-args-text-finish":n=kc(n,s);break;case"part-finish":n=Sc(n,s);break;case"text-delta":n=_c(n,s);break;case"result":n=Tc(n,s);break;case"message-finish":n=Pi(n,s);break;case"annotations":n=Ic(n,s);break;case"data":n=Ec(n,s);break;case"step-start":n=Ac(n,s);break;case"step-finish":n=Mc(n,s);break;case"error":n=Pc(n,s),r==null||r(s.error);break;case"update-state":n=Nc(n,s);break;default:{const l=o;throw new Error(`Unsupported chunk type: ${l}`)}}i()},flush(s){var o,l,u;if(((o=n.status)==null?void 0:o.type)==="running"){const c=(u=(l=n.parts)==null?void 0:l.some(d=>d.type==="tool-call"&&(d.state==="call"||d.state==="partial-call")&&d.result===void 0))!=null?u:!1;n=Pi(n,{finishReason:c?"tool-calls":"unknown"}),s.enqueue(n)}}})}},Oc=class extends xi{constructor(){super(e=>{const t=new uc({transform(r,n){n.appendText(r)}});return e.pipeThrough(new TextDecoderStream).pipeThrough(t)})}},Fc=class kn{constructor(t){this.readable=t,this.readable=t}static fromAssistantStream(t){return new kn(t.pipeThrough(new Dc))}unstable_result(){return P(this,null,function*(){let t;try{for(var r=Nt(this),n,a,i;n=!(a=yield r.next()).done;n=!1){const s=a.value;t=s}}catch(a){i=[a]}finally{try{n&&(a=r.return)&&(yield a.call(r))}finally{if(i)throw i[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 P(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 kn(t),new kn(r)]}},Ni=Symbol.for("aui.tool-response"),dt=class ii{constructor(t){C(this,"artifact");C(this,"result");C(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[Ni](){return!0}static[Symbol.hasInstance](t){return typeof t=="object"&&t!==null&&Ni in t}static toResponse(t){return t instanceof ii?t:new ii({result:t===void 0?"<no result>":t})}};function Bc(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 ar(e,t){let r=e;for(const n of t){if(r==null)return;r=r[n]}return r}var zc=class{constructor(e,t,r){C(this,"resolve");C(this,"reject");C(this,"disposed",!1);C(this,"fieldPath");this.resolve=e,this.reject=t,this.fieldPath=r}update(e){if(!this.disposed)try{if(Lt(e,this.fieldPath)==="complete"){const t=ar(e,this.fieldPath);t!==void 0&&(this.resolve(t),this.dispose())}}catch(t){this.reject(t),this.dispose()}}dispose(){this.disposed=!0}},Li=class{constructor(e,t){C(this,"controller");C(this,"disposed",!1);C(this,"fieldPath");this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=ar(e,this.fieldPath);t!==void 0&&this.controller.enqueue(t),Lt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},Di=class{constructor(e,t){C(this,"controller");C(this,"disposed",!1);C(this,"fieldPath");C(this,"lastValue");this.controller=e,this.fieldPath=t}update(e){var t;if(!this.disposed)try{const r=ar(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)}Lt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(r){this.controller.error(r),this.dispose()}}dispose(){this.disposed=!0}},Oi=class{constructor(e,t){C(this,"controller");C(this,"disposed",!1);C(this,"fieldPath");C(this,"processedIndexes",new Set);this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=ar(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];Lt(e,n)==="complete"&&(this.controller.enqueue(t[r]),this.processedIndexes.add(r))}Lt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},Rc=class{constructor(e){C(this,"argTextDeltas");C(this,"handles",new Set);C(this,"args",Lr(""));this.argTextDeltas=e,this.processStream()}processStream(){return P(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=Lr(e);if(a!==void 0){this.args=a;for(const i of this.handles)i.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 zc(t,r,e);if(this.args&&Lt(this.args,e)==="complete"){const a=ar(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 Li(n,t);this.handles.add(a),a.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Li){n.dispose(),this.handles.delete(n);break}}});return An(r)}streamText(...e){const t=e,r=new ReadableStream({start:n=>{const a=new Di(n,t);this.handles.add(a),a.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Di){n.dispose(),this.handles.delete(n);break}}});return An(r)}forEach(...e){const t=e,r=new ReadableStream({start:n=>{const a=new Oi(n,t);this.handles.add(a),a.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Oi){n.dispose(),this.handles.delete(n);break}}});return An(r)}},jc=class{constructor(e){this.promise=e}get(){return this.promise}},$c=class{constructor(){C(this,"args");C(this,"response");C(this,"writable");C(this,"resolve");C(this,"argsText","");C(this,"result",{get:()=>P(this,null,function*(){return(yield this.response.get()).result})});const e=new TransformStream;this.writable=e.writable,this.args=new Rc(e.readable);const{promise:t,resolve:r}=Pn();this.resolve=r,this.response=new jc(t)}appendArgsTextDelta(e){return P(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)}},Uc=class extends xi{constructor(e){const t=new Map,r=new Map;super(n=>{const a=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 $c;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,c=r.get(u);if(!c)throw new Error("No controller found for tool call");c.appendArgsTextDelta(s.textDelta)}break}case"result":{if(s.meta.type!=="tool-call")break;const{toolCallId:u}=s.meta,c=r.get(u);if(!c)throw new Error("No controller found for tool call");c.setResponse(new dt({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:c}=s.meta,d=r.get(u);if(!d)throw new Error("No controller found for tool call");let f=!1;const h=Bc(()=>{var w;let g;try{g=En.parse(d.argsText)}catch(b){throw new Error(`Function parameter parsing failed. ${JSON.stringify(b.message)}`)}const k=e.execute({toolCallId:u,toolName:c,args:g});return k!==void 0&&(f=!0,(w=e.onExecutionStart)==null||w.call(e,u,c)),k},g=>{var w;if(f&&((w=e.onExecutionEnd)==null||w.call(e,u,c)),g===void 0)return;const k=new dt({artifact:g.artifact,result:g.result,isError:g.isError});d.setResponse(k),o.enqueue(m({type:"result",path:s.path},k))},g=>{var w;f&&((w=e.onExecutionEnd)==null||w.call(e,u,c));const k=new dt({result:String(g),isError:!0});d.setResponse(k),o.enqueue(m({type:"result",path:s.path},k))});h&&t.set(u,h);break}case"part-finish":{if(s.meta.type!=="tool-call")break;const{toolCallId:u}=s.meta,c=t.get(u);c?c.then(()=>{t.delete(u),r.delete(u),o.enqueue(s)}):o.enqueue(s)}}},flush(){return P(this,null,function*(){yield Promise.all(t.values())})}});return n.pipeThrough(new vi).pipeThrough(a)})}},Hc=e=>typeof e=="object"&&e!==null&&"~standard"in e&&e["~standard"].version===1;function qc(e,t,r,n){const a=e==null?void 0:e[r.toolName];return!a||!a.execute?void 0:(s=>P(null,null,function*(){var c;if(t.aborted)return new dt({result:"Tool execution was cancelled.",isError:!0});let o=s;if(Hc(a.parameters)){let d=a.parameters["~standard"].validate(r.args);d instanceof Promise&&(d=yield d),d.issues&&(o=(c=a.experimental_onSchemaValidationError)!=null?c:(()=>{throw new Error(`Function parameter validation failed. ${JSON.stringify(d.issues)}`)}))}const l=new Promise(d=>{const f=()=>{queueMicrotask(()=>{queueMicrotask(()=>{d(new dt({result:"Tool execution was cancelled.",isError:!0}))})})};t.aborted?f():t.addEventListener("abort",f,{once:!0})}),u=P(null,null,function*(){const d=yield o(r.args,{toolCallId:r.toolCallId,abortSignal:t,human:f=>n(r.toolCallId,f)});return dt.toResponse(d)});return Promise.race([u,l])}))(a.execute)}function Vc(e,t,r,n,a){var i,s;(s=(i=e==null?void 0:e[n.toolName])==null?void 0:i.streamCall)==null||s.call(i,r,{toolCallId:n.toolCallId,abortSignal:t,human:o=>a(n.toolCallId,o)})}function Wc(e,t,r,n){const a=typeof e=="function"?e:()=>e,i=typeof t=="function"?t:()=>t;return new Uc({execute:s=>qc(a(),i(),s,r),streamCall:l=>{var u=l,{reader:s}=u,o=V(u,["reader"]);return Vc(a(),i(),s,o,r)},onExecutionStart:n==null?void 0:n.onExecutionStart,onExecutionEnd:n==null?void 0:n.onExecutionEnd})}var Fi=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,i=dt.toResponse(e);this.threadApi.getState().addToolResult({messageId:r.id,toolName:n,toolCallId:a,result:i.result,artifact:i.artifact,isError:i.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 Or{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 i=this.binding.getState();i!==t&&(t=i,r==null||r(),r=(s=this.binding.getState())==null?void 0:s.subscribe(e),e())},a=this.outerSubscribe(n);return()=>{a==null||a(),r==null||r()}}},$r=Object.freeze({type:"complete"}),Jc=(e,t,r)=>{if(e.role!=="assistant")return $r;if(r.type==="tool-call")return r.result?$r:e.status;const n=t===Math.max(0,e.content.length-1);return e.status.type==="requires-action"?$r:n?e.status:$r},Bi=(e,t)=>{const r=e.content[t];if(!r)return Xe;const n=Jc(e,t,r);return Object.freeze(E(m({},r),{[Br]:r[Br],status:n}))},Kc=class{constructor(e,t){C(this,"composer");C(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=e,this._threadBinding=t,this.composer=new bc(new jr({path:E(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,i=this._core.getState();if(i.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:i.parentId,sourceId:i.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 i=t;if(e==="previous"?i=a[r.branchNumber-2]:e==="next"&&(i=a[r.branchNumber]),!i)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(i)}unstable_getCopyText(){return zr(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 Fi(new Qe({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.content[${e}]`,messagePartSelector:{type:"index",index:e}}),getState:()=>Bi(this.getState(),e),subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new Fi(new Qe({path:E(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?Xe:Bi(t,r)},subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new pc(new Qe({path:E(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?E(m({},r),{source:"message"}):Xe},subscribe:t=>this._core.subscribe(t)}))}},Yc=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}:{})},Gc=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:{}}},Xc=(e,t)=>{var r,n,a,i,s,o,l,u,c,d,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=(s=t.parentId)!=null?s:(i=e.at(-1))==null?void 0:i.id)!=null?o:null,sourceId:(l=t.sourceId)!=null?l:null,role:(u=t.role)!=null?u:"user",content:t.content,attachments:(c=t.attachments)!=null?c:[],metadata:(d=t.metadata)!=null?d:{custom:{}},runConfig:(f=t.runConfig)!=null?f:{},startRun:t.startRun}},Qc=(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})},zi=class{constructor(e,t){C(this,"_threadBinding");C(this,"composer");C(this,"_eventSubscriptionSubjects",new Map);const r=new Qe({path:e.path,getState:()=>Qc(e.getState(),t.getState()),subscribe:n=>{const a=e.subscribe(n),i=t.subscribe(n);return()=>{a(),i()}}});this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>r.getState(),outerSubscribe:n=>e.outerSubscribe(n),subscribe:n=>e.subscribe(n)},this.composer=new yc(new jr({path:E(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(Xc(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(Gc(t))}unstable_resumeRun(e){return this._threadBinding.getState().resumeRun(Yc(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(E(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(E(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 Kc(new Qe({path:e,getState:()=>{var c,d;const{message:r,parentId:n,index:a}=(c=t())!=null?c:{},{messages:i,speech:s}=this._threadBinding.getState();if(!r||n===void 0||a===void 0)return Xe;const l=this._threadBinding.getState().getBranches(r.id),u=r.metadata.submittedFeedback;return E(m({},r),{[Br]:r[Br],index:a,isLast:((d=i.at(-1))==null?void 0:d.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 Ii({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}},Zc=e=>({mainThreadId:e.mainThreadId,newThread:e.newThreadId,threads:e.threadIds,archivedThreads:e.archivedThreadIds,isLoading:e.isLoading,threadItems:e.threadData}),Ur=(e,t)=>{if(t===void 0)return Xe;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}:Xe},ed=class{constructor(e,t=zi){C(this,"_getState");C(this,"_mainThreadListItemRuntime");C(this,"main");this._core=e,this._runtimeFactory=t;const r=new Ln({path:{},getState:()=>Zc(e),subscribe:n=>e.subscribe(n)});this._getState=r.getState.bind(r),this._mainThreadListItemRuntime=new Fr(new Qe({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>Ur(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 Fr(new Qe({path:{ref:`threadItems[${e}]`,threadSelector:{type:"index",index:e}},getState:()=>Ur(this._core,this._core.threadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getArchivedItemByIndex(e){return new Fr(new Qe({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:"archiveIndex",index:e}},getState:()=>Ur(this._core,this._core.archivedThreadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getItemById(e){return new Fr(new Qe({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>Ur(this._core,e),subscribe:t=>this._core.subscribe(t)}),this._core)}},td=e=>e.startsWith("image/")?"image":e.startsWith("text/")?"document":"file",rd=class{constructor(e){C(this,"accept","*");C(this,"uploadedUrls",new Map);this.cloud=e}add(t){return Mr(this,arguments,function*({file:e}){const r=crypto.randomUUID(),n=td(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:i,publicUrl:s}=yield new Ge(this.cloud.files.generatePresignedUploadUrl({filename:e.name}));yield new Ge(fetch(i,{method:"PUT",body:e,headers:{"Content-Type":e.type},mode:"cors"})),this.uploadedUrls.set(r,s),a=E(m({},a),{status:{type:"requires-action",reason:"composer-send"}}),yield a}catch(i){a=E(m({},a),{status:{type:"incomplete",reason:"error"}}),yield a}})}remove(e){return P(this,null,function*(){this.uploadedUrls.delete(e.id)})}send(e){return P(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}],E(m({},e),{status:{type:"complete"},content:r})})}},Dn=y.createContext(null),On=({adapters:e,children:t})=>{const r=y.useContext(Dn);return p.jsx(Dn.Provider,{value:m(m({},r),e),children:t})},nd=()=>y.useContext(Dn),ad=class extends ui{constructor(t,r,{parentId:n,message:a}){var i;super();C(this,"_nonTextParts");C(this,"_previousText");C(this,"_parentId");C(this,"_sourceId");this.runtime=t,this.endEditCallback=r,this._parentId=n,this._sourceId=a.id,this._previousText=zr(a),this.setText(this._previousText),this.setRole(a.role),this.setAttachments((i=a.attachments)!=null?i:[]),this._nonTextParts=a.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 P(this,null,function*(){zr(t)!==this._previousText&&this.runtime.append(E(m({},t),{content:[...t.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId})),this.handleCancel()})}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},id=class{constructor(e){C(this,"_subscriptions",new Set);C(this,"_isInitialized",!1);C(this,"repository",new _i);C(this,"composer",new ci(this));C(this,"_editComposers",new Map);C(this,"_stopSpeaking");C(this,"speech");C(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 ad(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 i;const r=(i=this.adapters)==null?void 0:i.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 s=E(m({},n),{metadata:E(m({},n.metadata),{submittedFeedback:{type:t}})});this.repository.addOrUpdateMessage(a,s)}this._notifySubscribers()}speak(e){var i,s;const t=(i=this.adapters)==null?void 0:i.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(zr(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(Nn.fromArray(e!=null?e:[]))}unstable_on(e,t){var n,a,i;if(e==="model-context-update")return(i=(a=(n=this._contextProvider).subscribe)==null?void 0:a.call(n,t))!=null?i:(()=>{});const r=this._eventSubscribers.get(e);return r?r.add(t):this._eventSubscribers.set(e,new Set([t])),()=>{this._eventSubscribers.get(e).delete(t)}}},sd=e=>{try{return JSON.parse(e),!0}catch(t){return!1}};function od({state:e,getTools:t,onResult:r,setToolStatuses:n}){const a=y.useRef({}),i=y.useRef(new Map),s=y.useRef(new AbortController),o=y.useRef(0),l=y.useRef([]),[u]=y.useState(()=>{const[h,g]=Si(),k=Wc(t,()=>{var w,b;return(b=(w=s.current)==null?void 0:w.signal)!=null?b:new AbortController().signal},(w,b)=>new Promise((I,T)=>{const B=i.current.get(w);B&&B.reject(new Error("Human input request was superseded by a new request")),i.current.set(w,{resolve:I,reject:T}),n(F=>E(m({},F),{[w]:{type:"interrupt",payload:{type:"human",payload:b}}}))}),{onExecutionStart:w=>{o.current++,n(b=>E(m({},b),{[w]:{type:"executing"}}))},onExecutionEnd:w=>{o.current--,n(b=>{const I=m({},b);return delete I[w],I}),o.current===0&&(l.current.forEach(b=>b()),l.current=[])}});return h.pipeThrough(k).pipeThrough(new vi).pipeTo(new WritableStream({write(w){var b;if(w.type==="result"){if((b=a.current[w.meta.toolCallId])!=null&&b.hasResult)return;r(m({type:"add-tool-result",toolCallId:w.meta.toolCallId,toolName:w.meta.toolName,result:w.result,isError:w.isError},w.artifact&&{artifact:w.artifact}))}}})),g}),c=y.useRef(new Set),d=y.useRef(!0);y.useEffect(()=>{const h=g=>{g.forEach(k=>{k.content.forEach(w=>{if(w.type==="tool-call"){if(d.current)c.current.add(w.toolCallId);else{if(c.current.has(w.toolCallId))return;let b=a.current[w.toolCallId];if(b||(b={argsText:"",hasResult:!1,argsComplete:!1,controller:u.addToolCallPart({toolName:w.toolName,toolCallId:w.toolCallId})},a.current[w.toolCallId]=b),w.argsText!==b.argsText)if(b.argsComplete)process.env.NODE_ENV!=="production"&&console.warn("argsText updated after controller was closed:",{previous:b.argsText,next:w.argsText});else{if(!w.argsText.startsWith(b.argsText))throw new Error(`Tool call argsText can only be appended, not updated: ${w.argsText} does not start with ${b.argsText}`);const I=w.argsText.slice(b.argsText.length);b.controller.argsText.append(I);const T=sd(w.argsText);T&&b.controller.argsText.close(),a.current[w.toolCallId]={argsText:w.argsText,hasResult:b.hasResult,argsComplete:T,controller:b.controller}}w.result!==void 0&&!b.hasResult&&(b.controller.setResponse(new dt({result:w.result,artifact:w.artifact,isError:w.isError})),b.controller.close(),a.current[w.toolCallId]={hasResult:!0,argsComplete:!0,argsText:b.argsText,controller:b.controller})}w.messages&&h(w.messages)}})})};h(e.messages),d.current&&(d.current=!1)},[e,u,r]);const f=()=>(i.current.forEach(({reject:h})=>{h(new Error("Tool execution aborted"))}),i.current.clear(),s.current.abort(),s.current=new AbortController,o.current===0?Promise.resolve():new Promise(h=>{l.current.push(h)}));return{reset:()=>{f(),d.current=!0},abort:f,resume:(h,g)=>{const k=i.current.get(h);if(k)i.current.delete(h),n(w=>E(m({},w),{[h]:{type:"executing"}})),k.resolve(g);else throw new Error(`Tool call ${h} is not waiting for human input`)}}}var ld=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 ud(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 i=!0;if(a.deps!==void 0&&r.deps!==void 0&&(i=a.deps.length!==r.deps.length||a.deps.some((s,o)=>!Object.is(s,r.deps[o]))),i){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 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}`);a.mounted=!0,a.cleanup=typeof s=="function"?s:void 0,a.deps=r.deps}catch(s){throw s}}})}function cd(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 ir=null;function dd(e,t){e.currentIndex=0;const r=ir;ir=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{ir=r}}function Fn(){if(!ir)throw new Error("No resource fiber available");return ir}function Ri(e,t){const r=e[ji];if(!r)throw new Error("ResourceElement.type is not a valid Resource");return r(t)}var ji=Symbol("fnSymbol");function Hr(e,t){return{resource:e,scheduleRerender:t,cells:[],currentIndex:0,renderContext:void 0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function Dt(e){e.isMounted=!1,cd(e)}function sr(e,t){const r={commitTasks:[],props:t,state:void 0};return dd(e,()=>{e.renderContext=r;try{r.state=Ri(e.resource,t)}finally{e.renderContext=void 0}}),r}function Ot(e,t){e.isMounted=!0,e.isNeverMounted=!1,ud(t,e)}var hd=globalThis.__ASSISTANT_UI_DISABLE_LAYOUT_EFFECT__===!0,$i=hd?y.useEffect:y.useLayoutEffect;function Bn(e){const[,t]=y.useState({}),r=y.useMemo(()=>Hr(e.type,()=>t({})),[e.type,t]),n=sr(r,e.props);return $i(()=>()=>Dt(r),[]),$i(()=>{Ot(r,n)}),n.state}var Ft=e=>typeof e=="string"?{scope:e.split(".")[0],event:e}:{scope:e.scope,event:e.event},kt=(e,t,r)=>t===e,Bt,zn=()=>{if(Bt)return Bt;const e=()=>({apis:new Map,nextId:0,listeners:new Set});if(typeof window=="undefined")return Bt=e(),Bt;const t=window.__ASSISTANT_UI_DEVTOOLS_HOOK__;if(t)return Bt=t,t;const r=e();return window.__ASSISTANT_UI_DEVTOOLS_HOOK__=r,Bt=r,r},fd=(rt=class{static register(t){var o,l;const r=zn();for(const u of r.apis.values())if(u.api===t)return()=>{};const n=r.nextId++,a={api:t,logs:[]},i=(o=t.on)==null?void 0:o.call(t,"*",u=>{const c=r.apis.get(n);c&&(c.logs.push({time:new Date,event:u.event,data:u.payload}),c.logs.length>rt.MAX_EVENT_LOGS_PER_API&&(c.logs=c.logs.slice(-200)),rt.notifyListeners(n))}),s=(l=t.subscribe)==null?void 0:l.call(t,()=>{rt.notifyListeners(n)});return r.apis.set(n,a),rt.notifyListeners(n),()=>{const u=zn();u.apis.get(n)&&(i==null||i(),s==null||s(),u.apis.delete(n),rt.notifyListeners(n))}}static notifyListeners(t){zn().listeners.forEach(n=>n(t))}},C(rt,"MAX_EVENT_LOGS_PER_API",200),rt);function pe(e){const t=(r,n)=>m({type:t,props:r},(n==null?void 0:n.key)!==void 0&&{key:n.key});return t[ji]=e,t}var pd=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 md(e){const t=Fn(),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 i={type:"state",value:typeof e=="function"?e():e,set:s=>{const o=i.value,l=typeof s=="function"?s(o):s;Object.is(o,l)||(i.value=l,pd(t))}};t.cells[r]=i}const n=t.cells[r];if(n.type!=="state")throw new Error("Hook order changed between renders");return n}function it(e){const t=md(e);return[t.value,t.set]}function gd(){const e=Fn(),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 Pe(e,t){const r=Fn(),n=gd();r.renderContext.commitTasks.push({effect:e,deps:t,cellIndex:n})}function zt(e){const[t]=it(()=>({current:e}));return t}var yd=(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},le=(e,t)=>{const r=zt();return r.current||(r.current={value:e(),deps:t}),yd(r.current.deps,t)||(r.current.value=e(),r.current.deps=t),r.current.value};function qr(e,t){const[r,n]=it({}),a=le(()=>Hr(e.type,()=>n({})),[e.type]),i=t?le(()=>e.props,t):e.props,s=le(()=>sr(a,i),[a,i,r]);return Pe(()=>()=>Dt(a),[a]),Pe(()=>{Ot(a,s)},[a,s]),s.state}function Ze(e){return Ri(e.type,e.props)}function Ui(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({}),a=le(()=>new Map(e.map(o=>[o.key,o])),[e]),[i]=it(()=>new Map),s=le(()=>{const o=new Map,l=new Set;return a.forEach((u,c)=>{l.add(c);let d=i.get(c);(!d||d.resource!==u.type)&&(d&&Dt(d),d=Hr(u.type,()=>n({})),i.set(c,d));const f=sr(d,u.props);o.set(c,f)}),i.forEach((u,c)=>{l.has(c)||(Dt(u),i.delete(c))}),o},[a,r]);return Pe(()=>{s.forEach((o,l)=>{const u=i.get(l);u&&Ot(u,o)})},[s,i]),Pe(()=>()=>{i.forEach(o=>{Dt(o)}),i.clear()},[i]),le(()=>e.map(o=>{var l;return(l=s.get(o.key))==null?void 0:l.state}),[e,s])}var Rn=[],jn=!1;function bd(){jn=!1;const e=Rn;Rn=[];for(const t of e)try{t()}catch(r){console.error("Error in scheduled task:",r)}}function wd(e){Rn.push(e),jn||(jn=!0,queueMicrotask(bd))}var xd=(Mt=class{constructor(t){C(this,"_isDirty",!1);C(this,"_hasScheduledTask",!1);C(this,"_isFlushing",!1);this._task=t}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,!(this._hasScheduledTask||this._isFlushing)&&(this._hasScheduledTask=!0,wd(()=>{this._hasScheduledTask=!1,this.flushSync()}))}flushSync(){if(this._isFlushing)return;this._isFlushing=!0;let t=0;try{for(;this._isDirty;){if(t++,t>Mt.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}}},C(Mt,"MAX_FLUSH_DEPTH",50),Mt),vd=pe(({element:e,onUpdateInput:t,onFlushSync:r,onDispose:n})=>{const[a,i]=it(e.props),s=Ze({type:e.type,props:a}),o=zt(new Set).current,l=zt(s);return Pe(()=>{s!==l.current&&(l.current=s,o.forEach(c=>c()))}),le(()=>({getState:()=>l.current,subscribe:c=>(o.add(c),()=>o.delete(c)),updateInput:c=>{t(),i(()=>c)},flushSync:r,dispose:n}),[])}),kd=(e,t=!1)=>{let r=!t;const n={element:e,onUpdateInput:()=>{r||(r=!0,Ot(i,s))},onFlushSync:()=>{a.flushSync()},onDispose:()=>Dt(i)},a=new xd(()=>{s=sr(i,n),r&&Ot(i,s)}),i=Hr(vd,()=>a.markDirty());let s=sr(i,n);return r&&Ot(i,s),s.state},or=Symbol("tap.Context"),Hi=e=>({[or]:e}),qi=(e,t,r)=>{const n=e[or];e[or]=t;try{return r()}finally{e[or]=n}},Vi=e=>e[or];const Wi=e=>{let t;const r=new Set,n=(u,c)=>{const d=typeof u=="function"?u(t):u;if(!Object.is(d,t)){const f=t;t=(c!=null?c:typeof d!="object"||d===null)?d:Object.assign({},t,d),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},Sd=(e=>e?Wi(e):Wi),_d=e=>e;function Td(e,t=_d){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 Ji=e=>{const t=Sd(e),r=n=>Td(t,n);return Object.assign(r,t),r},Rt=(e=>e?Ji(e):Ji);function Ki(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Yi(...e){return t=>{let r=!1;const n=e.map(a=>{const i=Ki(a,t);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let a=0;a<n.length;a++){const i=n[a];typeof i=="function"?i():Ki(e[a],null)}}}}function Vr(...e){return G.useCallback(Yi(...e),e)}var Gi=pe(e=>{const t=le(()=>kd(e,!0),[e.type]);return Pe(()=>{t.updateInput(e.props)}),t}),Cd=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}},et=(e,t)=>{const r=zt(e);Pe(()=>{r.current=e});const n=le(()=>new Proxy({},new Cd(()=>r.current)),[]),a=t==null?void 0:t.key,i=e.getState();return le(()=>({key:a,state:i,api:n}),[i,a])},ht=pe(e=>{const t=zt(e.get);return Pe(()=>{t.current=e.get}),le(()=>Ie({source:e.source,query:e.query,get:()=>t.current()}),[e.source,JSON.stringify(e.query)])}),Id=pe(e=>{const t=qr(e.scopeElement);return le(()=>[e.fieldName,t],[e.fieldName,t])}),Ed=pe(e=>{const o=e,{on:t,subscribe:r,flushSync:n}=o,a=V(o,["on","subscribe","flushSync"]),i=zt({on:t,subscribe:r,flushSync:n});Pe(()=>{i.current={on:t,subscribe:r,flushSync:n}});const s=Ui(Object.entries(a).map(([l,u])=>Id({fieldName:l,scopeElement:u},{key:l})));return le(()=>{const l=Object.fromEntries(s),{on:u,subscribe:c,flushSync:d}=i.current;return u&&(l.on=(f,h)=>u(f,h)),c&&(l.subscribe=f=>c(f)),d&&(l.flushSync=()=>d()),l},[...s])}),Xi=Hi(null),Ad=(e,t)=>qi(Xi,e,t),Qi=()=>{const e=Vi(Xi);if(!e)throw new Error("Model context is not available in this context");return e},Md=pe(({toolkit:e})=>{const[t,r]=it(()=>({tools:{}})),n=Qi();Pe(()=>{if(!e)return;const i=[];for(const[l,u]of Object.entries(e))u.render&&i.push(a(l,u.render));const s=Object.entries(e).reduce((l,[u,c])=>{const h=c,{render:d}=h,f=V(h,["render"]);return l[u]=f,l},{}),o={getModelContext:()=>({tools:s})};return i.push(n.register(o)),()=>{i.forEach(l=>l())}},[e,n]);const a=(i,s)=>(r(o=>{var l;return E(m({},o),{tools:E(m({},o.tools),{[i]:[...(l=o.tools[i])!=null?l:[],s]})})}),()=>{r(o=>{var l,u;return E(m({},o),{tools:E(m({},o.tools),{[i]:(u=(l=o.tools[i])==null?void 0:l.filter(c=>c!==s))!=null?u:[]})})})});return et({getState:()=>t,setToolUI:a})}),Pd=pe(()=>le(()=>{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),i=t.get("*");!a&&!i||queueMicrotask(()=>{if(a)for(const s of a)s(n);if(i)for(const s of i)s({event:r,payload:n})})}}},[])),Zi=Hi(null),Nd=(e,t)=>qi(Zi,e,t),$n=()=>{const e=Vi(Zi);if(!e)throw new Error("Events context is not available");return e},Ld=pe(()=>{const[e]=it(()=>({})),t=new Cn;return et({getState:()=>e,getModelContext:()=>t.getModelContext(),subscribe:r=>t.subscribe(r),register:r=>t.registerModelContextProvider(r)})}),Dd=pe(({threads:e,modelContext:t,tools:r})=>{const n=Ze(Pd()),{threads:a,tools:i,modelContext:s}=Nd(n,()=>{const l=qr(t!=null?t:Ld(),[t]);return Ad(l.api,()=>({modelContext:l,tools:qr(r!=null?r:Md({}),[r]),threads:qr(e,[e])}))}),o=le(()=>({threads:a.state,tools:i.state,modelContext:s.state}),[a.state,i.state,s.state]);return et({getState:()=>o,threads:a.api,tools:i.api,modelContext:s.api,on:n.on})}),Od=e=>{const t=()=>e.getState().api.threads.item("main");return{threads:Ie({source:"root",query:{},get:()=>e.getState().api.threads}),tools:Ie({source:"root",query:{},get:()=>e.getState().api.tools}),modelContext:Ie({source:"root",query:{},get:()=>e.getState().api.modelContext}),thread:Ie({source:"threads",query:{type:"main"},get:()=>e.getState().api.threads.thread("main")}),threadListItem:Ie({source:"threads",query:{type:"main"},get:()=>t()}),composer:Ie({source:"thread",query:{},get:()=>e.getState().api.threads.thread("main").composer}),on(r,n){const{event:a,scope:i}=Ft(r);if(i==="*")return e.getState().api.on(a,n);if(kt("thread",i)||kt("thread-list-item",i)||kt("composer",i))return e.getState().api.on(a,s=>{s.threadId===t().getState().id&&n(s)});throw new Error(`Event scope is not available in this component: ${i}`)},subscribe:e.subscribe,flushSync:e.flushSync}},Fd=e=>{const t=Wr(),r=Bn(Gi(Dd(e))),n=y.useMemo(()=>Od(r),[r]);return y.useMemo(()=>ts(t,n),[t,n])},Ie=e=>{const t=e.get;return t.source=e.source,t.query=e.query,t},ft=()=>()=>{},es=y.createContext({threads:Ie({source:null,query:{},get:()=>{throw new Error("Threads is only available inside <AssistantProvider />")}}),tools:Ie({source:null,query:{},get:()=>{throw new Error("Tools is only available inside <AssistantProvider />")}}),modelContext:Ie({source:null,query:{},get:()=>{throw new Error("ModelContext is only available inside <AssistantProvider />")}}),threadListItem:Ie({source:null,query:{},get:()=>{throw new Error("ThreadListItem is only available inside <AssistantProvider />")}}),thread:Ie({source:null,query:{},get:()=>{throw new Error("Thread is only available inside <AssistantProvider />")}}),composer:Ie({source:null,query:{},get:()=>{throw new Error("Composer is only available inside <AssistantProvider />")}}),message:Ie({source:null,query:{},get:()=>{throw new Error("Message is only available inside <ThreadPrimitive.Messages />")}}),part:Ie({source:null,query:{},get:()=>{throw new Error("Part is only available inside <MessagePrimitive.Parts />")}}),attachment:Ie({source:null,query:{},get:()=>{throw new Error("Attachment is only available inside <MessagePrimitive.Attachments /> or <ComposerPrimitive.Attachments />")}}),subscribe:ft,flushSync:ft,on:e=>{const{scope:t}=Ft(e);throw new Error(`Event scope is not available in this component: ${t}`)}}),Wr=()=>y.useContext(es),St=e=>{const t=Wr(),r=Bn(Ed(e));return y.useMemo(()=>ts(t,r),[t,r])},Bd=e=>Fd(e);function he(e){return e?Bd(e):Wr()}var zd=(e,t)=>e===ft?t:t===ft?e:(...r)=>{e(...r),t(...r)},Rd=(e,t)=>e===ft?t:t===ft?e:(...r)=>{const n=e(...r),a=t(...r);return()=>{n(),a()}},ts=(e,t)=>{const r=t.subscribe,n=t.flushSync;return E(m(m({},e),t),{subscribe:Rd(e.subscribe,r!=null?r:ft),flushSync:zd(e.flushSync,n!=null?n:ft)})},pt=({api:e,children:t,devToolsVisible:r=!0})=>(y.useEffect(()=>{if(!(!r||!e.subscribe))return fd.register(e)},[e,r]),p.jsx(es.Provider,{value:e,children:t})),rs=(vu=class{constructor(e){Xt(this,Je);Qt(this,Je,e)}get threads(){return qe(this,Je).threads().getState()}get tools(){return qe(this,Je).tools().getState()}get threadListItem(){return qe(this,Je).threadListItem().getState()}get thread(){return qe(this,Je).thread().getState()}get composer(){return qe(this,Je).composer().getState()}get message(){return qe(this,Je).message().getState()}get part(){return qe(this,Je).part().getState()}get attachment(){return qe(this,Je).attachment().getState()}},Je=new WeakMap,vu),re=e=>{const t=he(),r=y.useMemo(()=>new rs(t),[t]),n=y.useSyncExternalStore(t.subscribe,()=>e(r),()=>e(r));if(y.useDebugValue(n),n instanceof rs)throw new Error("You tried to return the entire AssistantState. This is not supported due to technical limitations.");return n},Un=(e,t)=>{const r=he(),n=y.useRef(t);y.useEffect(()=>{n.current=t});const{scope:a,event:i}=Ft(e);y.useEffect(()=>r.on({scope:a,event:i},s=>n.current(s)),[r,a,i])};function jd(e,t){function r(n){const a=y.useContext(e);if(!(n!=null&&n.optional)&&!a)throw new Error(`This component must be used within ${t}.`);return a}return r}function ns(e,t){function r(a){const i=e(a);return i?i[t]:null}function n(a){let i=!1,s;typeof a=="function"?s=a:a&&typeof a=="object"&&(i=!!a.optional,s=a.selector);const o=r({optional:i});return o?s?o(s):o():null}return{[t]:n,[`${t}Store`]:r}}var as=y.createContext(null),$d=jd(as,"ThreadPrimitive.Viewport"),{useThreadViewport:Jr,useThreadViewportStore:Hn}=ns($d,"useThreadViewport"),Ud=e=>{var r;const t=e;t.__isBound||((r=t.__internal_bindMethods)==null||r.call(t),t.__isBound=!0)};function Hd(e,t=qd){Ud(e);const r=y.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getState()));return y.useDebugValue(r),r}var qd=e=>e;function is(e){function t(r){let n=!1,a;typeof r=="function"?a=r:r&&(n=!!r.optional,a=r.selector);const i=e({optional:n});return i?Hd(i,a):null}return t}function ss(e){const t=he(),r=re(()=>{var n,a,i;return t.thread.source&&(i=(a=(n=t.thread()).__internal_getRuntime)==null?void 0:a.call(n))!=null?i:null});if(!r&&!(e!=null&&e.optional))throw new Error("ThreadRuntime is not available");return r}var Vd=is(ss);function Wd(e){const t=he(),r=re(()=>{var n,a,i;return t.threadListItem.source&&(i=(a=(n=t.threadListItem()).__internal_getRuntime)==null?void 0:a.call(n))!=null?i:null});if(!r&&!(e!=null&&e.optional))throw new Error("ThreadListItemRuntime is not available");return r}var os=is(Wd),_t=e=>{const[,t]=it(e.getState);return Pe(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},Jd=pe(({runtime:e})=>{const t=_t(e),r=$n();return Pe(()=>{const n=[],a=["switched-to","switched-away"];for(const i of a){const s=e.unstable_on(i,()=>{r.emit(`thread-list-item.${i}`,{threadId:e.getState().id})});n.push(s)}return()=>{for(const i of n)i()}},[e,r]),et({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})}),lr=e=>{const t=Ui(e);return{state:t.map(r=>r.state),api:r=>{var a,i;const n="index"in r?(a=t[r.index])==null?void 0:a.api:(i=t.find(s=>s.key===r.key))==null?void 0:i.api;if(!n)throw new Error(`tapLookupResources: Resource not found for lookup: ${JSON.stringify(r)}`);return n}}},ls=pe(({runtime:e})=>{const t=_t(e);return et({getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e},{key:t.id})}),Kd=pe(({runtime:e,index:t})=>{const r=le(()=>e.getAttachmentByIndex(t),[e,t]);return Ze(ls({runtime:r}))}),us=pe(({threadIdRef:e,messageIdRef:t,runtime:r})=>{var o;const n=_t(r),a=$n();Pe(()=>{const l=[],u=["send","attachment-add"];for(const c of u){const d=r.unstable_on(c,()=>{a.emit(`composer.${c}`,m({threadId:e.current},t&&{messageId:t.current}))});l.push(d)}return()=>{for(const c of l)c()}},[r,a,e,t]);const i=lr(n.attachments.map((l,u)=>Kd({runtime:r,index:u},{key:u}))),s=le(()=>{var l;return{text:n.text,role:n.role,attachments:i.state,runConfig:n.runConfig,isEditing:n.isEditing,canCancel:n.canCancel,attachmentAccept:n.attachmentAccept,isEmpty:n.isEmpty,type:(l=n.type)!=null?l:"thread"}},[n,i.state]);return et({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?i.api({key:l.id}):i.api(l),__internal_getRuntime:()=>r})}),Yd=pe(({runtime:e})=>{const t=_t(e);return et({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})}),Gd=pe(({runtime:e,index:t})=>{const r=le(()=>e.getAttachmentByIndex(t),[e,t]);return Ze(ls({runtime:r}))}),Xd=pe(({runtime:e,index:t})=>{const r=le(()=>e.getMessagePartByIndex(t),[e,t]);return Ze(Yd({runtime:r}))}),Qd=pe(({runtime:e,threadIdRef:t})=>{var f,h;const r=_t(e),[n,a]=it(!1),[i,s]=it(!1),o=le(()=>({get current(){return e.getState().id}}),[e]),l=Ze(us({runtime:e.composer,threadIdRef:t,messageIdRef:o})),u=lr(r.content.map((g,k)=>Xd({runtime:e,index:k},{key:k}))),c=lr((h=(f=r.attachments)==null?void 0:f.map((g,k)=>Gd({runtime:e,index:k},{key:k})))!=null?h:[]),d=le(()=>E(m({},r),{parts:u.state,composer:l.state,isCopied:n,isHovering:i}),[r,u.state,l.state,n,i]);return et({getState:()=>d,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?c.api({key:g.id}):c.api(g),setIsCopied:a,setIsHovering:s,__internal_getRuntime:()=>e},{key:r.id})}),Zd=pe(({runtime:e,id:t,threadIdRef:r})=>{const n=le(()=>e.getMessageById(t),[e,t]);return Ze(Qd({runtime:n,threadIdRef:r}))}),eh=pe(({runtime:e})=>{const t=_t(e),r=$n();Pe(()=>{const o=[],l=["run-start","run-end","initialize","model-context-update"];for(const u of l){const c=e.unstable_on(u,()=>{var f;const d=((f=e.getState())==null?void 0:f.threadId)||"unknown";r.emit(`thread.${u}`,{threadId:d})});o.push(c)}return()=>{for(const u of o)u()}},[e]);const n=le(()=>({get current(){return e.getState().threadId}}),[e]),a=Ze(us({runtime:e.composer,threadIdRef:n})),i=lr(t.messages.map(o=>Zd({runtime:e,id:o.id,threadIdRef:n},{key:o.id}))),s=le(()=>({isEmpty:i.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:i.state}),[t,i,a.state]);return et({getState:()=>s,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:()=>P(null,null,function*(){throw new Error("startVoice is not supported in this runtime")}),stopVoice:()=>P(null,null,function*(){throw new Error("stopVoice is not supported in this runtime")}),message:o=>"id"in o?i.api({key:o.id}):i.api(o),__internal_getRuntime:()=>e})}),th=pe(({runtime:e,id:t})=>{const r=le(()=>e.getItemById(t),[e,t]);return Ze(Jd({runtime:r}))}),rh=pe(({runtime:e,__internal_assistantRuntime:t})=>{const r=_t(e),n=Ze(eh({runtime:e.main})),a=lr(Object.keys(r.threadItems).map(s=>th({runtime:e,id:s},{key:s}))),i=le(()=>{var s;return{mainThreadId:r.mainThreadId,newThreadId:(s=r.newThread)!=null?s:null,isLoading:r.isLoading,threadIds:r.threads,archivedThreadIds:r.archivedThreads,threadItems:a.state,main:n.state}},[r,a.state,n.state]);return et({getState:()=>i,thread:()=>n.api,item:s=>{if(s==="main")return a.api({key:i.mainThreadId});if("id"in s)return a.api({key:s.id});const{index:o,archived:l=!1}=s,u=l?i.archivedThreadIds[o]:i.threadIds[o];return a.api({key:u})},switchToThread:s=>{e.switchToThread(s)},switchToNewThread:()=>{e.switchToNewThread()},__internal_getAssistantRuntime:()=>t})}),nh=pe(e=>{const t=Qi();return Pe(()=>e.registerModelContextProvider(t),[e,t]),Ze(rh({runtime:e.threads,__internal_assistantRuntime:e}))}),qn=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()}}}}},ah=(e={})=>{const t=new Set,r=qn(s=>{i.setState({height:E(m({},i.getState().height),{viewport:s})})}),n=qn(s=>{i.setState({height:E(m({},i.getState().height),{inset:s})})}),a=qn(s=>{i.setState({height:E(m({},i.getState().height),{userMessage:s})})}),i=Rt(()=>{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:a.register}});return i},ur=e=>e,ih=e=>{const t=Hn({optional:!0}),[r]=y.useState(()=>ah(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&&ur(t).setState({isAtBottom:n.isAtBottom})})},[r,t]),y.useEffect(()=>{var i;const n={turnAnchor:(i=e.turnAnchor)!=null?i:"bottom"};r.getState().turnAnchor!==n.turnAnchor&&ur(r).setState(n)},[r,e.turnAnchor]),r},cs=({children:e,options:t={}})=>{const r=ih(t),[n]=y.useState(()=>({useThreadViewport:r}));return p.jsx(as.Provider,{value:n,children:e})},sh=e=>{var t;return(t=e._core)==null?void 0:t.RenderComponent},oh=({children:e,runtime:t})=>{const r=he({threads:nh(t)}),n=sh(t);return p.jsxs(pt,{api:r,children:[n&&p.jsx(n,{}),p.jsx(cs,{children:e})]})},ds=y.memo(oh),lh=({index:e,archived:t,children:r})=>{const n=he(),a=St({threadListItem:ht({source:"threads",query:{type:"index",index:e,archived:t},get:()=>n.threads().item({index:e,archived:t})}),on(i,s){const o=()=>n.threads().item({index:e,archived:t}),{event:l,scope:u}=Ft(i);return kt("thread-list-item",u)?n.on({scope:"*",event:l},c=>{c.threadId===o().getState().id&&s(c)}):n.on(i,s)}});return p.jsx(pt,{api:a,children:r})},uh=({id:e,children:t})=>{const r=he(),n=St({threadListItem:ht({source:"threads",query:{type:"id",id:e},get:()=>r.threads().item({id:e})}),on(a,i){const s=()=>r.threads().item({id:e}),{event:o,scope:l}=Ft(a);return kt("thread-list-item",l)?r.on({scope:"*",event:o},u=>{u.threadId===s().getState().id&&i(u)}):r.on(a,i)}});return p.jsx(pt,{api:n,children:t})},ch=({index:e,children:t})=>{const r=he(),n=St({message:ht({source:"thread",query:{type:"index",index:e},get:()=>r.thread().message({index:e})}),composer:ht({source:"message",query:{},get:()=>r.thread().message({index:e}).composer}),on(a,i){const s=()=>r.thread().message({index:e}),{event:o,scope:l}=Ft(a);return!kt("composer",l)&&!kt("message",l)?r.on(a,i):r.on({scope:"thread",event:o},u=>{u.messageId===s().getState().id&&i(u)})}});return p.jsx(pt,{api:n,children:t})},dh=({index:e,children:t})=>{const r=he(),n=St({part:ht({source:"message",query:{type:"index",index:e},get:()=>r.message().part({index:e})})});return p.jsx(pt,{api:n,children:t})},hh=({index:e,children:t})=>{const r=he(),n=St({attachment:ht({source:"message",query:{type:"index",index:e},get:()=>r.message().attachment({index:e})})});return p.jsx(pt,{api:n,children:t})},fh=({index:e,children:t})=>{const r=he(),n=St({attachment:ht({source:"composer",query:{type:"index",index:e},get:()=>r.composer().attachment({index:e})})});return p.jsx(pt,{api:n,children:t})},ph=pe(({text:e,isRunning:t})=>{const r=le(()=>({type:"text",text:e,status:t?{type:"running"}:{type:"complete"}}),[e,t]);return et({getState:()=>r,addToolResult:()=>{throw new Error("Not supported")},resumeToolCall:()=>{throw new Error("Not supported")}})}),mh=({text:e,isRunning:t=!1,children:r})=>{const n=Bn(Gi(ph({text:e,isRunning:t}))),a=St({part:ht({source:"root",query:{},get:()=>n.getState().api}),subscribe:n.subscribe,flushSync:n.flushSync});return p.jsx(pt,{api:a,children:r})},hs=(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))},Vn=class extends Error{constructor(t,r){super(r);C(this,"name","AbortError");C(this,"detach");this.detach=t}},gh=class extends id{constructor(t,r){super(t);C(this,"capabilities",{switchToBranch:!0,switchBranchDuringRun:!0,edit:!0,reload:!0,cancel:!0,unstable_copy:!0,speech:!1,attachments:!1,feedback:!1});C(this,"abortController",null);C(this,"isDisabled",!1);C(this,"_isLoading",!1);C(this,"_suggestions",[]);C(this,"_suggestionsController",null);C(this,"_options");C(this,"_lastRunConfig",{});C(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 a=((o=t.adapters)==null?void 0:o.attachments)!==void 0;this.capabilities.attachments!==a&&(this.capabilities.attachments=a,r=!0);const i=((l=t.adapters)==null?void 0:l.feedback)!==void 0;this.capabilities.feedback!==i&&(this.capabilities.feedback=i,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 s,o;if(!a)return;this.repository.import(a),this._notifySubscribers();const i=(o=(s=this.adapters.history)==null?void 0:s.resume)==null?void 0:o.bind(this.adapters.history);a.unstable_resume&&i&&this.startRun({parentId:this.repository.headId,sourceId:this.repository.headId,runConfig:this._lastRunConfig},i)}).finally(()=>{this._isLoading=!1,this._notifySubscribers()}),this._loadPromise}append(t){return P(this,null,function*(){var a,i,s;this.ensureInitialized();const r=nr(t,xt(),{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})),((i=t.startRun)!=null?i: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 a=n,{stream:t}=a,r=V(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,i){return P(this,arguments,function*({parentId:t,runConfig:r},n){var u,c,d;this.ensureInitialized();let o={id:xt(),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(hs(o,this._options.unstable_humanToolNames))}finally{this._notifyEventSubscribers("run-end")}this._suggestionsController=new AbortController;const l=this._suggestionsController.signal;if(this.adapters.suggestion&&((c=o.status)==null?void 0:c.type)!=="requires-action"){const w=(d=this.adapters.suggestion)==null?void 0:d.generate({messages:this.messages});if(Symbol.asyncIterator in w)try{for(var f=Nt(w),h,g,k;h=!(g=yield f.next()).done;h=!1){const b=g.value;if(l.aborted)break;this._suggestions=b,this._notifySubscribers()}}catch(g){k=[g]}finally{try{h&&(g=f.return)&&(yield g.call(f))}finally{if(k)throw k[0]}}else{const b=yield w;if(l.aborted)return;this._suggestions=b,this._notifySubscribers()}}})}performRoundtrip(t,r,n,a){return P(this,null,function*(){var g,k,w,b,I,T,B,F,_,N;const i=t?this.repository.getMessages(t):[];(g=this.abortController)==null||g.abort(),this.abortController=new AbortController;const s=r.content,o=(k=r.metadata)==null?void 0:k.unstable_annotations,l=(w=r.metadata)==null?void 0:w.unstable_data,u=(b=r.metadata)==null?void 0:b.steps,c=(I=r.metadata)==null?void 0:I.custom,d=M=>{var me,x,Se,ve,v,U;const J=(me=M.metadata)==null?void 0:me.steps,z=J?[...u!=null?u:[],...J]:void 0,D=(x=M.metadata)==null?void 0:x.unstable_annotations,Y=(Se=M.metadata)==null?void 0:Se.unstable_data,ce=D?[...o!=null?o:[],...D]:void 0,se=Y?[...l!=null?l:[],...Y]:void 0;r=m(E(m(m({},r),M.content?{content:[...s,...(ve=M.content)!=null?ve:[]]}:void 0),{status:(v=M.status)!=null?v:r.status}),M.metadata?{metadata:m(m(m(m(m(m({},r.metadata),M.metadata.unstable_state?{unstable_state:M.metadata.unstable_state}:void 0),ce?{unstable_annotations:ce}:void 0),se?{unstable_data:se}:void 0),z?{steps:z}:void 0),(U=M.metadata)!=null&&U.custom?{custom:m(m({},c!=null?c:{}),M.metadata.custom)}:void 0)}:void 0),this.repository.addOrUpdateMessage(t,r),this._notifySubscribers()},f=(T=this._options.maxSteps)!=null?T:2;if(((_=(F=(B=r.metadata)==null?void 0:B.steps)==null?void 0:F.length)!=null?_:0)>=f)return d({status:{type:"incomplete",reason:"tool-calls"}}),r;d({status:{type:"running"}}),this.repository.resetHead(r.id),this._notifySubscribers();try{this._lastRunConfig=n!=null?n:{};const M=this.getModelContext();a=a!=null?a:this.adapters.chatModel.run.bind(this.adapters.chatModel);const J=this.abortController.signal,z=a({messages:i,runConfig:this._lastRunConfig,abortSignal:J,context:M,config:M,unstable_assistantMessageId:r.id,unstable_getMessage(){return r}});if(Symbol.asyncIterator in z)try{for(var $=Nt(z),R,j,S;R=!(j=yield $.next()).done;R=!1){const D=j.value;if(J.aborted){d({status:{type:"incomplete",reason:"cancelled"}});break}d(D)}}catch(j){S=[j]}finally{try{R&&(j=$.return)&&(yield j.call($))}finally{if(S)throw S[0]}}else d(yield z);r.status.type==="running"&&d({status:{type:"complete",reason:"unknown"}})}catch(M){if(M instanceof Vn)d({status:{type:"incomplete",reason:"cancelled"}});else throw d({status:{type:"incomplete",reason:"error",error:M instanceof Error?M.message:`[${typeof M}] ${new String(M).toString()}`}}),M}finally{this.abortController=null,(r.status.type==="complete"||r.status.type==="incomplete")&&(yield(N=this._options.adapters.history)==null?void 0:N.append({parentId:t,message:r,runConfig:this._lastRunConfig}))}return r})}detach(){var r;const t=new Vn(!0);(r=this.abortController)==null||r.abort(t),this.abortController=null}cancelRun(){var r;const t=new Vn(!1);(r=this.abortController)==null||r.abort(t),this.abortController=null}addToolResult({messageId:t,toolCallId:r,result:n,isError:a,artifact:i}){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,c=!1;const d=l.content.map(f=>f.type!=="tool-call"||f.toolCallId!==r?f:(c=!0,f.result||(u=!0),E(m({},f),{result:n,artifact:i,isError:a})));if(!c)throw new Error("Tried to add tool result to non-existing tool call");l=E(m({},l),{content:d}),this.repository.addOrUpdateMessage(o,l),u&&hs(l,this._options.unstable_humanToolNames)&&this.performRoundtrip(o,l,this._lastRunConfig)}resumeToolCall(t){throw new Error("Local runtime does not support resuming tool calls.")}},fs=Object.freeze([]),Wn="__DEFAULT_ID__",yh=Object.freeze({[Wn]:{id:Wn,remoteId:void 0,externalId:void 0,status:"regular",title:void 0}}),bh=class extends tr{constructor(t){super();C(this,"_mainThread");this._mainThread=t()}get isLoading(){return!1}getMainThreadRuntimeCore(){return this._mainThread}get newThreadId(){throw new Error("Method not implemented.")}get threadIds(){throw fs}get archivedThreadIds(){throw fs}get mainThreadId(){return Wn}get threadData(){return yh}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 P(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.")}},wh=class extends In{constructor(t,r){super();C(this,"threads");C(this,"Provider");C(this,"_options");this._options=t,this.threads=new bh(()=>new gh(this._contextProvider,this._options)),r&&this.threads.getMainThreadRuntimeCore().import(Nn.fromArray(r))}},ps=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),s=JSON.parse(a).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}`)}},ms=(ku=class{constructor(e){C(this,"strategy","jwt");C(this,"cachedToken",null);C(this,"tokenExpiry",null);Xt(this,_r);Qt(this,_r,e)}getAuthHeaders(){return P(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 qe(this,_r).call(this);return t?(this.cachedToken=t,this.tokenExpiry=ps(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=ps(n)}},_r=new WeakMap,ku),xh=(Su=class{constructor(e,t,r){C(this,"strategy","api-key");Xt(this,Tr);Xt(this,Cr);Xt(this,Ir);Qt(this,Tr,e),Qt(this,Cr,t),Qt(this,Ir,r)}getAuthHeaders(){return P(this,null,function*(){return{Authorization:`Bearer ${qe(this,Tr)}`,"Aui-User-Id":qe(this,Cr),"Aui-Workspace-Id":qe(this,Ir)}})}readAuthHeaders(){}},Tr=new WeakMap,Cr=new WeakMap,Ir=new WeakMap,Su),Kr="aui:refresh_token",vh=class{constructor(e){C(this,"strategy","anon");C(this,"baseUrl");C(this,"jwtStrategy");this.baseUrl=e,this.jwtStrategy=new ms(()=>P(this,null,function*(){const t=Date.now(),r=localStorage.getItem(Kr),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 c=yield u.json(),{access_token:d,refresh_token:f}=c;return f&&localStorage.setItem(Kr,JSON.stringify(f)),d}}else localStorage.removeItem(Kr);const a=yield fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:"POST"});if(!a.ok)return null;const i=yield a.json(),{access_token:s,refresh_token:o}=i;return!s||!o?null:(localStorage.setItem(Kr,JSON.stringify(o)),s)}))}getAuthHeaders(){return P(this,null,function*(){return this.jwtStrategy.getAuthHeaders()})}readAuthHeaders(e){this.jwtStrategy.readAuthHeaders(e)}},kh=class extends Error{constructor(e){super(e),this.name="APIError"}},Sh=class{constructor(e){C(this,"_auth");C(this,"_baseUrl");if("authToken"in e)this._baseUrl=e.baseUrl,this._auth=new ms(e.authToken);else if("apiKey"in e)this._baseUrl="https://backend.assistant-api.com",this._auth=new xh(e.apiKey,e.userId,e.workspaceId);else if("anonymous"in e)this._baseUrl=e.baseUrl,this._auth=new vh(e.baseUrl);else throw new Error("Invalid configuration: Must provide authToken, apiKey, or anonymous configuration")}initializeAuth(){return P(this,null,function*(){return!!this._auth.getAuthHeaders()})}makeRawRequest(r){return P(this,arguments,function*(e,t={}){var l;const n=yield this._auth.getAuthHeaders();if(!n)throw new Error("Authorization failed");const a=E(m(m({},n),t.headers),{"Content-Type":"application/json"}),i=new URLSearchParams;if(t.query)for(const[u,c]of Object.entries(t.query))c!==!1&&(c===!0?i.set(u,"true"):i.set(u,c.toString()));const s=new URL(`${this._baseUrl}/v1${e}`);s.search=i.toString();const o=yield fetch(s,{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 c=JSON.parse(u);throw new kh(c.message)}catch(c){throw new Error(`Request failed with status ${o.status}, ${u}`)}}return o})}makeRequest(r){return P(this,arguments,function*(e,t={}){return(yield this.makeRawRequest(e,t)).json()})}},_h=class{constructor(e){this.cloud=e}create(){return P(this,null,function*(){return this.cloud.makeRequest("/auth/tokens",{method:"POST"})})}},Th=class{constructor(e){this.cloud=e}__internal_getAssistantOptions(e){return{api:`${this.cloud._baseUrl}/v1/runs/stream`,headers:()=>P(this,null,function*(){const t=yield this.cloud._auth.getAuthHeaders();if(!t)throw new Error("Authorization failed");return E(m({},t),{Accept:"text/plain"})}),body:{assistant_id:e,response_format:"vercel-ai-data-stream/v1",thread_id:"unstable_todo"}}}stream(e){return P(this,null,function*(){const t=yield this.cloud.makeRawRequest("/runs/stream",{method:"POST",headers:{Accept:"text/plain"},body:e});return Mn.fromResponse(t,new Oc)})}},Ch=class{constructor(e){this.cloud=e}list(e,t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{query:t})})}create(e,t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{method:"POST",body:t})})}},Ih=class{constructor(e){C(this,"messages");this.cloud=e,this.messages=new Ch(e)}list(e){return P(this,null,function*(){return this.cloud.makeRequest("/threads",{query:e})})}get(e){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`)})}create(e){return P(this,null,function*(){return this.cloud.makeRequest("/threads",{method:"POST",body:e})})}update(e,t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"PUT",body:t})})}delete(e){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"DELETE"})})}},Eh=class{constructor(e){this.cloud=e}pdfToImages(e){return P(this,null,function*(){return this.cloud.makeRequest("/files/pdf-to-images",{method:"POST",body:e})})}generatePresignedUploadUrl(e){return P(this,null,function*(){return this.cloud.makeRequest("/files/attachments/generate-presigned-upload-url",{method:"POST",body:e})})}},Ah=class{constructor(e){C(this,"threads");C(this,"auth");C(this,"runs");C(this,"files");const t=new Sh(e);this.threads=new Ih(t),this.auth={tokens:new _h(t)},this.runs=new Th(t),this.files=new Eh(t)}};function Jn(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=>Jn(r,t+1)):typeof e=="object"?Object.entries(e).every(([r,n])=>typeof r=="string"&&Jn(n,t+1)):!1}var Mh=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 Jn(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)},Ph=e=>{const t=e.content,r=nr(m({id:e.id,createdAt:e.created_at},t),e.id,{type:"complete",reason:"unknown"});return{parentId:e.parent_id,message:r}},Kn=new WeakMap,Nh=class{constructor(e,t){this.parent=e,this.formatAdapter=t}append(e){return P(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 P(this,null,function*(){return this.parent._loadWithFormat(this.formatAdapter.format,e=>this.formatAdapter.decode(e))})}},Lh=class{constructor(e,t){this.cloudRef=e,this.store=t}get _getIdForLocalId(){return Kn.has(this.store.threadListItem())||Kn.set(this.store.threadListItem(),{}),Kn.get(this.store.threadListItem())}withFormat(e){return new Nh(this,e)}append(r){return P(this,arguments,function*({parentId:e,message:t}){var i;const{remoteId:n}=yield this.store.threadListItem().initialize(),a=this.cloudRef.current.threads.messages.create(n,{parent_id:e?(i=yield this._getIdForLocalId[e])!=null?i:e:null,format:"aui/v0",content:Mh(t)}).then(({message_id:s})=>(this._getIdForLocalId[t.id]=s,s));return this._getIdForLocalId[t.id]=a,a.then(()=>{})})}load(){return P(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(Ph).reverse()}})}_appendWithFormat(e,t,r,n){return P(this,null,function*(){var s;const{remoteId:a}=yield this.store.threadListItem().initialize(),i=this.cloudRef.current.threads.messages.create(a,{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]=i,i.then(()=>{})})}_loadWithFormat(e,t){return P(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()}})}},Dh=e=>{const t=he(),[r]=y.useState(()=>new Lh(e,t));return r},gs=typeof process!="undefined"&&((_u=process==null?void 0:process.env)==null?void 0:_u.NEXT_PUBLIC_ASSISTANT_BASE_URL),Yn=gs?new Ah({baseUrl:gs,anonymous:!0}):void 0,Oh=e=>{var a;const t=y.useRef(e);y.useEffect(()=>{t.current=e},[e]);const r=y.useCallback(function({children:s}){var d;const o=Dh({get current(){var f;return(f=t.current.cloud)!=null?f:Yn}}),l=(d=t.current.cloud)!=null?d:Yn,u=y.useMemo(()=>new rd(l),[l]),c=y.useMemo(()=>({history:o,attachments:u}),[o,u]);return p.jsx(On,{adapters:c,children:s})},[]),n=(a=e.cloud)!=null?a:Yn;return n?{list:()=>P(null,null,function*(){const{threads:i}=yield n.threads.list();return{threads:i.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:()=>P(null,null,function*(){var u,c;const s=yield(c=(u=e.create)==null?void 0:u.call(e))!=null?c: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:(i,s)=>P(null,null,function*(){return n.threads.update(i,{title:s})}),archive:i=>P(null,null,function*(){return n.threads.update(i,{is_archived:!0})}),unarchive:i=>P(null,null,function*(){return n.threads.update(i,{is_archived:!1})}),delete:i=>P(null,null,function*(){var s;return yield(s=e.delete)==null?void 0:s.call(e,i),n.threads.delete(i)}),generateTitle:(i,s)=>P(null,null,function*(){return n.runs.stream({thread_id:i,assistant_id:"system/thread_title",messages:s})}),fetch:i=>P(null,null,function*(){var o;const s=yield n.threads.get(i);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 ld},Fh=(e,n)=>{var a=n,{initialMessages:t}=a,r=V(a,["initialMessages"]);var u;const c=(u=nd())!=null?u:{},{modelContext:i}=c,s=V(c,["modelContext"]),o=y.useMemo(()=>E(m({},r),{adapters:E(m(m({},s),r.adapters),{chatModel:e})}),[e,r,s]),[l]=y.useState(()=>new wh(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(i)return l.registerModelContextProvider(i)},[i,l]),y.useMemo(()=>new Gn(l),[l])},ys=(e,n={})=>{var a=n,{cloud:t}=a,r=V(a,["cloud"]);const i=Oh({cloud:t});return ks({runtimeHook:function(){return Fh(e,r)},adapter:i,allowNesting:!0})},Gn=class{constructor(e){C(this,"threads");C(this,"_thread");this._core=e,this.threads=new ed(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(Nn.fromArray(e!=null?e:[]))}},Bh=e=>{const o=e,{cloud:t,initialMessages:r,maxSteps:n,adapters:a,unstable_humanToolNames:i}=o,s=V(o,["cloud","initialMessages","maxSteps","adapters","unstable_humanToolNames"]);return{localRuntimeOptions:{cloud:t,initialMessages:r,maxSteps:n,adapters:a,unstable_humanToolNames:i},otherOptions:s}};function Tt(e){const t=G.useRef(e);return G.useEffect(()=>{t.current=e}),G.useMemo(()=>(...r)=>{var n;return(n=t.current)==null?void 0:n.call(t,...r)},[])}var bs=y.createContext(null),zh=e=>({useSmoothStatus:Rt(()=>e)}),Rh=({children:e})=>{const t=ws({optional:!0}),r=he(),[n]=y.useState(()=>zh(r.part().getState().status));return t?e:p.jsx(bs.Provider,{value:n,children:e})},jh=e=>{const t=y.forwardRef((r,n)=>p.jsx(Rh,{children:p.jsx(e,E(m({},r),{ref:n}))}));return t.displayName=e.displayName,t};function ws(e){const t=y.useContext(bs);if(!(e!=null&&e.optional)&&!t)throw new Error("This component must be used within a SmoothContextProvider.");return t}var{useSmoothStatus:$h,useSmoothStatusStore:Uh}=ns(ws,"useSmoothStatus"),Hh=class{constructor(e,t){C(this,"animationFrameId",null);C(this,"lastUpdateTime",Date.now());C(this,"targetText","");C(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 i=0;for(;r>=a&&i<n;)i++,r-=a;i!==n?this.animationFrameId=requestAnimationFrame(this.animate):this.animationFrameId=null,i!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+i),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)}},Xn=Object.freeze({type:"running"}),xs=(e,t=!1)=>{const{text:r}=e,n=re(({message:c})=>c.id),a=y.useRef(n),[i,s]=y.useState(r),o=Uh({optional:!0}),l=Tt(c=>{if(s(c),o){const d=i!==c||e.status.type==="running"?Xn:e.status;ur(o).setState(d,!0)}});y.useEffect(()=>{if(o){const c=t&&(i!==r||e.status.type==="running")?Xn:e.status;ur(o).setState(c,!0)}},[o,t,r,i,e.status]);const[u]=y.useState(new Hh(r,l));return y.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]),y.useEffect(()=>()=>{u.stop()},[u]),y.useMemo(()=>t?{type:"text",text:i,status:r===i?e.status:Xn}:e,[t,i,e,r])};const qh=Object.freeze(Object.defineProperty({__proto__:null,AssistantRuntimeImpl:Gn,BaseAssistantRuntimeCore:In,CompositeContextProvider:Cn,DefaultThreadComposerRuntimeCore:ci,MessageRepository:_i,ThreadRuntimeImpl:zi,fromThreadMessageLike:nr,generateId:xt,getAutoStatus:hi,splitLocalRuntimeOptions:Bh,useSmooth:xs,useSmoothStatus:$h,useToolInvocations:od,withSmoothContextProvider:jh},Symbol.toStringTag,{value:"Module"}));var Vh=class extends tr{constructor(t){super();C(this,"useRuntimeHook");C(this,"instances",new Map);C(this,"useAliveThreadsKeysChanged",Rt(()=>({})));C(this,"_InnerActiveThreadProvider",({threadId:t})=>{const{useRuntime:r}=this.useRuntimeHook(),n=r(),a=n.thread.__internal_threadBinding,i=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=a.getState(),this._notifySubscribers()},[t,a]),s=y.useRef(!1);s.current||i(),y.useEffect(()=>(s.current=!0,i(),a.outerSubscribe(i)),[a,i]);const o=he();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});C(this,"_OuterActiveThreadProvider",y.memo(({threadId:t,provider:r})=>p.jsx(uh,{id:t,children:p.jsx(r,{children:p.jsx(this._InnerActiveThreadProvider,{threadId:t})})})));C(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=Rt(()=>({useRuntime:t}))}startThreadRuntime(t){return this.instances.has(t)||(this.instances.set(t,{}),this.useAliveThreadsKeysChanged.setState({},!0)),new Promise((r,n)=>{const a=()=>{const s=this.instances.get(t);if(!s)i(),n(new Error("Thread was deleted before runtime was started"));else if(s.runtime)i(),r(s.runtime);else return},i=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)}},ye=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."),Wh={getMessageById(){},getBranches(){return[]},switchToBranch(){throw ye},append(){throw ye},startRun(){throw ye},resumeRun(){throw ye},cancelRun(){throw ye},addToolResult(){throw ye},resumeToolCall(){throw ye},speak(){throw ye},stopSpeaking(){throw ye},submitFeedback(){throw ye},getModelContext(){return{}},unstable_loadExternalState(){throw ye},composer:{attachments:[],attachmentAccept:"*",addAttachment(){return P(this,null,function*(){throw ye})},removeAttachment(){return P(this,null,function*(){throw ye})},isEditing:!0,canCancel:!1,isEmpty:!0,text:"",setText(){throw ye},role:"user",setRole(){throw ye},runConfig:{},setRunConfig(){throw ye},reset(){return P(this,null,function*(){})},clearAttachments(){return P(this,null,function*(){})},send(){throw ye},cancel(){},subscribe(){return()=>{}},unstable_on(){return()=>{}}},getEditComposer(){},beginEdit(){throw ye},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 ye},export(){return{messages:[]}},reset(){throw ye},unstable_on(){return()=>{}}},vs=(e,t,r)=>r.reduce((n,a)=>{var i;return(i=a==null?void 0:a(n,t))!=null?i:n},e),Jh=class extends tr{constructor(t){super();C(this,"_pendingTransforms",[]);C(this,"_baseValue");C(this,"_cachedValue");this._baseValue=t,this._cachedValue=t}_updateState(){this._cachedValue=this._pendingTransforms.reduce((t,r)=>vs(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 P(this,null,function*(){const r=t.execute(),n=E(m({},t),{task:r});try{this._pendingTransforms.push(n),this._updateState();const a=yield r;return this._baseValue=vs(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 Mv(e){return e}var Yr=(e,t)=>{const r=e.threadIdMap[t];if(r!==void 0)return e.threadData[r]},Gr=(e,t,r)=>{const n=Yr(e,t);if(!n)return e;const{id:a,remoteId:i,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!==a);break;case"archived":o.archivedThreadIds=o.archivedThreadIds.filter(l=>l!==a);break;default:{const l=s;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!==i));break;default:{const l=r;throw new Error(`Unsupported state: ${l}`)}}return r!=="deleted"&&(o.threadData=E(m({},o.threadData),{[a]:E(m({},n),{status:r})})),o},Kh=class extends tr{constructor(t,r){super();C(this,"_options");C(this,"_hookManager");C(this,"_loadThreadsPromise");C(this,"_mainThreadId");C(this,"_state",new Jh({isLoading:!1,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}}));C(this,"useProvider");C(this,"initialize",t=>P(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=>Gr(r,t,"regular"),loading:(r,n)=>{const a=t;return E(m({},r),{threadData:E(m({},r.threadData),{[a]:E(m({},r.threadData[a]),{initializeTask:n})})})},then:(r,{remoteId:n,externalId:a})=>{const i=Yr(r,t);if(!i)return r;const s=t;return E(m({},r),{threadIdMap:E(m({},r.threadIdMap),{[n]:s}),threadData:E(m({},r.threadData),{[s]:E(m({},i),{initializeTask:Promise.resolve({remoteId:n,externalId:a}),remoteId:n,externalId:a})})})}})}));C(this,"generateTitle",t=>P(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 i=a.messages,s=yield this._options.adapter.generateTitle(n,i),o=Fc.fromAssistantStream(s);try{for(var u=Nt(o),c,d,f;c=!(d=yield u.next()).done;c=!1){const h=d.value;const g=(l=h.parts.filter(w=>w.type==="text")[0])==null?void 0:l.text,k=this._state.baseValue;this._state.update(E(m({},k),{threadData:E(m({},k.threadData),{[r.id]:E(m({},r),{title:g})})}))}}catch(d){f=[d]}finally{try{c&&(d=u.return)&&(yield d.call(u))}finally{if(f)throw f[0]}}}));C(this,"useBoundIds",Rt(()=>[]));C(this,"__internal_RenderComponent",()=>{const t=y.useId();y.useEffect(()=>(this.useBoundIds.setState(i=>[...i,t],!0),()=>{this.useBoundIds.setState(i=>i.filter(s=>s!==t),!0)}),[t]);const r=this.useBoundIds(),{Provider:n}=this.useProvider(),a={modelContext:this.contextProvider};return(r.length===0||r[0]===t)&&p.jsx(On,{adapters:a,children:p.jsx(this._hookManager.__internal_RenderThreadRuntimes,{provider:n})})});this.contextProvider=r,this._state.subscribe(()=>this._notifySubscribers()),this._hookManager=new Vh(t.runtimeHook),this.useProvider=Rt(()=>{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=>E(m({},t),{isLoading:!0}),then:(t,r)=>{const n=[],a=[],i={},s={};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;i[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 E(m({},t),{threadIds:n,archivedThreadIds:a,threadIdMap:m(m({},t.threadIdMap),i),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||Wh}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 Yr(this._state.value,t)}switchToThread(t){return P(this,null,function*(){let r=this.getItemById(t);if(!r){const a=yield this._options.adapter.fetch(t),i=this._state.value,s=a.remoteId,o=E(m({},i.threadData),{[s]:{id:s,initializeTask:Promise.resolve({remoteId:a.remoteId,externalId:a.externalId}),remoteId:a.remoteId,externalId:a.externalId,status:a.status,title:a.title}}),l=E(m({},i.threadIdMap),{[a.remoteId]:s}),u=a.status==="regular"?[...i.threadIds,a.remoteId]:i.threadIds,c=a.status==="archived"?[...i.archivedThreadIds,a.remoteId]:i.archivedThreadIds;this._state.update(E(m({},i),{threadIds:u,archivedThreadIds:c,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 P(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_${xt()}`;while(t.threadIdMap[r]);const n=r;this._state.update(E(m({},t),{newThreadId:r,threadIdMap:E(m({},t.threadIdMap),{[r]:n}),threadData:E(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:()=>P(this,null,function*(){const{remoteId:a}=yield n.initializeTask;return this._options.adapter.rename(a,r)}),optimistic:a=>{const i=Yr(a,t);return i?E(m({},a),{threadData:E(m({},a.threadData),{[i.id]:E(m({},i),{title:r})})}):a}})}_ensureThreadIsNotMain(t){return P(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 P(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:()=>P(this,null,function*(){yield this._ensureThreadIsNotMain(r.id);const{remoteId:n}=yield r.initializeTask;return this._options.adapter.archive(n)}),optimistic:n=>Gr(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:()=>P(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=>Gr(n,r.id,"regular")})}delete(t){return P(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:()=>P(this,null,function*(){yield this._ensureThreadIsNotMain(r.id);const{remoteId:n}=yield r.initializeTask;return yield this._options.adapter.delete(n)}),optimistic:n=>Gr(n,r.id,"deleted")})})}detach(t){return P(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)})}},Yh=class extends In{constructor(t){super();C(this,"threads");this.threads=new Kh(t,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}},Gh=e=>{const[t]=y.useState(()=>new Yh(e));return y.useEffect(()=>{t.threads.__internal_setOptions(e),t.threads.__internal_load()},[t,e]),y.useMemo(()=>new Gn(t),[t])},ks=e=>{if(Wr().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 Gh(e)},Xh=Symbol.for("react.lazy"),Xr=G[" use ".trim().toString()];function Qh(e){return typeof e=="object"&&e!==null&&"then"in e}function Ss(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Xh&&"_payload"in e&&Qh(e._payload)}function _s(e){const t=Zh(e),r=G.forwardRef((n,a)=>{let u=n,{children:i}=u,s=V(u,["children"]);Ss(i)&&typeof Xr=="function"&&(i=Xr(i._payload));const o=G.Children.toArray(i),l=o.find(tf);if(l){const c=l.props.children,d=o.map(f=>f===l?G.Children.count(c)>1?G.Children.only(null):G.isValidElement(c)?c.props.children:null:f);return p.jsx(t,E(m({},s),{ref:a,children:G.isValidElement(c)?G.cloneElement(c,void 0,d):null}))}return p.jsx(t,E(m({},s),{ref:a,children:i}))});return r.displayName=`${e}.Slot`,r}var Ts=_s("Slot");function Zh(e){const t=G.forwardRef((r,n)=>{let s=r,{children:a}=s,i=V(s,["children"]);if(Ss(a)&&typeof Xr=="function"&&(a=Xr(a._payload)),G.isValidElement(a)){const o=nf(a),l=rf(i,a.props);return a.type!==G.Fragment&&(l.ref=n?Yi(n,o):o),G.cloneElement(a,l)}return G.Children.count(a)>1?G.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var ef=Symbol("radix.slottable");function tf(e){return G.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===ef}function rf(e,t){const r=m({},t);for(const n in t){const a=e[n],i=t[n];/^on[A-Z]/.test(n)?a&&i?r[n]=(...o)=>{const l=i(...o);return a(...o),l}:a&&(r[n]=a):n==="style"?r[n]=m(m({},a),i):n==="className"&&(r[n]=[a,i].filter(Boolean).join(" "))}return m(m({},e),r)}function nf(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 af=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],lt=af.reduce((e,t)=>{const r=_s(`Primitive.${t}`),n=G.forwardRef((a,i)=>{const u=a,{asChild:s}=u,o=V(u,["asChild"]),l=s?r:t;return typeof window!="undefined"&&(window[Symbol.for("radix-ui")]=!0),p.jsx(l,E(m({},o),{ref:i}))});return n.displayName=`Primitive.${t}`,E(m({},e),{[t]:n})},{});function jt(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 cr=(e,t,r=[])=>{const n=y.forwardRef((a,i)=>{var u;const s={},o={};Object.keys(a).forEach(c=>{r.includes(c)?s[c]=a[c]:o[c]=a[c]});const l=(u=t(s))!=null?u:void 0;return p.jsx(lt.button,E(m({type:"button"},o),{ref:i,disabled:o.disabled||!l,onClick:jt(o.onClick,l)}))});return n.displayName=e,n};function sf(e,t=globalThis==null?void 0:globalThis.document){const r=Tt(e);G.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 of=()=>{const e=he();return y.useCallback(()=>{e.attachment().remove()},[e])},lf=cr("AttachmentPrimitive.Remove",of),dr=e=>{const t=y.useRef(void 0);return y.useCallback(n=>{t.current&&t.current(),n&&(t.current=e(n))},[e])},Cs=(e,t)=>{const r=y.useCallback(n=>{if(!e)return;const a=e(),i=()=>{const o=t?t(n):n.offsetHeight;a.setHeight(o)},s=new ResizeObserver(i);return s.observe(n),i(),()=>{s.disconnect(),a.unregister()}},[e,t]);return dr(r)},Is=y.createContext(!1),Es=(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 i=parseFloat(getComputedStyle(t).fontSize)||16;return n*i}if(a==="rem"){const i=parseFloat(getComputedStyle(document.documentElement).fontSize)||16;return n*i}return 0},As=({children:e,fillClampThreshold:t="10em",fillClampOffset:r="6em"})=>{const n=re(({message:l})=>l.isLast&&l.index>=2),a=Hn({optional:!0}),i=y.useContext(Is),s=y.useCallback(l=>{if(!a||i)return;const u=()=>{const c=a.getState();if(c.turnAnchor==="top"&&n){const{viewport:d,inset:f,userMessage:h}=c.height,g=Es(t,l),k=Es(r,l),w=h<=g?h:k,b=Math.max(0,d-f-w);l.style.minHeight=`${b}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,i,t,r]),o=dr(s);return p.jsx(Is.Provider,{value:!0,children:p.jsx(Ts,{ref:o,children:e})})};As.displayName="ThreadPrimitive.ViewportSlack";var uf=()=>{const e=he(),t=re(()=>e.message()),r=y.useCallback(n=>{const a=()=>{t.setIsHovering(!0)},i=()=>{t.setIsHovering(!1)};return n.addEventListener("mouseenter",a),n.addEventListener("mouseleave",i),n.matches(":hover")&&t.setIsHovering(!0),()=>{n.removeEventListener("mouseenter",a),n.removeEventListener("mouseleave",i),t.setIsHovering(!1)}},[t]);return dr(r)},cf=()=>{const e=Jr(a=>a.turnAnchor),t=Jr(a=>a.registerUserMessageHeight),r=re(({thread:a,message:i})=>{var s;return e==="top"&&i.role==="user"&&i.index===a.messages.length-2&&((s=a.messages.at(-1))==null?void 0:s.role)==="assistant"}),n=y.useCallback(a=>a.offsetHeight,[]);return Cs(r?t:null,n)},Qn=y.forwardRef((e,t)=>{const r=uf(),n=cf(),a=Vr(t,r,n);return p.jsx(As,{children:p.jsx(lt.div,E(m({},e),{ref:a}))})});Qn.displayName="MessagePrimitive.Root";var Ms=()=>re(({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}),Ps=y.forwardRef((a,n)=>{var i=a,{smooth:e=!0,component:t="span"}=i,r=V(i,["smooth","component"]);const{text:s,status:o}=xs(Ms(),e);return p.jsx(t,E(m({"data-status":o.type},r),{ref:n,children:s}))});Ps.displayName="MessagePartPrimitive.Text";var df=()=>re(({part:t})=>{if(t.type!=="image")throw new Error("MessagePartImage can only be used inside image message parts.");return t}),Ns=y.forwardRef((e,t)=>{const{image:r}=df();return p.jsx(lt.img,E(m({src:r},e),{ref:t}))});Ns.displayName="MessagePartPrimitive.Image";var Ls=({children:e})=>re(({part:r})=>r.status.type==="running")?e:null;Ls.displayName="MessagePartPrimitive.InProgress";const Ds=e=>Symbol.iterator in e,Os=e=>"entries"in e,Fs=(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,i]of r)if(!n.has(a)||!Object.is(i,n.get(a)))return!1;return!0},hf=(e,t)=>{const r=e[Symbol.iterator](),n=t[Symbol.iterator]();let a=r.next(),i=n.next();for(;!a.done&&!i.done;){if(!Object.is(a.value,i.value))return!1;a=r.next(),i=n.next()}return!!a.done&&!!i.done};function ff(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:Ds(e)&&Ds(t)?Os(e)&&Os(t)?Fs(e,t):hf(e,t):Fs({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function pf(e){const t=y.useRef(void 0);return r=>{const n=e(r);return ff(t.current,n)?t.current:t.current=n}}var Bs=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})}}},mf=e=>{const t=[],r=Bs("toolGroup"),n=Bs("reasoningGroup");for(let a=0;a<e.length;a++){const i=e[a];i==="tool-call"?(n.endGroup(a-1,t),r.startGroup(a)):i==="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},gf=()=>{const e=re(pf(t=>t.message.parts.map(r=>r.type)));return y.useMemo(()=>e.length===0?[]:mf(e),[e])},yf=r=>{var n=r,{Fallback:e}=n,t=V(n,["Fallback"]);const a=re(({tools:i})=>{var o,l;const s=(o=i.tools[t.toolName])!=null?o:e;return Array.isArray(s)?(l=s[0])!=null?l:e:s});return a?p.jsx(a,m({},t)):null},ut={Text:()=>p.jsxs("p",{style:{whiteSpace:"pre-line"},children:[p.jsx(Ps,{}),p.jsx(Ls,{children:p.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>p.jsx(Ns,{}),File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},bf=({components:{Text:e=ut.Text,Reasoning:t=ut.Reasoning,Image:r=ut.Image,Source:n=ut.Source,File:a=ut.File,Unstable_Audio:i=ut.Unstable_Audio,tools:s={}}={}})=>{var c,d,f;const o=he(),l=re(({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,E(m({},l),{addResult:h,resume:g}));const k=(d=(c=s.by_name)==null?void 0:c[l.toolName])!=null?d:s.Fallback;return p.jsx(yf,E(m({},l),{Fallback:k,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(i,m({},l));case"data":return null;default:const h=u;throw new Error(`Unknown message part type: ${h}`)}},Qr=y.memo(({index:e,components:t})=>p.jsx(dh,{index:e,children:p.jsx(bf,{components:t})}),(e,t)=>{var r,n,a,i,s,o,l,u,c,d,f,h,g,k,w,b,I,T;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)===((i=t.components)==null?void 0:i.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)&&((c=e.components)==null?void 0:c.File)===((d=t.components)==null?void 0:d.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)===((k=t.components)==null?void 0:k.tools)&&((w=e.components)==null?void 0:w.ToolGroup)===((b=t.components)==null?void 0:b.ToolGroup)&&((I=e.components)==null?void 0:I.ReasoningGroup)===((T=t.components)==null?void 0:T.ReasoningGroup)});Qr.displayName="MessagePrimitive.PartByIndex";var wf=({status:e,component:t})=>p.jsx(mh,{text:"",isRunning:e.type==="running",children:p.jsx(t,{type:"text",text:"",status:e})}),xf=Object.freeze({type:"complete"}),vf=({components:e})=>{var r;const t=re(n=>{var a;return(a=n.message.status)!=null?a:xf});return e!=null&&e.Empty?p.jsx(e.Empty,{status:t}):p.jsx(wf,{status:t,component:(r=e==null?void 0:e.Text)!=null?r:ut.Text})},kf=y.memo(vf,(e,t)=>{var r,n,a,i;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)===((i=t.components)==null?void 0:i.Text)}),Zn=({components:e})=>{const t=re(({message:a})=>a.parts.length),r=gf(),n=y.useMemo(()=>t===0?p.jsx(kf,{components:e}):r.map(a=>{var i,s;if(a.type==="single")return p.jsx(Qr,{index:a.index,components:e},a.index);if(a.type==="toolGroup"){const o=(i=e==null?void 0:e.ToolGroup)!=null?i:ut.ToolGroup;return p.jsx(o,{startIndex:a.startIndex,endIndex:a.endIndex,children:Array.from({length:a.endIndex-a.startIndex+1},(l,u)=>p.jsx(Qr,{index:a.startIndex+u,components:e},u))},`tool-${a.startIndex}`)}else{const o=(s=e==null?void 0:e.ReasoningGroup)!=null?s:ut.ReasoningGroup;return p.jsx(o,{startIndex:a.startIndex,endIndex:a.endIndex,children:Array.from({length:a.endIndex-a.startIndex+1},(l,u)=>p.jsx(Qr,{index:a.startIndex+u,components:e},u))},`reasoning-${a.startIndex}`)}}),[r,e,t]);return p.jsx(p.Fragment,{children:n})};Zn.displayName="MessagePrimitive.Parts";var Sf=(e,t)=>{var n,a,i;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(i=e==null?void 0:e.File)!=null?i:e==null?void 0:e.Attachment;default:const s=r;throw new Error(`Unknown attachment type: ${s}`)}},_f=({components:e})=>{const t=re(({attachment:n})=>n);if(!t)return null;const r=Sf(e,t);return r?p.jsx(r,{}):null},zs=y.memo(({index:e,components:t})=>p.jsx(hh,{index:e,children:p.jsx(_f,{components:t})}),(e,t)=>{var r,n,a,i,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)&&((a=e.components)==null?void 0:a.Document)===((i=t.components)==null?void 0:i.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)});zs.displayName="MessagePrimitive.AttachmentByIndex";var Rs=({components:e})=>{const t=re(({message:n})=>n.role!=="user"?0:n.attachments.length);return y.useMemo(()=>Array.from({length:t},(n,a)=>p.jsx(zs,{index:a,components:e},a)),[t,e])};Rs.displayName="MessagePrimitive.Attachments";var js=()=>{const e=he(),t=re(n=>n.thread.isRunning||!n.composer.isEditing||n.composer.isEmpty),r=y.useCallback(()=>{e.composer().send()},[e]);return t?null:r},Tf=cr("ComposerPrimitive.Send",js),$s=y.forwardRef((n,r)=>{var a=n,{onSubmit:e}=a,t=V(a,["onSubmit"]);const i=js(),s=o=>{o.preventDefault(),i&&i()};return p.jsx(lt.form,E(m({},t),{ref:r,onSubmit:jt(e,s)}))});$s.displayName="ComposerPrimitive.Root";function ea(){return ea=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},ea.apply(null,arguments)}function Cf(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 If=y.useLayoutEffect,Ef=function(t){var r=y.useRef(t);return If(function(){r.current=t}),r},Us=function(t,r){if(typeof t=="function"){t(r);return}t.current=r},Af=function(t,r){var n=y.useRef();return y.useCallback(function(a){t.current=a,n.current&&Us(n.current,null),n.current=r,r&&Us(r,a)},[r])},Hs={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},Mf=function(t){Object.keys(Hs).forEach(function(r){t.style.setProperty(r,Hs[r],"important")})},qs=Mf,Ne=null,Vs=function(t,r){var n=t.scrollHeight;return r.sizingStyle.boxSizing==="border-box"?n+r.borderSize:n-r.paddingSize};function Pf(e,t,r,n){r===void 0&&(r=1),n===void 0&&(n=1/0),Ne||(Ne=document.createElement("textarea"),Ne.setAttribute("tabindex","-1"),Ne.setAttribute("aria-hidden","true"),qs(Ne)),Ne.parentNode===null&&document.body.appendChild(Ne);var a=e.paddingSize,i=e.borderSize,s=e.sizingStyle,o=s.boxSizing;Object.keys(s).forEach(function(f){var h=f;Ne.style[h]=s[h]}),qs(Ne),Ne.value=t;var l=Vs(Ne,e);Ne.value=t,l=Vs(Ne,e),Ne.value="x";var u=Ne.scrollHeight-a,c=u*r;o==="border-box"&&(c=c+a+i),l=Math.max(c,l);var d=u*n;return o==="border-box"&&(d=d+a+i),l=Math.min(d,l),[l,u]}var Ws=function(){},Nf=function(t,r){return t.reduce(function(n,a){return n[a]=r[a],n},{})},Lf=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],Df=!!document.documentElement.currentStyle,Of=function(t){var r=window.getComputedStyle(t);if(r===null)return null;var n=Nf(Lf,r),a=n.boxSizing;if(a==="")return null;Df&&a==="border-box"&&(n.width=parseFloat(n.width)+parseFloat(n.borderRightWidth)+parseFloat(n.borderLeftWidth)+parseFloat(n.paddingRight)+parseFloat(n.paddingLeft)+"px");var i=parseFloat(n.paddingBottom)+parseFloat(n.paddingTop),s=parseFloat(n.borderBottomWidth)+parseFloat(n.borderTopWidth);return{sizingStyle:n,paddingSize:i,borderSize:s}},Ff=Of;function ta(e,t,r){var n=Ef(r);G.useLayoutEffect(function(){var a=function(s){return n.current(s)};if(e)return e.addEventListener(t,a),function(){return e.removeEventListener(t,a)}},[])}var Bf=function(t,r){ta(document.body,"reset",function(n){t.current.form===n.target&&r(n)})},zf=function(t){ta(window,"resize",t)},Rf=function(t){ta(document.fonts,"loadingdone",t)},jf=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],$f=function(t,r){var n=t.cacheMeasurements,a=t.maxRows,i=t.minRows,s=t.onChange,o=s===void 0?Ws:s,l=t.onHeightChange,u=l===void 0?Ws:l,c=Cf(t,jf),d=c.value!==void 0,f=G.useRef(null),h=Af(f,r),g=G.useRef(0),k=G.useRef(),w=function(){var T=f.current,B=n&&k.current?k.current:Ff(T);if(B){k.current=B;var F=Pf(B,T.value||T.placeholder||"x",i,a),_=F[0],$=F[1];g.current!==_&&(g.current=_,T.style.setProperty("height",_+"px","important"),u(_,{rowHeight:$}))}},b=function(T){d||w(),o(T)};return G.useLayoutEffect(w),Bf(f,function(){if(!d){var I=f.current.value;requestAnimationFrame(function(){var T=f.current;T&&I!==T.value&&w()})}}),zf(w),Rf(w),G.createElement("textarea",ea({},c,{onChange:b,ref:h}))},Uf=G.forwardRef($f),Js=e=>{const t=Tt(e),r=Jr(n=>n.onScrollToBottom);y.useEffect(()=>r(t),[r,t])},Ks=y.forwardRef((g,h)=>{var k=g,{autoFocus:e=!1,asChild:t,disabled:r,onChange:n,onKeyDown:a,onPaste:i,submitOnEnter:s=!0,cancelOnEscape:o=!0,unstable_focusOnRunStart:l=!0,unstable_focusOnScrollToBottom:u=!0,unstable_focusOnThreadSwitched:c=!0,addAttachmentOnPaste:d=!0}=k,f=V(k,["autoFocus","asChild","disabled","onChange","onKeyDown","onPaste","submitOnEnter","cancelOnEscape","unstable_focusOnRunStart","unstable_focusOnScrollToBottom","unstable_focusOnThreadSwitched","addAttachmentOnPaste"]);const w=he(),b=re(({composer:S})=>S.isEditing?S.text:""),I=t?Ts:Uf,T=re(({thread:S})=>S.isDisabled)||r,B=y.useRef(null),F=Vr(h,B);sf(S=>{var M;if(!o||!((M=B.current)!=null&&M.contains(S.target)))return;const N=w.composer();N.getState().canCancel&&(N.cancel(),S.preventDefault())});const _=S=>{var N,M;T||!s||S.nativeEvent.isComposing||S.key==="Enter"&&S.shiftKey===!1&&(w.thread().getState().isRunning||(S.preventDefault(),(M=(N=B.current)==null?void 0:N.closest("form"))==null||M.requestSubmit()))},$=S=>P(null,null,function*(){var J;if(!d)return;const N=w.thread().getState().capabilities,M=Array.from(((J=S.clipboardData)==null?void 0:J.files)||[]);if(N.attachments&&M.length>0)try{S.preventDefault(),yield Promise.all(M.map(z=>w.composer().addAttachment(z)))}catch(z){console.error("Error adding attachment:",z)}}),R=e&&!T,j=y.useCallback(()=>{const S=B.current;!S||!R||(S.focus({preventScroll:!0}),S.setSelectionRange(S.value.length,S.value.length))},[R]);return y.useEffect(()=>j(),[j]),Js(()=>{w.composer().getState().type==="thread"&&u&&j()}),y.useEffect(()=>{if(!(w.composer().getState().type!=="thread"||!l))return w.on("thread.run-start",j)},[l,j,w]),y.useEffect(()=>{if(!(w.composer().getState().type!=="thread"||!c))return w.on("thread-list-item.switched-to",j)},[c,j,w]),p.jsx(I,E(m({name:"input",value:b},f),{ref:F,disabled:T,onChange:jt(n,S=>{w.composer().getState().isEditing&&(w.composer().setText(S.target.value),w.flushSync())}),onKeyDown:jt(a,_),onPaste:jt(i,$)}))});Ks.displayName="ComposerPrimitive.Input";var Hf=({multiple:e=!0}={})=>{const t=re(({composer:a})=>!a.isEditing),r=he(),n=y.useCallback(()=>{const a=document.createElement("input");a.type="file",a.multiple=e,a.hidden=!0;const i=r.composer().getState().attachmentAccept;i!=="*"&&(a.accept=i),document.body.appendChild(a),a.onchange=s=>{const o=s.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},qf=cr("ComposerPrimitive.AddAttachment",Hf,["multiple"]),Vf=(e,t)=>{var n,a,i;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(i=e==null?void 0:e.File)!=null?i:e==null?void 0:e.Attachment;default:const s=r;throw new Error(`Unknown attachment type: ${s}`)}},Wf=({components:e})=>{const t=re(({attachment:n})=>n);if(!t)return null;const r=Vf(e,t);return r?p.jsx(r,{}):null},Ys=y.memo(({index:e,components:t})=>p.jsx(fh,{index:e,children:p.jsx(Wf,{components:t})}),(e,t)=>{var r,n,a,i,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)&&((a=e.components)==null?void 0:a.Document)===((i=t.components)==null?void 0:i.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)});Ys.displayName="ComposerPrimitive.AttachmentByIndex";var Gs=({components:e})=>{const t=re(n=>n.composer.attachments.length);return y.useMemo(()=>Array.from({length:t},(n,a)=>p.jsx(Ys,{index:a,components:e},a)),[t,e])};Gs.displayName="ComposerPrimitive.Attachments";var Xs=y.forwardRef((e,t)=>p.jsx(lt.div,E(m({},e),{ref:t})));Xs.displayName="ThreadPrimitive.Root";var Qs=({children:e})=>re(({thread:r})=>r.messages.length===0&&!r.isLoading)?e:null;Qs.displayName="ThreadPrimitive.Empty";var Jf=e=>{const t=Tt(e),r=y.useCallback(n=>{const a=new ResizeObserver(()=>{t()}),i=new MutationObserver(()=>{t()});return a.observe(n),i.observe(n,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{a.disconnect(),i.disconnect()}},[t]);return dr(r)},Kf=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:r=!0,scrollToBottomOnThreadSwitch:n=!0})=>{const a=y.useRef(null),i=Hn();e===void 0&&(e=i.getState().turnAnchor!=="top");const s=y.useRef(0),o=y.useRef(null),l=y.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=i.getState().isAtBottom,k=Math.abs(h.scrollHeight-h.scrollTop-h.clientHeight)<1||h.scrollHeight<=h.clientHeight;!k&&s.current<h.scrollTop||(k&&(o.current=null),(k||o.current===null)&&k!==g&&ur(i).setState({isAtBottom:k})),s.current=h.scrollTop},c=Jf(()=>{const h=o.current;h?l(h):e&&i.getState().isAtBottom&&l("instant"),u()}),d=dr(h=>(h.addEventListener("scroll",u),()=>{h.removeEventListener("scroll",u)}));return Js(({behavior:h})=>{l(h)}),Un("thread.run-start",()=>{t&&(o.current="auto",requestAnimationFrame(()=>{l("auto")}))}),Un("thread.initialize",()=>{r&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Un("thread-list-item.switched-to",()=>{n&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Vr(c,d,a)},Yf=()=>{const e=Jr(r=>r.registerViewport),t=y.useCallback(r=>r.clientHeight,[]);return Cs(e,t)},Zs=y.forwardRef((o,s)=>{var l=o,{autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:r,scrollToBottomOnThreadSwitch:n,children:a}=l,i=V(l,["autoScroll","scrollToBottomOnRunStart","scrollToBottomOnInitialize","scrollToBottomOnThreadSwitch","children"]);const u=Kf({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:r,scrollToBottomOnThreadSwitch:n}),c=Yf(),d=Vr(s,u,c);return p.jsx(lt.div,E(m({},i),{ref:d,children:a}))});Zs.displayName="ThreadPrimitive.ViewportScrollable";var eo=y.forwardRef((n,r)=>{var a=n,{turnAnchor:e}=a,t=V(a,["turnAnchor"]);return p.jsx(cs,{options:{turnAnchor:e},children:p.jsx(Zs,E(m({},t),{ref:r}))})});eo.displayName="ThreadPrimitive.Viewport";var to=(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,Gf=()=>null,Xf=(e,t,r)=>{var n,a,i,s,o,l,u,c,d,f,h,g;switch(t){case"user":return r?(i=(a=(n=e.UserEditComposer)!=null?n:e.EditComposer)!=null?a:e.UserMessage)!=null?i: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:(c=e.AssistantMessage)!=null?c:e.Message;case"system":return r?(h=(f=(d=e.SystemEditComposer)!=null?d:e.EditComposer)!=null?f:e.SystemMessage)!=null?h:e.Message:(g=e.SystemMessage)!=null?g:Gf;default:const k=t;throw new Error(`Unknown message role: ${k}`)}},Qf=({components:e})=>{const t=re(({message:a})=>a.role),r=re(({message:a})=>a.composer.isEditing),n=Xf(e,t,r);return p.jsx(n,{})},ro=y.memo(({index:e,components:t})=>p.jsx(ch,{index:e,children:p.jsx(Qf,{components:t})}),(e,t)=>e.index===t.index&&to(e.components,t.components));ro.displayName="ThreadPrimitive.MessageByIndex";var no=({components:e})=>{const t=re(({thread:n})=>n.messages.length);return y.useMemo(()=>t===0?null:Array.from({length:t},(n,a)=>p.jsx(ro,{index:a,components:e},a)),[t,e])};no.displayName="ThreadPrimitive.Messages";var Zf=y.memo(no,(e,t)=>to(e.components,t.components)),ao=y.forwardRef((a,n)=>{var i=a,{onClick:e,disabled:t}=i,r=V(i,["onClick","disabled"]);const s=re(({threads:l})=>l.newThreadId===l.mainThreadId),o=he();return p.jsx(lt.button,E(m(m({type:"button"},s?{"data-active":"true","aria-current":"true"}:null),r),{ref:n,disabled:t,onClick:jt(e,()=>{o.threads().switchToNewThread()})}))});ao.displayName="ThreadListPrimitive.New";var io=y.memo(({index:e,archived:t=!1,components:r})=>{const n=r.ThreadListItem;return p.jsx(lh,{index:e,archived:t,children:p.jsx(n,{})})},(e,t)=>e.index===t.index&&e.archived===t.archived&&e.components.ThreadListItem===t.components.ThreadListItem);io.displayName="ThreadListPrimitive.ItemByIndex";var so=({archived:e=!1,components:t})=>{const r=re(({threads:a})=>e?a.archivedThreadIds.length:a.threadIds.length);return y.useMemo(()=>Array.from({length:r},(a,i)=>p.jsx(io,{index:i,archived:e,components:t},i)),[r,e,t])};so.displayName="ThreadListPrimitive.Items";var oo=y.forwardRef((e,t)=>p.jsx(lt.div,E(m({},e),{ref:t})));oo.displayName="ThreadListPrimitive.Root";var lo=y.forwardRef((e,t)=>{const r=re(({threads:n,threadListItem:a})=>n.mainThreadId===a.id);return p.jsx(lt.div,E(m(m({},r?{"data-active":"true","aria-current":"true"}:null),e),{ref:t}))});lo.displayName="ThreadListItemPrimitive.Root";var ep=()=>{const e=he();return y.useCallback(()=>{e.threadListItem().delete()},[e])},tp=cr("ThreadListItemPrimitive.Delete",ep),rp=()=>{const e=he();return y.useCallback(()=>{e.threadListItem().switchTo()},[e])},np=cr("ThreadListItemPrimitive.Trigger",rp);class uo{constructor(t,r,n=!1){C(this,"baseUrl");C(this,"sessionToken",null);C(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 P(this,null,function*(){const n=this.getUrl("/v1/chats"),i={"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&&(i.Authorization=`Bearer ${this.sessionToken}`);const s=E(m({},t),{stream:!0}),o=yield fetch(n,{method:"POST",headers:i,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 P(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 i=yield a.json().catch(()=>({}));throw new Error(i.detail||i.message||`API error: ${a.status} ${a.statusText}`)}return a.json()})}listChats(t){return P(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 a={"Content-Type":"application/json"};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(n.toString(),{method:"GET",headers:a});if(!i.ok){const s=yield i.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${i.status} ${i.statusText}`)}return i.json()})}generateIdempotencyKey(){try{if(typeof crypto!="undefined"&&crypto.randomUUID)return crypto.randomUUID()}catch(n){}const t=n=>Array.from({length:n},()=>Math.floor(Math.random()*16).toString(16)).join(""),r=()=>{const n=["8","9","a","b"];return n[Math.floor(Math.random()*n.length)]};return`${t(8)}-${t(4)}-4${t(3)}-${r()}${t(3)}-${t(12)}`}updateChat(t,r){return P(this,null,function*(){const n=`/v1/chats/${t}`,a=this.getUrl(n),i=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(i.toString(),{method:"PATCH",headers:o,body:JSON.stringify(r)});if(!l.ok){const c=yield l.text();let d={};try{d=JSON.parse(c)}catch(f){d={detail:c}}throw new Error(d.detail||d.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(c){return{}}})}deleteChat(t){return P(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),s={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(s.Authorization=`Bearer ${this.sessionToken}`);const o=yield fetch(a.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}`)}})}listModels(t){return P(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 a={"Content-Type":"application/json"};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(n.toString(),{method:"GET",headers:a});if(!i.ok){const s=yield i.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${i.status} ${i.statusText}`)}return i.json()})}getModel(t){return P(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 i=yield a.json().catch(()=>({}));throw new Error(i.detail||i.message||`API error: ${a.status} ${a.statusText}`)}return a.json()})}uploadFile(t,r,n){return P(this,null,function*(){const a=this.getUrl("/v1/files"),i=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":i};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(a,{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 ap(e,t){return Mr(this,null,function*(){const r=e.getReader(),n=new TextDecoder;let a="";try{for(;;){if(t!=null&&t.aborted){r.cancel();break}const{done:i,value:s}=yield new Ge(r.read());if(i)break;a+=n.decode(s,{stream:!0});const o=a.split(`
6
6
 
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 rp(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 np(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 Xr=new Map;function ap(e,t){return{list(){return P(this,null,function*(){const n=[];let i,s=0;do{const l=yield e.listChats({limit:50,cursor:i}),u=l.items||[];Array.isArray(u)&&u.length>0&&n.push(...u),i=l.nextCursor||void 0,s++}while(i&&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 P(this,null,function*(){return{remoteId:Xr.get(n)||n,externalId:void 0}})},rename(n,a){return P(this,null,function*(){yield e.updateChat(n,{title:a})})},archive(n){return P(this,null,function*(){})},unarchive(n){return P(this,null,function*(){})},delete(n){return P(this,null,function*(){yield e.deleteChat(n)})},generateTitle(n,a){return P(this,null,function*(){return new ReadableStream})},fetch(n){return P(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){Xr.set(n,a),t==null||t(n,a)},unstable_Provider:({children:n})=>{const a=as(),i=a==null?void 0:a.remoteId,s=g.useMemo(()=>({load(){return P(this,null,function*(){if(!i)return{messages:[]};try{const u=yield e.getChat(i);return!u.messages||u.messages.length===0?{messages:[]}:{messages:u.messages.map(c=>np(c))}}catch(u){return console.error("Failed to load messages for thread:",i,u),{messages:[]}}})},append(u){return P(this,null,function*(){})}}),[i,e]),o=g.useMemo(()=>({history:s}),[s]);return p.jsx(Dn,{adapters:o,children:n})}}}const lo=new Map,uo=[];let Qr=[];function ip(e,t,r=50,n=800){uo.push({question:e,response:t,streamingSpeed:r,initialDelay:n})}function co(e,t){const{modelId:r,systemPrompt:n,ephemeral:a,onChatCreated:i,onUserMessage:s,onThreadIdUpdate:o,onBeforeRequest:l}=t;let u;return{run(c){return Er(this,null,function*(){var k,D;const{messages:f,abortSignal:h,context:y}=c,S=uo.shift();if(S){s==null||s();const j=(k=S.initialDelay)!=null?k:800;if(j>0&&(yield new qe(new Promise(ae=>setTimeout(ae,j)))),h!=null&&h.aborted)throw new Error("Request aborted");const J=S.response.split(" ");let re="";const Z=S.streamingSpeed||50,w=`premade-${Date.now()}`;a&&(i==null||i(w));for(let ae=0;ae<J.length;ae++){if(h!=null&&h.aborted)throw new Error("Request aborted");re+=(ae===0?"":" ")+J[ae],yield{content:[{type:"text",text:re}]},yield new qe(new Promise(xe=>setTimeout(xe,Z+Math.random()*(Z*.5))))}yield{content:[{type:"text",text:re}]},Qr.push({role:"user",content:S.question},{role:"assistant",content:S.response});return}const x=y==null?void 0:y.threadId;let b=x;if(!b&&f.length>0){const j=f.find(J=>J.role==="user");j&&(b=(typeof j.content=="string"?j.content:Array.isArray(j.content)&&((D=j.content.find(re=>re.type==="text"))==null?void 0:D.text)||"").substring(0,50))}let _;x&&(_=Xr.get(x)),!_&&b&&(_=lo.get(b)),!_&&u&&(_=u),s==null||s();let T=f,L=-1;for(let j=f.length-1;j>=0;j--)if(f[j].role==="assistant"){L=j;break}(_||L>=0)&&L>=0&&(T=f.slice(L+1));const z=rp(T);if(Qr.length>0&&!_){const j=Qr.map(J=>({role:J.role,content:J.content}));z.unshift(...j),Qr=[]}const I={messages:z,chatId:_||null,systemPrompt:n,ephemeral:a,stream:!0};if(r&&r.trim()!==""&&(I.modelId=r),l&&!(yield new qe(l())))throw new Error("Request blocked");const q=yield new qe(e.createOrContinueChat(I,h));let B="",U;try{for(var M=Mt(tp(q,h)),H,R,F;H=!(R=yield new qe(M.next())).done;H=!1){const j=R.value;if(h!=null&&h.aborted)throw new Error("Request aborted");const J=j.id||j.chatId;J&&!U&&(U=J,u=J,i==null||i(J),x&&o&&(o(x,J),Xr.set(x,J)),b&&lo.set(b,J));const re=j.delta;if(re!=null&&(B+=re),j.type==="message"||j.content){const w=j.content||"";B+=w}if(j.message&&(B+=j.message.content||""),j.tool_calls,j.finished){B&&(yield{content:[{type:"text",text:B}]});break}B&&(yield{content:[{type:"text",text:B}]})}}catch(R){F=[R]}finally{try{H&&(R=M.return)&&(yield new qe(R.call(M)))}finally{if(F)throw F[0]}}B&&(yield{content:[{type:"text",text:B}]})})}}}function ho(){return{accept:".pdf,.docx,.txt,.md,.csv,.json,image/*",add(r){return P(this,arguments,function*({file:t}){let n="file";return t.type.startsWith("image/")?n="image":(t.type.includes("pdf")||t.type.includes("document")||t.type.includes("text")||t.name.endsWith(".pdf")||t.name.endsWith(".docx")||t.name.endsWith(".txt")||t.name.endsWith(".md")||t.name.endsWith(".csv")||t.name.endsWith(".json"))&&(n="document"),{id:`${t.name}-${Date.now()}`,type:n,name:t.name,contentType:t.type,file:t,status:{type:"requires-action",reason:"composer-send"}}})},remove(){return P(this,null,function*(){})},send(t){return P(this,null,function*(){if(t.type==="image"&&t.file){const r=yield new Promise((n,a)=>{const i=new FileReader;i.onload=()=>n(i.result),i.onerror=a,i.readAsDataURL(t.file)});return E(m({},t),{status:{type:"complete"},content:[{type:"image",image:r}]})}return E(m({},t),{status:{type:"complete"},content:[]})})}}}function sp({children:e,baseUrl:t,sessionToken:r,isProxyMode:n=!1,mode:a="multiChat",modelId:i,onModelChange:s,ephemeral:o=!1,systemPrompt:l,initialThreadId:u,onError:d,onChatCreated:c,onUserMessage:f,onThreadIdUpdate:h,onChatsLoaded:y,enableAttachments:S=!1,onBeforeRequest:x}){const b=g.useMemo(()=>new oo(t,r||void 0,n),[t,r,n]),[_,T]=g.useState(i||null);g.useEffect(()=>{i&&T(i)},[i]);const L=g.useCallback(q=>{c==null||c(q)},[c]),z=g.useCallback((q,B)=>{h==null||h(q,B)},[h]),I=g.useMemo(()=>co(b,{modelId:_||void 0,systemPrompt:l,ephemeral:o,onChatCreated:L,onUserMessage:f,onBeforeRequest:x}),[b,_,l,o,L,f,x]);return a==="singleChat"?p.jsx(op,{modelAdapter:I,enableAttachments:S,children:e}):p.jsx(lp,{client:b,modelAdapterOptions:{modelId:_||void 0,systemPrompt:l,ephemeral:o,onChatCreated:L,onUserMessage:f,onBeforeRequest:x},initialThreadId:u,onChatsLoaded:y,onThreadIdUpdate:z,onError:d,enableAttachments:S,children:e})}function op({modelAdapter:e,enableAttachments:t,children:r}){const n=g.useMemo(()=>t?ho():void 0,[t]),a=ps(e,{adapters:m({},n&&{attachments:n})});return p.jsx(ls,{runtime:a,children:r})}function lp({client:e,modelAdapterOptions:t,initialThreadId:r,onChatsLoaded:n,onThreadIdUpdate:a,onError:i,enableAttachments:s,children:o}){const l=g.useMemo(()=>ap(e,(S,x)=>{a==null||a(S,x)}),[e,a]),u=g.useCallback((S,x)=>{l.updateRemoteId&&l.updateRemoteId(S,x),a==null||a(S,x)},[l,a]),d=g.useMemo(()=>E(m({},l),{list(){return P(this,null,function*(){const x=yield l.list();return n==null||n(),x})}}),[l,n]);g.useEffect(()=>{window.__cuadraThreadListAdapter=d,window.__cuadraThreadListRuntime=null},[d]);const c=g.useMemo(()=>co(e,E(m({},t),{onThreadIdUpdate:u})),[e,t,u]),f=g.useMemo(()=>s?ho():void 0,[s]),h=g.useCallback(()=>ps(c,{adapters:m({},f&&{attachments:f})}),[c,f]),y=ws({adapter:d,runtimeHook:h});return g.useEffect(()=>{window.__cuadraThreadListRuntime=y},[y]),p.jsx(ls,{runtime:y,children:o})}function bv(){}function wv(){}function up(e,t){const r={};return(e[e.length-1]===""?[...e,""]:e).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}const cp=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,dp=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,hp={};function fo(e,t){return(hp.jsx?dp:cp).test(e)}const fp=/[ \t\n\f\r]/g;function pp(e){return typeof e=="object"?e.type==="text"?po(e.value):!1:po(e)}function po(e){return e.replace(fp,"")===""}class dr{constructor(t,r,n){this.normal=r,this.property=t,n&&(this.space=n)}}dr.prototype.normal={},dr.prototype.property={},dr.prototype.space=void 0;function mo(e,t){const r={},n={};for(const a of e)Object.assign(r,a.property),Object.assign(n,a.normal);return new dr(r,n,t)}function ta(e){return e.toLowerCase()}class Me{constructor(t,r){this.attribute=r,this.property=t}}Me.prototype.attribute="",Me.prototype.booleanish=!1,Me.prototype.boolean=!1,Me.prototype.commaOrSpaceSeparated=!1,Me.prototype.commaSeparated=!1,Me.prototype.defined=!1,Me.prototype.mustUseProperty=!1,Me.prototype.number=!1,Me.prototype.overloadedBoolean=!1,Me.prototype.property="",Me.prototype.spaceSeparated=!1,Me.prototype.space=void 0;let mp=0;const X=It(),ge=It(),ra=It(),N=It(),ce=It(),jt=It(),Oe=It();function It(){return Iu(2,++mp)}const na=Object.freeze(Object.defineProperty({__proto__:null,boolean:X,booleanish:ge,commaOrSpaceSeparated:Oe,commaSeparated:jt,number:N,overloadedBoolean:ra,spaceSeparated:ce},Symbol.toStringTag,{value:"Module"})),aa=Object.keys(na);class ia extends Me{constructor(t,r,n,a){let i=-1;if(super(t,r),go(this,"space",a),typeof n=="number")for(;++i<aa.length;){const s=aa[i];go(this,aa[i],(n&na[s])===na[s])}}}ia.prototype.defined=!0;function go(e,t,r){r&&(e[t]=r)}function $t(e){const t={},r={};for(const[n,a]of Object.entries(e.properties)){const i=new ia(n,e.transform(e.attributes||{},n),a,e.space);e.mustUseProperty&&e.mustUseProperty.includes(n)&&(i.mustUseProperty=!0),t[n]=i,r[ta(n)]=n,r[ta(i.attribute)]=n}return new dr(t,r,e.space)}const yo=$t({properties:{ariaActiveDescendant:null,ariaAtomic:ge,ariaAutoComplete:null,ariaBusy:ge,ariaChecked:ge,ariaColCount:N,ariaColIndex:N,ariaColSpan:N,ariaControls:ce,ariaCurrent:null,ariaDescribedBy:ce,ariaDetails:null,ariaDisabled:ge,ariaDropEffect:ce,ariaErrorMessage:null,ariaExpanded:ge,ariaFlowTo:ce,ariaGrabbed:ge,ariaHasPopup:null,ariaHidden:ge,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:ce,ariaLevel:N,ariaLive:null,ariaModal:ge,ariaMultiLine:ge,ariaMultiSelectable:ge,ariaOrientation:null,ariaOwns:ce,ariaPlaceholder:null,ariaPosInSet:N,ariaPressed:ge,ariaReadOnly:ge,ariaRelevant:null,ariaRequired:ge,ariaRoleDescription:ce,ariaRowCount:N,ariaRowIndex:N,ariaRowSpan:N,ariaSelected:ge,ariaSetSize:N,ariaSort:null,ariaValueMax:N,ariaValueMin:N,ariaValueNow:N,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 wo(e,t){return bo(e,t.toLowerCase())}const gp=$t({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:jt,acceptCharset:ce,accessKey:ce,action:null,allow:null,allowFullScreen:X,allowPaymentRequest:X,allowUserMedia:X,alt:null,as:null,async:X,autoCapitalize:null,autoComplete:ce,autoFocus:X,autoPlay:X,blocking:ce,capture:null,charSet:null,checked:X,cite:null,className:ce,cols:N,colSpan:null,content:null,contentEditable:ge,controls:X,controlsList:ce,coords:N|jt,crossOrigin:null,data:null,dateTime:null,decoding:null,default:X,defer:X,dir:null,dirName:null,disabled:X,download:ra,draggable:ge,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:X,formTarget:null,headers:ce,height:N,hidden:ra,high:N,href:null,hrefLang:null,htmlFor:ce,httpEquiv:ce,id:null,imageSizes:null,imageSrcSet:null,inert:X,inputMode:null,integrity:null,is:null,isMap:X,itemId:null,itemProp:ce,itemRef:ce,itemScope:X,itemType:ce,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:X,low:N,manifest:null,max:null,maxLength:N,media:null,method:null,min:null,minLength:N,multiple:X,muted:X,name:null,nonce:null,noModule:X,noValidate:X,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:X,optimum:N,pattern:null,ping:ce,placeholder:null,playsInline:X,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:X,referrerPolicy:null,rel:ce,required:X,reversed:X,rows:N,rowSpan:N,sandbox:ce,scope:null,scoped:X,seamless:X,selected:X,shadowRootClonable:X,shadowRootDelegatesFocus:X,shadowRootMode:null,shape:null,size:N,sizes:null,slot:null,span:N,spellCheck:ge,src:null,srcDoc:null,srcLang:null,srcSet:null,start:N,step:null,style:null,tabIndex:N,target:null,title:null,translate:null,type:null,typeMustMatch:X,useMap:null,value:ge,width:N,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:ce,axis:null,background:null,bgColor:null,border:N,borderColor:null,bottomMargin:N,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:X,declare:X,event:null,face:null,frame:null,frameBorder:null,hSpace:N,leftMargin:N,link:null,longDesc:null,lowSrc:null,marginHeight:N,marginWidth:N,noResize:X,noHref:X,noShade:X,noWrap:X,object:null,profile:null,prompt:null,rev:null,rightMargin:N,rules:null,scheme:null,scrolling:ge,standby:null,summary:null,text:null,topMargin:N,valueType:null,version:null,vAlign:null,vLink:null,vSpace:N,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:X,disableRemotePlayback:X,prefix:null,property:null,results:N,security:null,unselectable:null},space:"html",transform:wo}),yp=$t({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:Oe,accentHeight:N,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:N,amplitude:N,arabicForm:null,ascent:N,attributeName:null,attributeType:null,azimuth:N,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:N,by:null,calcMode:null,capHeight:N,className:ce,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:N,diffuseConstant:N,direction:null,display:null,dur:null,divisor:N,dominantBaseline:null,download:X,dx:null,dy:null,edgeMode:null,editable:null,elevation:N,enableBackground:null,end:null,event:null,exponent:N,externalResourcesRequired:null,fill:null,fillOpacity:N,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:jt,g2:jt,glyphName:jt,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:N,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:N,horizOriginX:N,horizOriginY:N,id:null,ideographic:N,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:N,k:N,k1:N,k2:N,k3:N,k4:N,kernelMatrix:Oe,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:N,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:N,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:N,overlineThickness:N,paintOrder:null,panose1:null,path:null,pathLength:N,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:ce,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:N,pointsAtY:N,pointsAtZ:N,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Oe,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Oe,rev:Oe,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Oe,requiredFeatures:Oe,requiredFonts:Oe,requiredFormats:Oe,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:N,specularExponent:N,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:N,strikethroughThickness:N,string:null,stroke:null,strokeDashArray:Oe,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:N,strokeOpacity:N,strokeWidth:null,style:null,surfaceScale:N,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Oe,tabIndex:N,tableValues:null,target:null,targetX:N,targetY:N,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Oe,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:N,underlineThickness:N,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:N,values:null,vAlphabetic:N,vMathematical:N,vectorEffect:null,vHanging:N,vIdeographic:N,version:null,vertAdvY:N,vertOriginX:N,vertOriginY:N,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:N,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:bo}),xo=$t({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()}}),vo=$t({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:wo}),So=$t({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),bp={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"},wp=/[A-Z]/g,ko=/-[a-z]/g,xp=/^data[-\w.:]+$/i;function vp(e,t){const r=ta(t);let n=t,a=Me;if(r in e.normal)return e.property[e.normal[r]];if(r.length>4&&r.slice(0,4)==="data"&&xp.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(ko,kp);n="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!ko.test(i)){let s=i.replace(wp,Sp);s.charAt(0)!=="-"&&(s="-"+s),t="data"+s}}a=ia}return new a(n,t)}function Sp(e){return"-"+e.toLowerCase()}function kp(e){return e.charAt(1).toUpperCase()}const _p=mo([yo,gp,xo,vo,So],"html"),sa=mo([yo,yp,xo,vo,So],"svg");function Tp(e){return e.join(" ").trim()}var Ut={},oa,_o;function Cp(){if(_o)return oa;_o=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,r=/^\s*/,n=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,s=/^[;\s]*/,o=/^\s+|\s+$/g,l=`
8
- `,u="/",d="*",c="",f="comment",h="declaration";function y(x,b){if(typeof x!="string")throw new TypeError("First argument must be a string");if(!x)return[];b=b||{};var _=1,T=1;function L(R){var F=R.match(t);F&&(_+=F.length);var j=R.lastIndexOf(l);T=~j?R.length-j:T+R.length}function z(){var R={line:_,column:T};return function(F){return F.position=new I(R),U(),F}}function I(R){this.start=R,this.end={line:_,column:T},this.source=b.source}I.prototype.content=x;function q(R){var F=new Error(b.source+":"+_+":"+T+": "+R);if(F.reason=R,F.filename=b.source,F.line=_,F.column=T,F.source=x,!b.silent)throw F}function B(R){var F=R.exec(x);if(F){var j=F[0];return L(j),x=x.slice(j.length),F}}function U(){B(r)}function k(R){var F;for(R=R||[];F=D();)F!==!1&&R.push(F);return R}function D(){var R=z();if(!(u!=x.charAt(0)||d!=x.charAt(1))){for(var F=2;c!=x.charAt(F)&&(d!=x.charAt(F)||u!=x.charAt(F+1));)++F;if(F+=2,c===x.charAt(F-1))return q("End of comment missing");var j=x.slice(2,F-2);return T+=2,L(j),x=x.slice(F),T+=2,R({type:f,comment:j})}}function M(){var R=z(),F=B(n);if(F){if(D(),!B(a))return q("property missing ':'");var j=B(i),J=R({type:h,property:S(F[0].replace(e,c)),value:j?S(j[0].replace(e,c)):c});return B(s),J}}function H(){var R=[];k(R);for(var F;F=M();)F!==!1&&(R.push(F),k(R));return R}return U(),H()}function S(x){return x?x.replace(o,c):c}return oa=y,oa}var To;function Ip(){if(To)return Ut;To=1;var e=Ut&&Ut.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.default=r;const t=e(Cp());function r(n,a){let i=null;if(!n||typeof n!="string")return i;const s=(0,t.default)(n),o=typeof a=="function";return s.forEach(l=>{if(l.type!=="declaration")return;const{property:u,value:d}=l;o?a(u,d,l):d&&(i=i||{},i[u]=d)}),i}return Ut}var hr={},Co;function Ep(){if(Co)return hr;Co=1,Object.defineProperty(hr,"__esModule",{value:!0}),hr.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,r=/^[^-]+$/,n=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,i=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={}),i(u)?u:(u=u.toLowerCase(),d.reactCompat?u=u.replace(a,o):u=u.replace(n,o),u.replace(t,s))};return hr.camelCase=l,hr}var fr,Io;function Ap(){if(Io)return fr;Io=1;var e=fr&&fr.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(Ip()),r=Ep();function n(a,i){var s={};return!a||typeof a!="string"||(0,t.default)(a,function(o,l){o&&l&&(s[(0,r.camelCase)(o,i)]=l)}),s}return n.default=n,fr=n,fr}var Pp=Ap();const Mp=Ar(Pp),Eo=Ao("end"),la=Ao("start");function Ao(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 Np(e){const t=la(e),r=Eo(e);if(t&&r)return{start:t,end:r}}function pr(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Po(e.position):"start"in e||"end"in e?Po(e):"line"in e||"column"in e?ua(e):""}function ua(e){return Mo(e&&e.line)+":"+Mo(e&&e.column)}function Po(e){return ua(e&&e.start)+"-"+ua(e&&e.end)}function Mo(e){return e&&typeof e=="number"?e:1}class ke extends Error{constructor(t,r,n){super(),typeof r=="string"&&(n=r,r=void 0);let a="",i={},s=!1;if(r&&("line"in r&&"column"in r?i={place:r}:"start"in r&&"end"in r?i={place:r}:"type"in r?i={ancestors:[r],place:r.position}:i=m({},r)),typeof t=="string"?a=t:!i.cause&&t&&(s=!0,a=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof n=="string"){const l=n.indexOf(":");l===-1?i.ruleId=n:(i.source=n.slice(0,l),i.ruleId=n.slice(l+1))}if(!i.place&&i.ancestors&&i.ancestors){const l=i.ancestors[i.ancestors.length-1];l&&(i.place=l.position)}const o=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.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=pr(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=s&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}ke.prototype.file="",ke.prototype.name="",ke.prototype.reason="",ke.prototype.message="",ke.prototype.stack="",ke.prototype.column=void 0,ke.prototype.line=void 0,ke.prototype.ancestors=void 0,ke.prototype.cause=void 0,ke.prototype.fatal=void 0,ke.prototype.place=void 0,ke.prototype.ruleId=void 0,ke.prototype.source=void 0;const ca={}.hasOwnProperty,Lp=new Map,Dp=/[A-Z]/g,Op=new Set(["table","tbody","thead","tfoot","tr"]),Fp=new Set(["td","th"]),No="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Bp(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=Vp(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=qp(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},i=Lo(a,e,void 0);return i&&typeof i!="string"?i:a.create(e,a.Fragment,{children:i||void 0},void 0)}function Lo(e,t,r){if(t.type==="element")return zp(e,t,r);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return Rp(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return $p(e,t,r);if(t.type==="mdxjsEsm")return jp(e,t);if(t.type==="root")return Up(e,t,r);if(t.type==="text")return Hp(e,t)}function zp(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 i=Oo(e,t.tagName,!1),s=Wp(e,t);let o=ha(e,t);return Op.has(t.tagName)&&(o=o.filter(function(l){return typeof l=="string"?!pp(l):!0})),Do(e,s,i,t),da(s,o),e.ancestors.pop(),e.schema=n,e.create(t,i,s,r)}function Rp(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)}mr(e,t.position)}function jp(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);mr(e,t.position)}function $p(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 i=t.name===null?e.Fragment:Oo(e,t.name,!0),s=Jp(e,t),o=ha(e,t);return Do(e,s,i,t),da(s,o),e.ancestors.pop(),e.schema=n,e.create(t,i,s,r)}function Up(e,t,r){const n={};return da(n,ha(e,t)),e.create(t,e.Fragment,n,r)}function Hp(e,t){return t.value}function Do(e,t,r,n){typeof r!="string"&&r!==e.Fragment&&e.passNode&&(t.node=n)}function da(e,t){if(t.length>0){const r=t.length>1?t:t[0];r&&(e.children=r)}}function qp(e,t,r){return n;function n(a,i,s,o){const u=Array.isArray(s.children)?r:t;return o?u(i,s,o):u(i,s)}}function Vp(e,t){return r;function r(n,a,i,s){const o=Array.isArray(i.children),l=la(n);return t(a,i,s,o,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function Wp(e,t){const r={};let n,a;for(a in t.properties)if(a!=="children"&&ca.call(t.properties,a)){const i=Kp(e,a,t.properties[a]);if(i){const[s,o]=i;e.tableCellAlignToStyle&&s==="align"&&typeof o=="string"&&Fp.has(t.tagName)?n=o:r[s]=o}}if(n){const i=r.style||(r.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=n}return r}function Jp(e,t){const r={};for(const n of t.attributes)if(n.type==="mdxJsxExpressionAttribute")if(n.data&&n.data.estree&&e.evaluater){const i=n.data.estree.body[0];i.type;const s=i.expression;s.type;const o=s.properties[0];o.type,Object.assign(r,e.evaluater.evaluateExpression(o.argument))}else mr(e,t.position);else{const a=n.name;let i;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,i=e.evaluater.evaluateExpression(o.expression)}else mr(e,t.position);else i=n.value===null?!0:n.value;r[a]=i}return r}function ha(e,t){const r=[];let n=-1;const a=e.passKeys?new Map:Lp;for(;++n<t.children.length;){const i=t.children[n];let s;if(e.passKeys){const l=i.type==="element"?i.tagName:i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement"?i.name:void 0;if(l){const u=a.get(l)||0;s=l+"-"+u,a.set(l,u+1)}}const o=Lo(e,i,s);o!==void 0&&r.push(o)}return r}function Kp(e,t,r){const n=vp(e.schema,t);if(!(r==null||typeof r=="number"&&Number.isNaN(r))){if(Array.isArray(r)&&(r=n.commaSeparated?up(r):Tp(r)),n.property==="style"){let a=typeof r=="object"?r:Gp(e,String(r));return e.stylePropertyNameCase==="css"&&(a=Yp(a)),["style",a]}return[e.elementAttributeNameCase==="react"&&n.space?bp[n.property]||n.property:n.attribute,r]}}function Gp(e,t){try{return Mp(t,{reactCompat:!0})}catch(r){if(e.ignoreInvalidStyle)return{};const n=r,a=new ke("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=No+"#cannot-parse-style-attribute",a}}function Oo(e,t,r){let n;if(!r)n={type:"Literal",value:t};else if(t.includes(".")){const a=t.split(".");let i=-1,s;for(;++i<a.length;){const o=fo(a[i])?{type:"Identifier",name:a[i]}:{type:"Literal",value:a[i]};s=s?{type:"MemberExpression",object:s,property:o,computed:!!(i&&o.type==="Literal"),optional:!1}:o}n=s}else n=fo(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(n.type==="Literal"){const a=n.value;return ca.call(e.components,a)?e.components[a]:a}if(e.evaluater)return e.evaluater.evaluateExpression(n);mr(e)}function mr(e,t){const r=new ke("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=No+"#cannot-handle-mdx-estrees-without-createevaluater",r}function Yp(e){const t={};let r;for(r in e)ca.call(e,r)&&(t[Xp(r)]=e[r]);return t}function Xp(e){let t=e.replace(Dp,Qp);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function Qp(e){return"-"+e.toLowerCase()}const fa={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"]},Zp={};function pa(e,t){const r=Zp,n=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,a=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return Fo(e,n,a)}function Fo(e,t,r){if(em(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 Bo(e.children,t,r)}return Array.isArray(e)?Bo(e,t,r):""}function Bo(e,t,r){const n=[];let a=-1;for(;++a<e.length;)n[a]=Fo(e[a],t,r);return n.join("")}function em(e){return!!(e&&typeof e=="object")}const zo=document.createElement("i");function ma(e){const t="&"+e+";";zo.innerHTML=t;const r=zo.textContent;return r.charCodeAt(r.length-1)===59&&e!=="semi"||r===t?!1:r}function Fe(e,t,r,n){const a=e.length;let i=0,s;if(t<0?t=-t>a?0:a+t:t=t>a?a: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);i<n.length;)s=n.slice(i,i+1e4),s.unshift(t,0),e.splice(...s),i+=1e4,t+=1e4}function je(e,t){return e.length>0?(Fe(e,e.length,0,t),e):t}const Ro={}.hasOwnProperty;function jo(e){const t={};let r=-1;for(;++r<e.length;)tm(t,e[r]);return t}function tm(e,t){let r;for(r in t){const a=(Ro.call(e,r)?e[r]:void 0)||(e[r]={}),i=t[r];let s;if(i)for(s in i){Ro.call(a,s)||(a[s]=[]);const o=i[s];rm(a[s],Array.isArray(o)?o:o?[o]:[])}}}function rm(e,t){let r=-1;const n=[];for(;++r<t.length;)(t[r].add==="after"?e:n).push(t[r]);Fe(e,0,0,n)}function $o(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 Ge(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Ee=pt(/[A-Za-z]/),_e=pt(/[\dA-Za-z]/),nm=pt(/[#-'*+\--9=?A-Z^-~]/);function Zr(e){return e!==null&&(e<32||e===127)}const ga=pt(/\d/),am=pt(/[\dA-Fa-f]/),im=pt(/[!-/:-@[-`{-~]/);function K(e){return e!==null&&e<-2}function ue(e){return e!==null&&(e<0||e===32)}function ee(e){return e===-2||e===-1||e===32}const en=pt(new RegExp("\\p{P}|\\p{S}","u")),Et=pt(/\s/);function pt(e){return t;function t(r){return r!==null&&r>-1&&e.test(String.fromCharCode(r))}}function Ht(e){const t=[];let r=-1,n=0,a=0;for(;++r<e.length;){const i=e.charCodeAt(r);let s="";if(i===37&&_e(e.charCodeAt(r+1))&&_e(e.charCodeAt(r+2)))a=2;else if(i<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(i))||(s=String.fromCharCode(i));else if(i>55295&&i<57344){const o=e.charCodeAt(r+1);i<56320&&o>56319&&o<57344?(s=String.fromCharCode(i,o),a=1):s="�"}else s=String.fromCharCode(i);s&&(t.push(e.slice(n,r),encodeURIComponent(s)),n=r+a+1,s=""),a&&(r+=a,a=0)}return t.join("")+e.slice(n)}function ne(e,t,r,n){const a=n?n-1:Number.POSITIVE_INFINITY;let i=0;return s;function s(l){return ee(l)?(e.enter(r),o(l)):t(l)}function o(l){return ee(l)&&i++<a?(e.consume(l),o):(e.exit(r),t(l))}}const sm={tokenize:om};function om(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"),ne(e,t,"linePrefix")}function a(o){return e.enter("paragraph"),i(o)}function i(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 K(o)?(e.consume(o),e.exit("chunkText"),i):(e.consume(o),s)}}const lm={tokenize:um},Uo={tokenize:cm};function um(e){const t=this,r=[];let n=0,a,i,s;return o;function o(T){if(n<r.length){const L=r[n];return t.containerState=L[1],e.attempt(L[0].continuation,l,u)(T)}return u(T)}function l(T){if(n++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,a&&_();const L=t.events.length;let z=L,I;for(;z--;)if(t.events[z][0]==="exit"&&t.events[z][1].type==="chunkFlow"){I=t.events[z][1].end;break}b(n);let q=L;for(;q<t.events.length;)t.events[q][1].end=m({},I),q++;return Fe(t.events,z+1,0,t.events.slice(L)),t.events.length=q,u(T)}return o(T)}function u(T){if(n===r.length){if(!a)return f(T);if(a.currentConstruct&&a.currentConstruct.concrete)return y(T);t.interrupt=!!(a.currentConstruct&&!a._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Uo,d,c)(T)}function d(T){return a&&_(),b(n),f(T)}function c(T){return t.parser.lazy[t.now().line]=n!==r.length,s=t.now().offset,y(T)}function f(T){return t.containerState={},e.attempt(Uo,h,y)(T)}function h(T){return n++,r.push([t.currentConstruct,t.containerState]),f(T)}function y(T){if(T===null){a&&_(),b(0),e.consume(T);return}return a=a||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:a,contentType:"flow",previous:i}),S(T)}function S(T){if(T===null){x(e.exit("chunkFlow"),!0),b(0),e.consume(T);return}return K(T)?(e.consume(T),x(e.exit("chunkFlow")),n=0,t.interrupt=void 0,o):(e.consume(T),S)}function x(T,L){const z=t.sliceStream(T);if(L&&z.push(null),T.previous=i,i&&(i.next=T),i=T,a.defineSkip(T.start),a.write(z),t.parser.lazy[T.start.line]){let I=a.events.length;for(;I--;)if(a.events[I][1].start.offset<s&&(!a.events[I][1].end||a.events[I][1].end.offset>s))return;const q=t.events.length;let B=q,U,k;for(;B--;)if(t.events[B][0]==="exit"&&t.events[B][1].type==="chunkFlow"){if(U){k=t.events[B][1].end;break}U=!0}for(b(n),I=q;I<t.events.length;)t.events[I][1].end=m({},k),I++;Fe(t.events,B+1,0,t.events.slice(q)),t.events.length=I}}function b(T){let L=r.length;for(;L-- >T;){const z=r[L];t.containerState=z[1],z[0].exit.call(t,e)}r.length=T}function _(){a.write([null]),i=void 0,a=void 0,t.containerState._closeFlow=void 0}}function cm(e,t,r){return ne(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||ue(e)||Et(e))return 1;if(en(e))return 2}function tn(e,t,r){const n=[];let a=-1;for(;++a<e.length;){const i=e[a].resolveAll;i&&!n.includes(i)&&(t=i(t,r),n.push(i))}return t}const ya={name:"attention",resolveAll:dm,tokenize:hm};function dm(e,t){let r=-1,n,a,i,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);Ho(c,-l),Ho(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},i={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({},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",a,t],["enter",s,t],["exit",s,t],["enter",i,t]]),u=je(u,tn(t.parser.constructs.insideSpan.null,e.slice(n+1,r),t)),u=je(u,[["exit",i,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,Fe(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 hm(e,t){const r=this.parser.constructs.attentionMarkers.null,n=this.previous,a=qt(n);let i;return s;function s(l){return i=l,e.enter("attentionSequence"),o(l)}function o(l){if(l===i)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=!!(i===42?c:c&&(a||!f)),u._close=!!(i===42?f:f&&(d||!c)),t(l)}}function Ho(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const fm={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"),i}function i(h){return Ee(h)?(e.consume(h),s):h===64?r(h):u(h)}function s(h){return h===43||h===45||h===46||_e(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||_e(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||Zr(h)?r(h):(e.consume(h),l)}function u(h){return h===64?(e.consume(h),d):nm(h)?(e.consume(h),u):r(h)}function d(h){return _e(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||_e(h))&&n++<63){const y=h===45?f:c;return e.consume(h),y}return r(h)}}const gr={partial:!0,tokenize:mm};function mm(e,t,r){return n;function n(i){return ee(i)?ne(e,a,"linePrefix")(i):a(i)}function a(i){return i===null||K(i)?t(i):r(i)}}const qo={continuation:{tokenize:ym},exit:bm,name:"blockQuote",tokenize:gm};function gm(e,t,r){const n=this;return a;function a(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"),i}return r(s)}function i(s){return ee(s)?(e.enter("blockQuotePrefixWhitespace"),e.consume(s),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(s))}}function ym(e,t,r){const n=this;return a;function a(s){return ee(s)?ne(e,i,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(s):i(s)}function i(s){return e.attempt(qo,t,r)(s)}}function bm(e){e.exit("blockQuote")}const Vo={name:"characterEscape",tokenize:wm};function wm(e,t,r){return n;function n(i){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(i),e.exit("escapeMarker"),a}function a(i){return im(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):r(i)}}const Wo={name:"characterReference",tokenize:xm};function xm(e,t,r){const n=this;let a=0,i,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"),i=31,s=_e,d(c))}function u(c){return c===88||c===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(c),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,s=am,d):(e.enter("characterReferenceValue"),i=7,s=ga,d(c))}function d(c){if(c===59&&a){const f=e.exit("characterReferenceValue");return s===_e&&!ma(n.sliceSerialize(f))?r(c):(e.enter("characterReferenceMarker"),e.consume(c),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return s(c)&&a++<i?(e.consume(c),d):r(c)}}const Jo={partial:!0,tokenize:Sm},Ko={concrete:!0,name:"codeFenced",tokenize:vm};function vm(e,t,r){const n=this,a={partial:!0,tokenize:z};let i=0,s=0,o;return l;function l(I){return u(I)}function u(I){const q=n.events[n.events.length-1];return i=q&&q[1].type==="linePrefix"?q[2].sliceSerialize(q[1],!0).length:0,o=I,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),d(I)}function d(I){return I===o?(s++,e.consume(I),d):s<3?r(I):(e.exit("codeFencedFenceSequence"),ee(I)?ne(e,c,"whitespace")(I):c(I))}function c(I){return I===null||K(I)?(e.exit("codeFencedFence"),n.interrupt?t(I):e.check(Jo,S,L)(I)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(I))}function f(I){return I===null||K(I)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),c(I)):ee(I)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),ne(e,h,"whitespace")(I)):I===96&&I===o?r(I):(e.consume(I),f)}function h(I){return I===null||K(I)?c(I):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),y(I))}function y(I){return I===null||K(I)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),c(I)):I===96&&I===o?r(I):(e.consume(I),y)}function S(I){return e.attempt(a,L,x)(I)}function x(I){return e.enter("lineEnding"),e.consume(I),e.exit("lineEnding"),b}function b(I){return i>0&&ee(I)?ne(e,_,"linePrefix",i+1)(I):_(I)}function _(I){return I===null||K(I)?e.check(Jo,S,L)(I):(e.enter("codeFlowValue"),T(I))}function T(I){return I===null||K(I)?(e.exit("codeFlowValue"),_(I)):(e.consume(I),T)}function L(I){return e.exit("codeFenced"),t(I)}function z(I,q,B){let U=0;return k;function k(F){return I.enter("lineEnding"),I.consume(F),I.exit("lineEnding"),D}function D(F){return I.enter("codeFencedFence"),ee(F)?ne(I,M,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(F):M(F)}function M(F){return F===o?(I.enter("codeFencedFenceSequence"),H(F)):B(F)}function H(F){return F===o?(U++,I.consume(F),H):U>=s?(I.exit("codeFencedFenceSequence"),ee(F)?ne(I,R,"whitespace")(F):R(F)):B(F)}function R(F){return F===null||K(F)?(I.exit("codeFencedFence"),q(F)):B(F)}}}function Sm(e,t,r){const n=this;return a;function a(s){return s===null?r(s):(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),i)}function i(s){return n.parser.lazy[n.now().line]?r(s):t(s)}}const ba={name:"codeIndented",tokenize:_m},km={partial:!0,tokenize:Tm};function _m(e,t,r){const n=this;return a;function a(u){return e.enter("codeIndented"),ne(e,i,"linePrefix",5)(u)}function i(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):K(u)?e.attempt(km,s,l)(u):(e.enter("codeFlowValue"),o(u))}function o(u){return u===null||K(u)?(e.exit("codeFlowValue"),s(u)):(e.consume(u),o)}function l(u){return e.exit("codeIndented"),t(u)}}function Tm(e,t,r){const n=this;return a;function a(s){return n.parser.lazy[n.now().line]?r(s):K(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),a):ne(e,i,"linePrefix",5)(s)}function i(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):K(s)?a(s):r(s)}}const Cm={name:"codeText",previous:Em,resolve:Im,tokenize:Am};function Im(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 Em(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Am(e,t,r){let n=0,a,i;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?(i=e.enter("codeTextSequence"),a=0,d(c)):K(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||K(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)):(i.type="codeTextData",u(c))}}class Pm{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 i=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return n&&yr(this.left,n),i.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),yr(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),yr(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);yr(this.right,r.reverse())}else{const r=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);yr(this.left,r.reverse())}}}function yr(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 Go(e){const t={};let r=-1,n,a,i,s,o,l,u;const d=new Pm(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,i=0,i<l.length&&l[i][1].type==="lineEndingBlank"&&(i+=2),i<l.length&&l[i][1].type==="content"))for(;++i<l.length&&l[i][1].type!=="content";)l[i][1].type==="chunkText"&&(l[i][1]._isInFirstContentOfListItem=!0,i++);if(n[0]==="enter")n[1].contentType&&(Object.assign(t,Mm(d,r)),r=t[r],u=!0);else if(n[1]._container){for(i=r,a=void 0;i--;)if(s=d.get(i),s[1].type==="lineEnding"||s[1].type==="lineEndingBlank")s[0]==="enter"&&(a&&(d.get(a)[1].type="lineEndingBlank"),s[1].type="lineEnding",a=i);else if(!(s[1].type==="linePrefix"||s[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 Fe(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!u}function Mm(e,t){const r=e.get(t)[1],n=e.get(t)[2];let a=t-1;const i=[];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,y=0,S=0;const x=[S];for(;h;){for(;e.get(++a)[1]!==h;);i.push(a),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&&(S=f+1,x.push(S),h._tokenizer=void 0,h.previous=void 0,h=h.next);for(s.events=[],h?(h._tokenizer=void 0,h.previous=void 0):x.pop(),f=x.length;f--;){const b=o.slice(x[f],x[f+1]),_=i.pop();l.push([_,_+b.length-1]),e.splice(_,2,b)}for(l.reverse(),f=-1;++f<l.length;)u[y+l[f][0]]=y+l[f][1],y+=l[f][1]-l[f][0]-1;return u}const Nm={resolve:Dm,tokenize:Om},Lm={partial:!0,tokenize:Fm};function Dm(e){return Go(e),e}function Om(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?i(o):K(o)?e.check(Lm,s,i)(o):(e.consume(o),a)}function i(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,a}}function Fm(e,t,r){const n=this;return a;function a(s){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),ne(e,i,"linePrefix")}function i(s){if(s===null||K(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 Yo(e,t,r,n,a,i,s,o,l){const u=l||Number.POSITIVE_INFINITY;let d=0;return c;function c(b){return b===60?(e.enter(n),e.enter(a),e.enter(i),e.consume(b),e.exit(i),f):b===null||b===32||b===41||Zr(b)?r(b):(e.enter(n),e.enter(s),e.enter(o),e.enter("chunkString",{contentType:"string"}),S(b))}function f(b){return b===62?(e.enter(i),e.consume(b),e.exit(i),e.exit(a),e.exit(n),t):(e.enter(o),e.enter("chunkString",{contentType:"string"}),h(b))}function h(b){return b===62?(e.exit("chunkString"),e.exit(o),f(b)):b===null||b===60||K(b)?r(b):(e.consume(b),b===92?y:h)}function y(b){return b===60||b===62||b===92?(e.consume(b),h):h(b)}function S(b){return!d&&(b===null||b===41||ue(b))?(e.exit("chunkString"),e.exit(o),e.exit(s),e.exit(n),t(b)):d<u&&b===40?(e.consume(b),d++,S):b===41?(e.consume(b),d--,S):b===null||b===32||b===40||Zr(b)?r(b):(e.consume(b),b===92?x:S)}function x(b){return b===40||b===41||b===92?(e.consume(b),S):S(b)}}function Xo(e,t,r,n,a,i){const s=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(i),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(i),e.enter(a),e.consume(h),e.exit(a),e.exit(n),t):K(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||K(h)||o++>999?(e.exit("chunkString"),d(h)):(e.consume(h),l||(l=!ee(h)),h===92?f:c)}function f(h){return h===91||h===92||h===93?(e.consume(h),o++,c):c(h)}}function Qo(e,t,r,n,a,i){let s;return o;function o(f){return f===34||f===39||f===40?(e.enter(n),e.enter(a),e.consume(f),e.exit(a),s=f===40?41:f,l):r(f)}function l(f){return f===s?(e.enter(a),e.consume(f),e.exit(a),e.exit(n),t):(e.enter(i),u(f))}function u(f){return f===s?(e.exit(i),l(s)):f===null?r(f):K(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),ne(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(f))}function d(f){return f===s||f===null||K(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 br(e,t){let r;return n;function n(a){return K(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),r=!0,n):ee(a)?ne(e,n,r?"linePrefix":"lineSuffix")(a):t(a)}}const Bm={name:"definition",tokenize:Rm},zm={partial:!0,tokenize:jm};function Rm(e,t,r){const n=this;let a;return i;function i(h){return e.enter("definition"),s(h)}function s(h){return Xo.call(n,e,o,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(h)}function o(h){return a=Ge(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 ue(h)?br(e,u)(h):u(h)}function u(h){return Yo(e,d,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(h)}function d(h){return e.attempt(zm,c,c)(h)}function c(h){return ee(h)?ne(e,f,"whitespace")(h):f(h)}function f(h){return h===null||K(h)?(e.exit("definition"),n.parser.defined.push(a),t(h)):r(h)}}function jm(e,t,r){return n;function n(o){return ue(o)?br(e,a)(o):r(o)}function a(o){return Qo(e,i,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function i(o){return ee(o)?ne(e,s,"whitespace")(o):s(o)}function s(o){return o===null||K(o)?t(o):r(o)}}const $m={name:"hardBreakEscape",tokenize:Um};function Um(e,t,r){return n;function n(i){return e.enter("hardBreakEscape"),e.consume(i),a}function a(i){return K(i)?(e.exit("hardBreakEscape"),t(i)):r(i)}}const Hm={name:"headingAtx",resolve:qm,tokenize:Vm};function qm(e,t){let r=e.length-2,n=3,a,i;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},i={type:"chunkText",start:e[n][1].start,end:e[r][1].end,contentType:"text"},Fe(e,n,r-n+1,[["enter",a,t],["enter",i,t],["exit",i,t],["exit",a,t]])),e}function Vm(e,t,r){let n=0;return a;function a(d){return e.enter("atxHeading"),i(d)}function i(d){return e.enter("atxHeadingSequence"),s(d)}function s(d){return d===35&&n++<6?(e.consume(d),s):d===null||ue(d)?(e.exit("atxHeadingSequence"),o(d)):r(d)}function o(d){return d===35?(e.enter("atxHeadingSequence"),l(d)):d===null||K(d)?(e.exit("atxHeading"),t(d)):ee(d)?ne(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||ue(d)?(e.exit("atxHeadingText"),o(d)):(e.consume(d),u)}}const Wm=["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"],Zo=["pre","script","style","textarea"],Jm={concrete:!0,name:"htmlFlow",resolveTo:Ym,tokenize:Xm},Km={partial:!0,tokenize:Zm},Gm={partial:!0,tokenize:Qm};function Ym(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 Xm(e,t,r){const n=this;let a,i,s,o,l;return u;function u(v){return d(v)}function d(v){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(v),c}function c(v){return v===33?(e.consume(v),f):v===47?(e.consume(v),i=!0,S):v===63?(e.consume(v),a=3,n.interrupt?t:w):Ee(v)?(e.consume(v),s=String.fromCharCode(v),x):r(v)}function f(v){return v===45?(e.consume(v),a=2,h):v===91?(e.consume(v),a=5,o=0,y):Ee(v)?(e.consume(v),a=4,n.interrupt?t:w):r(v)}function h(v){return v===45?(e.consume(v),n.interrupt?t:w):r(v)}function y(v){const ve="CDATA[";return v===ve.charCodeAt(o++)?(e.consume(v),o===ve.length?n.interrupt?t:M:y):r(v)}function S(v){return Ee(v)?(e.consume(v),s=String.fromCharCode(v),x):r(v)}function x(v){if(v===null||v===47||v===62||ue(v)){const ve=v===47,Xe=s.toLowerCase();return!ve&&!i&&Zo.includes(Xe)?(a=1,n.interrupt?t(v):M(v)):Wm.includes(s.toLowerCase())?(a=6,ve?(e.consume(v),b):n.interrupt?t(v):M(v)):(a=7,n.interrupt&&!n.parser.lazy[n.now().line]?r(v):i?_(v):T(v))}return v===45||_e(v)?(e.consume(v),s+=String.fromCharCode(v),x):r(v)}function b(v){return v===62?(e.consume(v),n.interrupt?t:M):r(v)}function _(v){return ee(v)?(e.consume(v),_):k(v)}function T(v){return v===47?(e.consume(v),k):v===58||v===95||Ee(v)?(e.consume(v),L):ee(v)?(e.consume(v),T):k(v)}function L(v){return v===45||v===46||v===58||v===95||_e(v)?(e.consume(v),L):z(v)}function z(v){return v===61?(e.consume(v),I):ee(v)?(e.consume(v),z):T(v)}function I(v){return v===null||v===60||v===61||v===62||v===96?r(v):v===34||v===39?(e.consume(v),l=v,q):ee(v)?(e.consume(v),I):B(v)}function q(v){return v===l?(e.consume(v),l=null,U):v===null||K(v)?r(v):(e.consume(v),q)}function B(v){return v===null||v===34||v===39||v===47||v===60||v===61||v===62||v===96||ue(v)?z(v):(e.consume(v),B)}function U(v){return v===47||v===62||ee(v)?T(v):r(v)}function k(v){return v===62?(e.consume(v),D):r(v)}function D(v){return v===null||K(v)?M(v):ee(v)?(e.consume(v),D):r(v)}function M(v){return v===45&&a===2?(e.consume(v),j):v===60&&a===1?(e.consume(v),J):v===62&&a===4?(e.consume(v),ae):v===63&&a===3?(e.consume(v),w):v===93&&a===5?(e.consume(v),Z):K(v)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(Km,xe,H)(v)):v===null||K(v)?(e.exit("htmlFlowData"),H(v)):(e.consume(v),M)}function H(v){return e.check(Gm,R,xe)(v)}function R(v){return e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),F}function F(v){return v===null||K(v)?H(v):(e.enter("htmlFlowData"),M(v))}function j(v){return v===45?(e.consume(v),w):M(v)}function J(v){return v===47?(e.consume(v),s="",re):M(v)}function re(v){if(v===62){const ve=s.toLowerCase();return Zo.includes(ve)?(e.consume(v),ae):M(v)}return Ee(v)&&s.length<8?(e.consume(v),s+=String.fromCharCode(v),re):M(v)}function Z(v){return v===93?(e.consume(v),w):M(v)}function w(v){return v===62?(e.consume(v),ae):v===45&&a===2?(e.consume(v),w):M(v)}function ae(v){return v===null||K(v)?(e.exit("htmlFlowData"),xe(v)):(e.consume(v),ae)}function xe(v){return e.exit("htmlFlow"),t(v)}}function Qm(e,t,r){const n=this;return a;function a(s){return K(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),i):r(s)}function i(s){return n.parser.lazy[n.now().line]?r(s):t(s)}}function Zm(e,t,r){return n;function n(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(gr,t,r)}}const eg={name:"htmlText",tokenize:tg};function tg(e,t,r){const n=this;let a,i,s;return o;function o(w){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(w),l}function l(w){return w===33?(e.consume(w),u):w===47?(e.consume(w),z):w===63?(e.consume(w),T):Ee(w)?(e.consume(w),B):r(w)}function u(w){return w===45?(e.consume(w),d):w===91?(e.consume(w),i=0,y):Ee(w)?(e.consume(w),_):r(w)}function d(w){return w===45?(e.consume(w),h):r(w)}function c(w){return w===null?r(w):w===45?(e.consume(w),f):K(w)?(s=c,J(w)):(e.consume(w),c)}function f(w){return w===45?(e.consume(w),h):c(w)}function h(w){return w===62?j(w):w===45?f(w):c(w)}function y(w){const ae="CDATA[";return w===ae.charCodeAt(i++)?(e.consume(w),i===ae.length?S:y):r(w)}function S(w){return w===null?r(w):w===93?(e.consume(w),x):K(w)?(s=S,J(w)):(e.consume(w),S)}function x(w){return w===93?(e.consume(w),b):S(w)}function b(w){return w===62?j(w):w===93?(e.consume(w),b):S(w)}function _(w){return w===null||w===62?j(w):K(w)?(s=_,J(w)):(e.consume(w),_)}function T(w){return w===null?r(w):w===63?(e.consume(w),L):K(w)?(s=T,J(w)):(e.consume(w),T)}function L(w){return w===62?j(w):T(w)}function z(w){return Ee(w)?(e.consume(w),I):r(w)}function I(w){return w===45||_e(w)?(e.consume(w),I):q(w)}function q(w){return K(w)?(s=q,J(w)):ee(w)?(e.consume(w),q):j(w)}function B(w){return w===45||_e(w)?(e.consume(w),B):w===47||w===62||ue(w)?U(w):r(w)}function U(w){return w===47?(e.consume(w),j):w===58||w===95||Ee(w)?(e.consume(w),k):K(w)?(s=U,J(w)):ee(w)?(e.consume(w),U):j(w)}function k(w){return w===45||w===46||w===58||w===95||_e(w)?(e.consume(w),k):D(w)}function D(w){return w===61?(e.consume(w),M):K(w)?(s=D,J(w)):ee(w)?(e.consume(w),D):U(w)}function M(w){return w===null||w===60||w===61||w===62||w===96?r(w):w===34||w===39?(e.consume(w),a=w,H):K(w)?(s=M,J(w)):ee(w)?(e.consume(w),M):(e.consume(w),R)}function H(w){return w===a?(e.consume(w),a=void 0,F):w===null?r(w):K(w)?(s=H,J(w)):(e.consume(w),H)}function R(w){return w===null||w===34||w===39||w===60||w===61||w===96?r(w):w===47||w===62||ue(w)?U(w):(e.consume(w),R)}function F(w){return w===47||w===62||ue(w)?U(w):r(w)}function j(w){return w===62?(e.consume(w),e.exit("htmlTextData"),e.exit("htmlText"),t):r(w)}function J(w){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),re}function re(w){return ee(w)?ne(e,Z,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(w):Z(w)}function Z(w){return e.enter("htmlTextData"),s(w)}}const wa={name:"labelEnd",resolveAll:ig,resolveTo:sg,tokenize:og},rg={tokenize:lg},ng={tokenize:ug},ag={tokenize:cg};function ig(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&&Fe(e,0,e.length,r),e}function sg(e,t){let r=e.length,n=0,a,i,s,o;for(;r--;)if(a=e[r][1],i){if(a.type==="link"||a.type==="labelLink"&&a._inactive)break;e[r][0]==="enter"&&a.type==="labelLink"&&(a._inactive=!0)}else if(s){if(e[r][0]==="enter"&&(a.type==="labelImage"||a.type==="labelLink")&&!a._balanced&&(i=r,a.type!=="labelLink")){n=2;break}}else a.type==="labelEnd"&&(s=r);const l={type:e[i][1].type==="labelLink"?"link":"image",start:m({},e[i][1].start),end:m({},e[e.length-1][1].end)},u={type:"label",start:m({},e[i][1].start),end:m({},e[s][1].end)},d={type:"labelText",start:m({},e[i+n+2][1].end),end:m({},e[s-2][1].start)};return o=[["enter",l,t],["enter",u,t]],o=je(o,e.slice(i+1,i+n+3)),o=je(o,[["enter",d,t]]),o=je(o,tn(t.parser.constructs.insideSpan.null,e.slice(i+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]]),Fe(e,i,e.length,o),e}function og(e,t,r){const n=this;let a=n.events.length,i,s;for(;a--;)if((n.events[a][1].type==="labelImage"||n.events[a][1].type==="labelLink")&&!n.events[a][1]._balanced){i=n.events[a][1];break}return o;function o(f){return i?i._inactive?c(f):(s=n.parser.defined.includes(Ge(n.sliceSerialize({start:i.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(rg,d,s?d:c)(f):f===91?e.attempt(ng,d,s?u:c)(f):s?d(f):c(f)}function u(f){return e.attempt(ag,d,c)(f)}function d(f){return t(f)}function c(f){return i._balanced=!0,r(f)}}function lg(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 ue(c)?br(e,i)(c):i(c)}function i(c){return c===41?d(c):Yo(e,s,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(c)}function s(c){return ue(c)?br(e,l)(c):d(c)}function o(c){return r(c)}function l(c){return c===34||c===39||c===40?Qo(e,u,r,"resourceTitle","resourceTitleMarker","resourceTitleString")(c):d(c)}function u(c){return ue(c)?br(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 ug(e,t,r){const n=this;return a;function a(o){return Xo.call(n,e,i,s,"reference","referenceMarker","referenceString")(o)}function i(o){return n.parser.defined.includes(Ge(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)))?t(o):r(o)}function s(o){return r(o)}}function cg(e,t,r){return n;function n(i){return e.enter("reference"),e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),a}function a(i){return i===93?(e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),e.exit("reference"),t):r(i)}}const dg={name:"labelStartImage",resolveAll:wa.resolveAll,tokenize:hg};function hg(e,t,r){const n=this;return a;function a(o){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(o),e.exit("labelImageMarker"),i}function i(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 fg={name:"labelStartLink",resolveAll:wa.resolveAll,tokenize:pg};function pg(e,t,r){const n=this;return a;function a(s){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(s),e.exit("labelMarker"),e.exit("labelLink"),i}function i(s){return s===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(s):t(s)}}const xa={name:"lineEnding",tokenize:mg};function mg(e,t){return r;function r(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),ne(e,t,"linePrefix")}}const rn={name:"thematicBreak",tokenize:gg};function gg(e,t,r){let n=0,a;return i;function i(u){return e.enter("thematicBreak"),s(u)}function s(u){return a=u,o(u)}function o(u){return u===a?(e.enter("thematicBreakSequence"),l(u)):n>=3&&(u===null||K(u))?(e.exit("thematicBreak"),t(u)):r(u)}function l(u){return u===a?(e.consume(u),n++,l):(e.exit("thematicBreakSequence"),ee(u)?ne(e,o,"whitespace")(u):o(u))}}const Ne={continuation:{tokenize:xg},exit:Sg,name:"list",tokenize:wg},yg={partial:!0,tokenize:kg},bg={partial:!0,tokenize:vg};function wg(e,t,r){const n=this,a=n.events[n.events.length-1];let i=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,s=0;return o;function o(h){const y=n.containerState.type||(h===42||h===43||h===45?"listUnordered":"listOrdered");if(y==="listUnordered"?!n.containerState.marker||h===n.containerState.marker:ga(h)){if(n.containerState.type||(n.containerState.type=y,e.enter(y,{_container:!0})),y==="listUnordered")return e.enter("listItemPrefix"),h===42||h===45?e.check(rn,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 ga(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(gr,n.interrupt?r:d,e.attempt(yg,f,c))}function d(h){return n.containerState.initialBlankLine=!0,i++,f(h)}function c(h){return ee(h)?(e.enter("listItemPrefixWhitespace"),e.consume(h),e.exit("listItemPrefixWhitespace"),f):r(h)}function f(h){return n.containerState.size=i+n.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(h)}}function xg(e,t,r){const n=this;return n.containerState._closeFlow=void 0,e.check(gr,a,i);function a(o){return n.containerState.furtherBlankLines=n.containerState.furtherBlankLines||n.containerState.initialBlankLine,ne(e,t,"listItemIndent",n.containerState.size+1)(o)}function i(o){return n.containerState.furtherBlankLines||!ee(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(bg,t,s)(o))}function s(o){return n.containerState._closeFlow=!0,n.interrupt=void 0,ne(e,e.attempt(Ne,t,r),"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function vg(e,t,r){const n=this;return ne(e,a,"listItemIndent",n.containerState.size+1);function a(i){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(i):r(i)}}function Sg(e){e.exit(this.containerState.type)}function kg(e,t,r){const n=this;return ne(e,a,"listItemPrefixWhitespace",n.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(i){const s=n.events[n.events.length-1];return!ee(i)&&s&&s[1].type==="listItemPrefixWhitespace"?t(i):r(i)}}const el={name:"setextUnderline",resolveTo:_g,tokenize:Tg};function _g(e,t){let r=e.length,n,a,i;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),!i&&e[r][1].type==="definition"&&(i=r);const s={type:"setextHeading",start:m({},e[n][1].start),end:m({},e[e.length-1][1].end)};return e[a][1].type="setextHeadingText",i?(e.splice(a,0,["enter",s,t]),e.splice(i+1,0,["exit",e[n][1],t]),e[n][1].end=m({},e[i][1].end)):e[n][1]=s,e.push(["exit",s,t]),e}function Tg(e,t,r){const n=this;let a;return i;function i(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,s(u)):r(u)}function s(u){return e.enter("setextHeadingLineSequence"),o(u)}function o(u){return u===a?(e.consume(u),o):(e.exit("setextHeadingLineSequence"),ee(u)?ne(e,l,"lineSuffix")(u):l(u))}function l(u){return u===null||K(u)?(e.exit("setextHeadingLine"),t(u)):r(u)}}const Cg={tokenize:Ig};function Ig(e){const t=this,r=e.attempt(gr,n,e.attempt(this.parser.constructs.flowInitial,a,ne(e,e.attempt(this.parser.constructs.flow,a,e.attempt(Nm,a)),"linePrefix")));return r;function n(i){if(i===null){e.consume(i);return}return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,r}function a(i){if(i===null){e.consume(i);return}return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,r}}const Eg={resolveAll:rl()},Ag=tl("string"),Pg=tl("text");function tl(e){return{resolveAll:rl(e==="text"?Mg:void 0),tokenize:t};function t(r){const n=this,a=this.parser.constructs[e],i=r.attempt(a,s,o);return s;function s(d){return u(d)?i(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"),i(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 rl(e){return t;function t(r,n){let a=-1,i;for(;++a<=r.length;)i===void 0?r[a]&&r[a][1].type==="data"&&(i=a,a++):(!r[a]||r[a][1].type!=="data")&&(a!==i+2&&(r[i][1].end=r[a-1][1].end,r.splice(i+2,a-i-2),a=i+2),i=void 0);return e?e(r,n):r}}function Mg(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 i=a.length,s=-1,o=0,l;for(;i--;){const u=a[i];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){i++;break}}if(t._contentTypeTextTrailing&&r===e.length&&(o=0),o){const u={type:r===e.length||l||o<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?s:n.start._bufferIndex+s,_index:n.start._index+i,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 Ng=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:{null:[42,95]},contentInitial:{91:Bm},disable:{null:[]},document:{42:Ne,43:Ne,45:Ne,48:Ne,49:Ne,50:Ne,51:Ne,52:Ne,53:Ne,54:Ne,55:Ne,56:Ne,57:Ne,62:qo},flow:{35:Hm,42:rn,45:[el,rn],60:Jm,61:el,95:rn,96:Ko,126:Ko},flowInitial:{[-2]:ba,[-1]:ba,32:ba},insideSpan:{null:[ya,Eg]},string:{38:Wo,92:Vo},text:{[-5]:xa,[-4]:xa,[-3]:xa,33:dg,38:Wo,42:ya,60:[fm,eg],91:fg,92:[$m,Vo],93:wa,95:ya,96:Cm}},Symbol.toStringTag,{value:"Module"}));function Lg(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={},i=[];let s=[],o=[];const l={attempt:q(z),check:q(I),consume:_,enter:T,exit:L,interrupt:q(I,{interrupt:!0})},u={code:null,containerState:{},defineSkip:S,events:[],now:y,parser:e,previous:null,sliceSerialize:f,sliceStream:h,write:c};let d=t.tokenize.call(u,l);return t.resolveAll&&i.push(t),u;function c(D){return s=je(s,D),x(),s[s.length-1]!==null?[]:(B(t,0),u.events=tn(i,u.events,u),u.events)}function f(D,M){return Og(h(D),M)}function h(D){return Dg(s,D)}function y(){const{_bufferIndex:D,_index:M,line:H,column:R,offset:F}=n;return{_bufferIndex:D,_index:M,line:H,column:R,offset:F}}function S(D){a[D.line]=D.column,k()}function x(){let D;for(;n._index<s.length;){const M=s[n._index];if(typeof M=="string")for(D=n._index,n._bufferIndex<0&&(n._bufferIndex=0);n._index===D&&n._bufferIndex<M.length;)b(M.charCodeAt(n._bufferIndex));else b(M)}}function b(D){d=d(D)}function _(D){K(D)?(n.line++,n.column=1,n.offset+=D===-3?2:1,k()):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 T(D,M){const H=M||{};return H.type=D,H.start=y(),u.events.push(["enter",H,u]),o.push(H),H}function L(D){const M=o.pop();return M.end=y(),u.events.push(["exit",M,u]),M}function z(D,M){B(D,M.from)}function I(D,M){M.restore()}function q(D,M){return H;function H(R,F,j){let J,re,Z,w;return Array.isArray(R)?xe(R):"tokenize"in R?xe([R]):ae(R);function ae(pe){return gt;function gt(Qe){const ot=Qe!==null&&pe[Qe],yt=Qe!==null&&pe.null,Jt=[...Array.isArray(ot)?ot:ot?[ot]:[],...Array.isArray(yt)?yt:yt?[yt]:[]];return xe(Jt)(Qe)}}function xe(pe){return J=pe,re=0,pe.length===0?j:v(pe[re])}function v(pe){return gt;function gt(Qe){return w=U(),Z=pe,pe.partial||(u.currentConstruct=pe),pe.name&&u.parser.constructs.disable.null.includes(pe.name)?Xe():pe.tokenize.call(M?Object.assign(Object.create(u),M):u,l,ve,Xe)(Qe)}}function ve(pe){return D(Z,w),F}function Xe(pe){return w.restore(),++re<J.length?v(J[re]):j}}}function B(D,M){D.resolveAll&&!i.includes(D)&&i.push(D),D.resolve&&Fe(u.events,M,u.events.length-M,D.resolve(u.events.slice(M),u)),D.resolveTo&&(u.events=D.resolveTo(u.events,u))}function U(){const D=y(),M=u.previous,H=u.currentConstruct,R=u.events.length,F=Array.from(o);return{from:R,restore:j};function j(){n=D,u.previous=M,u.currentConstruct=H,u.events.length=R,o=F,k()}}function k(){n.line in a&&n.column<2&&(n.column=a[n.line],n.offset+=a[n.line]-1)}}function Dg(e,t){const r=t.start._index,n=t.start._bufferIndex,a=t.end._index,i=t.end._bufferIndex;let s;if(r===a)s=[e[r].slice(n,i)];else{if(s=e.slice(r,a),n>-1){const o=s[0];typeof o=="string"?s[0]=o.slice(n):s.shift()}i>0&&s.push(e[a].slice(0,i))}return s}function Og(e,t){let r=-1;const n=[];let a;for(;++r<e.length;){const i=e[r];let s;if(typeof i=="string")s=i;else switch(i){case-5:{s="\r";break}case-4:{s=`
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(c){}}}}finally{r.releaseLock()}})}function ip(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 sp(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 Zr=new Map;function op(e,t){return{list(){return P(this,null,function*(){const n=[];let i,s=0;do{const l=yield e.listChats({limit:50,cursor:i}),u=l.items||[];Array.isArray(u)&&u.length>0&&n.push(...u),i=l.nextCursor||void 0,s++}while(i&&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 P(this,null,function*(){return{remoteId:Zr.get(n)||n,externalId:void 0}})},rename(n,a){return P(this,null,function*(){yield e.updateChat(n,{title:a})})},archive(n){return P(this,null,function*(){})},unarchive(n){return P(this,null,function*(){})},delete(n){return P(this,null,function*(){yield e.deleteChat(n)})},generateTitle(n,a){return P(this,null,function*(){return new ReadableStream})},fetch(n){return P(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){Zr.set(n,a),t==null||t(n,a)},unstable_Provider:({children:n})=>{const a=os(),i=a==null?void 0:a.remoteId,s=y.useMemo(()=>({load(){return P(this,null,function*(){if(!i)return{messages:[]};try{const u=yield e.getChat(i);return!u.messages||u.messages.length===0?{messages:[]}:{messages:u.messages.map(d=>sp(d))}}catch(u){return{messages:[]}}})},append(u){return P(this,null,function*(){})}}),[i,e]),o=y.useMemo(()=>({history:s}),[s]);return p.jsx(On,{adapters:o,children:n})}}}class lp{constructor(){C(this,"messageMetadata",new Map);C(this,"currentMessageId",null);C(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,E(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 Ct=new lp,co=new Map,ho=[];let en=[];function up(e,t,r=50,n=800){ho.push({question:e,response:t,streamingSpeed:r,initialDelay:n})}function fo(e,t){const{modelId:r,systemPrompt:n,ephemeral:a,enableReasoning:i,onChatCreated:s,onUserMessage:o,onThreadIdUpdate:l,onBeforeRequest:u}=t;let c;return{run(f){return Mr(this,null,function*(){var ce,se,me;const{messages:h,abortSignal:g,context:k}=f,w=ho.shift();if(w){o==null||o();const U=(ce=w.initialDelay)!=null?ce:800;if(U>0&&(yield new Ge(new Promise(ge=>setTimeout(ge,U)))),g!=null&&g.aborted)throw new Error("Request aborted");const oe=w.response.split(" ");let ne="";const _e=w.streamingSpeed||50,Te=`premade-${Date.now()}`;a&&(s==null||s(Te));for(let ge=0;ge<oe.length;ge++){if(g!=null&&g.aborted)throw new Error("Request aborted");ne+=(ge===0?"":" ")+oe[ge],yield{content:[{type:"text",text:ne}]},yield new Ge(new Promise(He=>setTimeout(He,_e+Math.random()*(_e*.5))))}yield{content:[{type:"text",text:ne}]},en.push({role:"user",content:w.question},{role:"assistant",content:w.response});return}const b=k==null?void 0:k.threadId;let I=b;if(!I&&h.length>0){const U=h.find(oe=>oe.role==="user");U&&(I=(typeof U.content=="string"?U.content:Array.isArray(U.content)&&((se=U.content.find(ne=>ne.type==="text"))==null?void 0:se.text)||"").substring(0,50))}let T;b&&(T=Zr.get(b)),!T&&I&&(T=co.get(I)),!T&&c&&(T=c),o==null||o();let B=h,F=-1;for(let U=h.length-1;U>=0;U--)if(h[U].role==="assistant"){F=U;break}(T||F>=0)&&F>=0&&(B=h.slice(F+1));const _=ip(B);if(en.length>0&&!T){const U=en.map(oe=>({role:oe.role,content:oe.content}));_.unshift(...U),en=[]}const $={messages:_,chatId:T||null,systemPrompt:n,ephemeral:a,enableReasoning:i,stream:!0};if(r&&r.trim()!==""&&($.modelId=r),u&&!(yield new Ge(u())))throw new Error("Request blocked");const R=yield new Ge(e.createOrContinueChat($,g));let j="",S="",N;const M=[];let J=0;const z=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;Ct.clear(),Ct.setCurrentMessage(z);const D=()=>{M.length!==J&&(J=M.length,Ct.update({sources:M.length>0?[...M]:void 0}))},Y=()=>{D();const U=[];return S&&U.push({type:"reasoning",text:S}),j&&U.push({type:"text",text:j}),U.length===0&&U.push({type:"text",text:""}),{content:U}};try{for(var x=Nt(ap(R,g)),Se,ve,v;Se=!(ve=yield new Ge(x.next())).done;Se=!1){const U=ve.value;if(g!=null&&g.aborted)throw new Error("Request aborted");const oe=U.id||U.chatId||U.messageId;oe&&!N&&(N=oe,c=oe,s==null||s(oe),b&&l&&(l(b,oe),Zr.set(b,oe)),I&&co.set(I,oe));const ne=U.sources;if(ne&&Array.isArray(ne)&&ne.length>0)for(const ge of ne)M.some(He=>He.sourceId===ge.sourceId)||M.push({sourceId:ge.sourceId,filename:ge.filename||"Unknown",score:(me=ge.score)!=null?me:1,chunkId:ge.chunkId,datasetId:ge.datasetId});const _e=U.reasoning;if(_e&&_e.length>0&&(S+=_e,yield Y()),U.type)switch(U.type){case"source-document":U.sourceId&&M.push({sourceId:U.sourceId,filename:U.title||"Unknown",score:1});continue;case"reasoning-start":continue;case"reasoning-delta":U.delta&&(S+=U.delta),(j||S)&&(yield Y());continue;case"reasoning-end":(j||S)&&(yield Y());continue;case"text-delta":U.delta&&(j+=U.delta),j&&(yield Y());continue;case"error":throw new Error(U.errorText||"Stream error");case"text-start":case"text-end":case"start":case"start-step":case"finish-step":case"finish":continue}const Te=U.delta;if(Te!=null&&(j+=Te),U.content&&(j+=U.content),U.message&&(j+=U.message.content||""),U.finished){(j||S||M.length>0)&&(yield Y());break}(j||S||M.length>0)&&(yield Y())}}catch(ve){v=[ve]}finally{try{Se&&(ve=x.return)&&(yield new Ge(ve.call(x)))}finally{if(v)throw v[0]}}(j||S||M.length>0)&&(yield Y())})}}}function po(){return{accept:".pdf,.docx,.txt,.md,.csv,.json,image/*",add(r){return P(this,arguments,function*({file:t}){let n="file";return t.type.startsWith("image/")?n="image":(t.type.includes("pdf")||t.type.includes("document")||t.type.includes("text")||t.name.endsWith(".pdf")||t.name.endsWith(".docx")||t.name.endsWith(".txt")||t.name.endsWith(".md")||t.name.endsWith(".csv")||t.name.endsWith(".json"))&&(n="document"),{id:`${t.name}-${Date.now()}`,type:n,name:t.name,contentType:t.type,file:t,status:{type:"requires-action",reason:"composer-send"}}})},remove(){return P(this,null,function*(){})},send(t){return P(this,null,function*(){if(t.type==="image"&&t.file){const r=yield new Promise((n,a)=>{const i=new FileReader;i.onload=()=>n(i.result),i.onerror=a,i.readAsDataURL(t.file)});return E(m({},t),{status:{type:"complete"},content:[{type:"image",image:r}]})}return E(m({},t),{status:{type:"complete"},content:[]})})}}}function cp({children:e,baseUrl:t,sessionToken:r,isProxyMode:n=!1,mode:a="multiChat",modelId:i,onModelChange:s,ephemeral:o=!1,systemPrompt:l,enableReasoning:u=!1,initialThreadId:c,onError:d,onChatCreated:f,onUserMessage:h,onThreadIdUpdate:g,onChatsLoaded:k,enableAttachments:w=!1,onBeforeRequest:b}){const I=y.useMemo(()=>new uo(t,r||void 0,n),[t,r,n]),[T,B]=y.useState(i||null);y.useEffect(()=>{i&&B(i)},[i]);const F=y.useCallback(R=>{f==null||f(R)},[f]),_=y.useCallback((R,j)=>{g==null||g(R,j)},[g]),$=y.useMemo(()=>fo(I,{modelId:T||void 0,systemPrompt:l,ephemeral:o,enableReasoning:u,onChatCreated:F,onUserMessage:h,onBeforeRequest:b}),[I,T,l,o,u,F,h,b]);return a==="singleChat"?p.jsx(dp,{modelAdapter:$,enableAttachments:w,children:e}):p.jsx(hp,{client:I,modelAdapterOptions:{modelId:T||void 0,systemPrompt:l,ephemeral:o,enableReasoning:u,onChatCreated:F,onUserMessage:h,onBeforeRequest:b},initialThreadId:c,onChatsLoaded:k,onThreadIdUpdate:_,onError:d,enableAttachments:w,children:e})}function dp({modelAdapter:e,enableAttachments:t,children:r}){const n=y.useMemo(()=>t?po():void 0,[t]),a=ys(e,{adapters:m({},n&&{attachments:n})});return p.jsx(ds,{runtime:a,children:r})}function hp({client:e,modelAdapterOptions:t,initialThreadId:r,onChatsLoaded:n,onThreadIdUpdate:a,onError:i,enableAttachments:s,children:o}){const l=y.useMemo(()=>op(e,(k,w)=>{a==null||a(k,w)}),[e,a]),u=y.useCallback((k,w)=>{l.updateRemoteId&&l.updateRemoteId(k,w),a==null||a(k,w)},[l,a]),c=y.useMemo(()=>E(m({},l),{list(){return P(this,null,function*(){const w=yield l.list();return n==null||n(),w})}}),[l,n]);y.useEffect(()=>{window.__cuadraThreadListAdapter=c,window.__cuadraThreadListRuntime=null},[c]);const d=y.useMemo(()=>fo(e,E(m({},t),{onThreadIdUpdate:u})),[e,t,u]),f=y.useMemo(()=>s?po():void 0,[s]),h=y.useCallback(()=>ys(d,{adapters:m({},f&&{attachments:f})}),[d,f]),g=ks({adapter:c,runtimeHook:h});return y.useEffect(()=>{window.__cuadraThreadListRuntime=g},[g]),p.jsx(ds,{runtime:g,children:o})}function Pv(){}function Nv(){}function fp(e,t){const r={};return(e[e.length-1]===""?[...e,""]:e).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}const pp=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,mp=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,gp={};function mo(e,t){return(gp.jsx?mp:pp).test(e)}const yp=/[ \t\n\f\r]/g;function bp(e){return typeof e=="object"?e.type==="text"?go(e.value):!1:go(e)}function go(e){return e.replace(yp,"")===""}class hr{constructor(t,r,n){this.normal=r,this.property=t,n&&(this.space=n)}}hr.prototype.normal={},hr.prototype.property={},hr.prototype.space=void 0;function yo(e,t){const r={},n={};for(const a of e)Object.assign(r,a.property),Object.assign(n,a.normal);return new hr(r,n,t)}function ra(e){return e.toLowerCase()}class Be{constructor(t,r){this.attribute=r,this.property=t}}Be.prototype.attribute="",Be.prototype.booleanish=!1,Be.prototype.boolean=!1,Be.prototype.commaOrSpaceSeparated=!1,Be.prototype.commaSeparated=!1,Be.prototype.defined=!1,Be.prototype.mustUseProperty=!1,Be.prototype.number=!1,Be.prototype.overloadedBoolean=!1,Be.prototype.property="",Be.prototype.spaceSeparated=!1,Be.prototype.space=void 0;let wp=0;const X=It(),be=It(),na=It(),L=It(),de=It(),$t=It(),$e=It();function It(){return Eu(2,++wp)}const aa=Object.freeze(Object.defineProperty({__proto__:null,boolean:X,booleanish:be,commaOrSpaceSeparated:$e,commaSeparated:$t,number:L,overloadedBoolean:na,spaceSeparated:de},Symbol.toStringTag,{value:"Module"})),ia=Object.keys(aa);class sa extends Be{constructor(t,r,n,a){let i=-1;if(super(t,r),bo(this,"space",a),typeof n=="number")for(;++i<ia.length;){const s=ia[i];bo(this,ia[i],(n&aa[s])===aa[s])}}}sa.prototype.defined=!0;function bo(e,t,r){r&&(e[t]=r)}function Ut(e){const t={},r={};for(const[n,a]of Object.entries(e.properties)){const i=new sa(n,e.transform(e.attributes||{},n),a,e.space);e.mustUseProperty&&e.mustUseProperty.includes(n)&&(i.mustUseProperty=!0),t[n]=i,r[ra(n)]=n,r[ra(i.attribute)]=n}return new hr(t,r,e.space)}const wo=Ut({properties:{ariaActiveDescendant:null,ariaAtomic:be,ariaAutoComplete:null,ariaBusy:be,ariaChecked:be,ariaColCount:L,ariaColIndex:L,ariaColSpan:L,ariaControls:de,ariaCurrent:null,ariaDescribedBy:de,ariaDetails:null,ariaDisabled:be,ariaDropEffect:de,ariaErrorMessage:null,ariaExpanded:be,ariaFlowTo:de,ariaGrabbed:be,ariaHasPopup:null,ariaHidden:be,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:de,ariaLevel:L,ariaLive:null,ariaModal:be,ariaMultiLine:be,ariaMultiSelectable:be,ariaOrientation:null,ariaOwns:de,ariaPlaceholder:null,ariaPosInSet:L,ariaPressed:be,ariaReadOnly:be,ariaRelevant:null,ariaRequired:be,ariaRoleDescription:de,ariaRowCount:L,ariaRowIndex:L,ariaRowSpan:L,ariaSelected:be,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 xo(e,t){return t in e?e[t]:t}function vo(e,t){return xo(e,t.toLowerCase())}const xp=Ut({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:$t,acceptCharset:de,accessKey:de,action:null,allow:null,allowFullScreen:X,allowPaymentRequest:X,allowUserMedia:X,alt:null,as:null,async:X,autoCapitalize:null,autoComplete:de,autoFocus:X,autoPlay:X,blocking:de,capture:null,charSet:null,checked:X,cite:null,className:de,cols:L,colSpan:null,content:null,contentEditable:be,controls:X,controlsList:de,coords:L|$t,crossOrigin:null,data:null,dateTime:null,decoding:null,default:X,defer:X,dir:null,dirName:null,disabled:X,download:na,draggable:be,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:X,formTarget:null,headers:de,height:L,hidden:na,high:L,href:null,hrefLang:null,htmlFor:de,httpEquiv:de,id:null,imageSizes:null,imageSrcSet:null,inert:X,inputMode:null,integrity:null,is:null,isMap:X,itemId:null,itemProp:de,itemRef:de,itemScope:X,itemType:de,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:X,low:L,manifest:null,max:null,maxLength:L,media:null,method:null,min:null,minLength:L,multiple:X,muted:X,name:null,nonce:null,noModule:X,noValidate:X,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:X,optimum:L,pattern:null,ping:de,placeholder:null,playsInline:X,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:X,referrerPolicy:null,rel:de,required:X,reversed:X,rows:L,rowSpan:L,sandbox:de,scope:null,scoped:X,seamless:X,selected:X,shadowRootClonable:X,shadowRootDelegatesFocus:X,shadowRootMode:null,shape:null,size:L,sizes:null,slot:null,span:L,spellCheck:be,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:X,useMap:null,value:be,width:L,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:de,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:X,declare:X,event:null,face:null,frame:null,frameBorder:null,hSpace:L,leftMargin:L,link:null,longDesc:null,lowSrc:null,marginHeight:L,marginWidth:L,noResize:X,noHref:X,noShade:X,noWrap:X,object:null,profile:null,prompt:null,rev:null,rightMargin:L,rules:null,scheme:null,scrolling:be,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:X,disableRemotePlayback:X,prefix:null,property:null,results:L,security:null,unselectable:null},space:"html",transform:vo}),vp=Ut({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:$e,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:de,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:X,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:$t,g2:$t,glyphName:$t,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:$e,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:de,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:L,pointsAtY:L,pointsAtZ:L,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:$e,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:$e,rev:$e,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:$e,requiredFeatures:$e,requiredFonts:$e,requiredFormats:$e,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:$e,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:$e,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:$e,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:xo}),ko=Ut({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()}}),So=Ut({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:vo}),_o=Ut({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),kp={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"},Sp=/[A-Z]/g,To=/-[a-z]/g,_p=/^data[-\w.:]+$/i;function Tp(e,t){const r=ra(t);let n=t,a=Be;if(r in e.normal)return e.property[e.normal[r]];if(r.length>4&&r.slice(0,4)==="data"&&_p.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(To,Ip);n="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!To.test(i)){let s=i.replace(Sp,Cp);s.charAt(0)!=="-"&&(s="-"+s),t="data"+s}}a=sa}return new a(n,t)}function Cp(e){return"-"+e.toLowerCase()}function Ip(e){return e.charAt(1).toUpperCase()}const Ep=yo([wo,xp,ko,So,_o],"html"),oa=yo([wo,vp,ko,So,_o],"svg");function Ap(e){return e.join(" ").trim()}var Ht={},la,Co;function Mp(){if(Co)return la;Co=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,r=/^\s*/,n=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,s=/^[;\s]*/,o=/^\s+|\s+$/g,l=`
8
+ `,u="/",c="*",d="",f="comment",h="declaration";function g(w,b){if(typeof w!="string")throw new TypeError("First argument must be a string");if(!w)return[];b=b||{};var I=1,T=1;function B(z){var D=z.match(t);D&&(I+=D.length);var Y=z.lastIndexOf(l);T=~Y?z.length-Y:T+z.length}function F(){var z={line:I,column:T};return function(D){return D.position=new _(z),j(),D}}function _(z){this.start=z,this.end={line:I,column:T},this.source=b.source}_.prototype.content=w;function $(z){var D=new Error(b.source+":"+I+":"+T+": "+z);if(D.reason=z,D.filename=b.source,D.line=I,D.column=T,D.source=w,!b.silent)throw D}function R(z){var D=z.exec(w);if(D){var Y=D[0];return B(Y),w=w.slice(Y.length),D}}function j(){R(r)}function S(z){var D;for(z=z||[];D=N();)D!==!1&&z.push(D);return z}function N(){var z=F();if(!(u!=w.charAt(0)||c!=w.charAt(1))){for(var D=2;d!=w.charAt(D)&&(c!=w.charAt(D)||u!=w.charAt(D+1));)++D;if(D+=2,d===w.charAt(D-1))return $("End of comment missing");var Y=w.slice(2,D-2);return T+=2,B(Y),w=w.slice(D),T+=2,z({type:f,comment:Y})}}function M(){var z=F(),D=R(n);if(D){if(N(),!R(a))return $("property missing ':'");var Y=R(i),ce=z({type:h,property:k(D[0].replace(e,d)),value:Y?k(Y[0].replace(e,d)):d});return R(s),ce}}function J(){var z=[];S(z);for(var D;D=M();)D!==!1&&(z.push(D),S(z));return z}return j(),J()}function k(w){return w?w.replace(o,d):d}return la=g,la}var Io;function Pp(){if(Io)return Ht;Io=1;var e=Ht&&Ht.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Ht,"__esModule",{value:!0}),Ht.default=r;const t=e(Mp());function r(n,a){let i=null;if(!n||typeof n!="string")return i;const s=(0,t.default)(n),o=typeof a=="function";return s.forEach(l=>{if(l.type!=="declaration")return;const{property:u,value:c}=l;o?a(u,c,l):c&&(i=i||{},i[u]=c)}),i}return Ht}var fr={},Eo;function Np(){if(Eo)return fr;Eo=1,Object.defineProperty(fr,"__esModule",{value:!0}),fr.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,r=/^[^-]+$/,n=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,i=function(u){return!u||r.test(u)||e.test(u)},s=function(u,c){return c.toUpperCase()},o=function(u,c){return"".concat(c,"-")},l=function(u,c){return c===void 0&&(c={}),i(u)?u:(u=u.toLowerCase(),c.reactCompat?u=u.replace(a,o):u=u.replace(n,o),u.replace(t,s))};return fr.camelCase=l,fr}var pr,Ao;function Lp(){if(Ao)return pr;Ao=1;var e=pr&&pr.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(Pp()),r=Np();function n(a,i){var s={};return!a||typeof a!="string"||(0,t.default)(a,function(o,l){o&&l&&(s[(0,r.camelCase)(o,i)]=l)}),s}return n.default=n,pr=n,pr}var Dp=Lp();const Op=Pr(Dp),Mo=Po("end"),ua=Po("start");function Po(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 Fp(e){const t=ua(e),r=Mo(e);if(t&&r)return{start:t,end:r}}function mr(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?No(e.position):"start"in e||"end"in e?No(e):"line"in e||"column"in e?ca(e):""}function ca(e){return Lo(e&&e.line)+":"+Lo(e&&e.column)}function No(e){return ca(e&&e.start)+"-"+ca(e&&e.end)}function Lo(e){return e&&typeof e=="number"?e:1}class Ee extends Error{constructor(t,r,n){super(),typeof r=="string"&&(n=r,r=void 0);let a="",i={},s=!1;if(r&&("line"in r&&"column"in r?i={place:r}:"start"in r&&"end"in r?i={place:r}:"type"in r?i={ancestors:[r],place:r.position}:i=m({},r)),typeof t=="string"?a=t:!i.cause&&t&&(s=!0,a=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof n=="string"){const l=n.indexOf(":");l===-1?i.ruleId=n:(i.source=n.slice(0,l),i.ruleId=n.slice(l+1))}if(!i.place&&i.ancestors&&i.ancestors){const l=i.ancestors[i.ancestors.length-1];l&&(i.place=l.position)}const o=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.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=mr(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=s&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Ee.prototype.file="",Ee.prototype.name="",Ee.prototype.reason="",Ee.prototype.message="",Ee.prototype.stack="",Ee.prototype.column=void 0,Ee.prototype.line=void 0,Ee.prototype.ancestors=void 0,Ee.prototype.cause=void 0,Ee.prototype.fatal=void 0,Ee.prototype.place=void 0,Ee.prototype.ruleId=void 0,Ee.prototype.source=void 0;const da={}.hasOwnProperty,Bp=new Map,zp=/[A-Z]/g,Rp=new Set(["table","tbody","thead","tfoot","tr"]),jp=new Set(["td","th"]),Do="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function $p(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=Yp(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=Kp(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"?oa:Ep,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=Oo(a,e,void 0);return i&&typeof i!="string"?i:a.create(e,a.Fragment,{children:i||void 0},void 0)}function Oo(e,t,r){if(t.type==="element")return Up(e,t,r);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return Hp(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return Vp(e,t,r);if(t.type==="mdxjsEsm")return qp(e,t);if(t.type==="root")return Wp(e,t,r);if(t.type==="text")return Jp(e,t)}function Up(e,t,r){const n=e.schema;let a=n;t.tagName.toLowerCase()==="svg"&&n.space==="html"&&(a=oa,e.schema=a),e.ancestors.push(t);const i=Bo(e,t.tagName,!1),s=Gp(e,t);let o=fa(e,t);return Rp.has(t.tagName)&&(o=o.filter(function(l){return typeof l=="string"?!bp(l):!0})),Fo(e,s,i,t),ha(s,o),e.ancestors.pop(),e.schema=n,e.create(t,i,s,r)}function Hp(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)}gr(e,t.position)}function qp(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);gr(e,t.position)}function Vp(e,t,r){const n=e.schema;let a=n;t.name==="svg"&&n.space==="html"&&(a=oa,e.schema=a),e.ancestors.push(t);const i=t.name===null?e.Fragment:Bo(e,t.name,!0),s=Xp(e,t),o=fa(e,t);return Fo(e,s,i,t),ha(s,o),e.ancestors.pop(),e.schema=n,e.create(t,i,s,r)}function Wp(e,t,r){const n={};return ha(n,fa(e,t)),e.create(t,e.Fragment,n,r)}function Jp(e,t){return t.value}function Fo(e,t,r,n){typeof r!="string"&&r!==e.Fragment&&e.passNode&&(t.node=n)}function ha(e,t){if(t.length>0){const r=t.length>1?t:t[0];r&&(e.children=r)}}function Kp(e,t,r){return n;function n(a,i,s,o){const u=Array.isArray(s.children)?r:t;return o?u(i,s,o):u(i,s)}}function Yp(e,t){return r;function r(n,a,i,s){const o=Array.isArray(i.children),l=ua(n);return t(a,i,s,o,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function Gp(e,t){const r={};let n,a;for(a in t.properties)if(a!=="children"&&da.call(t.properties,a)){const i=Qp(e,a,t.properties[a]);if(i){const[s,o]=i;e.tableCellAlignToStyle&&s==="align"&&typeof o=="string"&&jp.has(t.tagName)?n=o:r[s]=o}}if(n){const i=r.style||(r.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=n}return r}function Xp(e,t){const r={};for(const n of t.attributes)if(n.type==="mdxJsxExpressionAttribute")if(n.data&&n.data.estree&&e.evaluater){const i=n.data.estree.body[0];i.type;const s=i.expression;s.type;const o=s.properties[0];o.type,Object.assign(r,e.evaluater.evaluateExpression(o.argument))}else gr(e,t.position);else{const a=n.name;let i;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,i=e.evaluater.evaluateExpression(o.expression)}else gr(e,t.position);else i=n.value===null?!0:n.value;r[a]=i}return r}function fa(e,t){const r=[];let n=-1;const a=e.passKeys?new Map:Bp;for(;++n<t.children.length;){const i=t.children[n];let s;if(e.passKeys){const l=i.type==="element"?i.tagName:i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement"?i.name:void 0;if(l){const u=a.get(l)||0;s=l+"-"+u,a.set(l,u+1)}}const o=Oo(e,i,s);o!==void 0&&r.push(o)}return r}function Qp(e,t,r){const n=Tp(e.schema,t);if(!(r==null||typeof r=="number"&&Number.isNaN(r))){if(Array.isArray(r)&&(r=n.commaSeparated?fp(r):Ap(r)),n.property==="style"){let a=typeof r=="object"?r:Zp(e,String(r));return e.stylePropertyNameCase==="css"&&(a=em(a)),["style",a]}return[e.elementAttributeNameCase==="react"&&n.space?kp[n.property]||n.property:n.attribute,r]}}function Zp(e,t){try{return Op(t,{reactCompat:!0})}catch(r){if(e.ignoreInvalidStyle)return{};const n=r,a=new Ee("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=Do+"#cannot-parse-style-attribute",a}}function Bo(e,t,r){let n;if(!r)n={type:"Literal",value:t};else if(t.includes(".")){const a=t.split(".");let i=-1,s;for(;++i<a.length;){const o=mo(a[i])?{type:"Identifier",name:a[i]}:{type:"Literal",value:a[i]};s=s?{type:"MemberExpression",object:s,property:o,computed:!!(i&&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 a=n.value;return da.call(e.components,a)?e.components[a]:a}if(e.evaluater)return e.evaluater.evaluateExpression(n);gr(e)}function gr(e,t){const r=new Ee("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=Do+"#cannot-handle-mdx-estrees-without-createevaluater",r}function em(e){const t={};let r;for(r in e)da.call(e,r)&&(t[tm(r)]=e[r]);return t}function tm(e){let t=e.replace(zp,rm);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function rm(e){return"-"+e.toLowerCase()}const pa={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"]},nm={};function ma(e,t){const r=nm,n=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,a=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return zo(e,n,a)}function zo(e,t,r){if(am(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 Ro(e.children,t,r)}return Array.isArray(e)?Ro(e,t,r):""}function Ro(e,t,r){const n=[];let a=-1;for(;++a<e.length;)n[a]=zo(e[a],t,r);return n.join("")}function am(e){return!!(e&&typeof e=="object")}const jo=document.createElement("i");function ga(e){const t="&"+e+";";jo.innerHTML=t;const r=jo.textContent;return r.charCodeAt(r.length-1)===59&&e!=="semi"||r===t?!1:r}function Ue(e,t,r,n){const a=e.length;let i=0,s;if(t<0?t=-t>a?0:a+t:t=t>a?a: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);i<n.length;)s=n.slice(i,i+1e4),s.unshift(t,0),e.splice(...s),i+=1e4,t+=1e4}function We(e,t){return e.length>0?(Ue(e,e.length,0,t),e):t}const $o={}.hasOwnProperty;function Uo(e){const t={};let r=-1;for(;++r<e.length;)im(t,e[r]);return t}function im(e,t){let r;for(r in t){const a=($o.call(e,r)?e[r]:void 0)||(e[r]={}),i=t[r];let s;if(i)for(s in i){$o.call(a,s)||(a[s]=[]);const o=i[s];sm(a[s],Array.isArray(o)?o:o?[o]:[])}}}function sm(e,t){let r=-1;const n=[];for(;++r<t.length;)(t[r].add==="after"?e:n).push(t[r]);Ue(e,0,0,n)}function Ho(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 tt(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Le=mt(/[A-Za-z]/),Ae=mt(/[\dA-Za-z]/),om=mt(/[#-'*+\--9=?A-Z^-~]/);function tn(e){return e!==null&&(e<32||e===127)}const ya=mt(/\d/),lm=mt(/[\dA-Fa-f]/),um=mt(/[!-/:-@[-`{-~]/);function W(e){return e!==null&&e<-2}function ue(e){return e!==null&&(e<0||e===32)}function Q(e){return e===-2||e===-1||e===32}const rn=mt(new RegExp("\\p{P}|\\p{S}","u")),Et=mt(/\s/);function mt(e){return t;function t(r){return r!==null&&r>-1&&e.test(String.fromCharCode(r))}}function qt(e){const t=[];let r=-1,n=0,a=0;for(;++r<e.length;){const i=e.charCodeAt(r);let s="";if(i===37&&Ae(e.charCodeAt(r+1))&&Ae(e.charCodeAt(r+2)))a=2;else if(i<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(i))||(s=String.fromCharCode(i));else if(i>55295&&i<57344){const o=e.charCodeAt(r+1);i<56320&&o>56319&&o<57344?(s=String.fromCharCode(i,o),a=1):s="�"}else s=String.fromCharCode(i);s&&(t.push(e.slice(n,r),encodeURIComponent(s)),n=r+a+1,s=""),a&&(r+=a,a=0)}return t.join("")+e.slice(n)}function ee(e,t,r,n){const a=n?n-1:Number.POSITIVE_INFINITY;let i=0;return s;function s(l){return Q(l)?(e.enter(r),o(l)):t(l)}function o(l){return Q(l)&&i++<a?(e.consume(l),o):(e.exit(r),t(l))}}const cm={tokenize:dm};function dm(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"),ee(e,t,"linePrefix")}function a(o){return e.enter("paragraph"),i(o)}function i(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"),i):(e.consume(o),s)}}const hm={tokenize:fm},qo={tokenize:pm};function fm(e){const t=this,r=[];let n=0,a,i,s;return o;function o(T){if(n<r.length){const B=r[n];return t.containerState=B[1],e.attempt(B[0].continuation,l,u)(T)}return u(T)}function l(T){if(n++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,a&&I();const B=t.events.length;let F=B,_;for(;F--;)if(t.events[F][0]==="exit"&&t.events[F][1].type==="chunkFlow"){_=t.events[F][1].end;break}b(n);let $=B;for(;$<t.events.length;)t.events[$][1].end=m({},_),$++;return Ue(t.events,F+1,0,t.events.slice(B)),t.events.length=$,u(T)}return o(T)}function u(T){if(n===r.length){if(!a)return f(T);if(a.currentConstruct&&a.currentConstruct.concrete)return g(T);t.interrupt=!!(a.currentConstruct&&!a._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(qo,c,d)(T)}function c(T){return a&&I(),b(n),f(T)}function d(T){return t.parser.lazy[t.now().line]=n!==r.length,s=t.now().offset,g(T)}function f(T){return t.containerState={},e.attempt(qo,h,g)(T)}function h(T){return n++,r.push([t.currentConstruct,t.containerState]),f(T)}function g(T){if(T===null){a&&I(),b(0),e.consume(T);return}return a=a||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:a,contentType:"flow",previous:i}),k(T)}function k(T){if(T===null){w(e.exit("chunkFlow"),!0),b(0),e.consume(T);return}return W(T)?(e.consume(T),w(e.exit("chunkFlow")),n=0,t.interrupt=void 0,o):(e.consume(T),k)}function w(T,B){const F=t.sliceStream(T);if(B&&F.push(null),T.previous=i,i&&(i.next=T),i=T,a.defineSkip(T.start),a.write(F),t.parser.lazy[T.start.line]){let _=a.events.length;for(;_--;)if(a.events[_][1].start.offset<s&&(!a.events[_][1].end||a.events[_][1].end.offset>s))return;const $=t.events.length;let R=$,j,S;for(;R--;)if(t.events[R][0]==="exit"&&t.events[R][1].type==="chunkFlow"){if(j){S=t.events[R][1].end;break}j=!0}for(b(n),_=$;_<t.events.length;)t.events[_][1].end=m({},S),_++;Ue(t.events,R+1,0,t.events.slice($)),t.events.length=_}}function b(T){let B=r.length;for(;B-- >T;){const F=r[B];t.containerState=F[1],F[0].exit.call(t,e)}r.length=T}function I(){a.write([null]),i=void 0,a=void 0,t.containerState._closeFlow=void 0}}function pm(e,t,r){return ee(e,e.attempt(this.parser.constructs.document,t,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Vt(e){if(e===null||ue(e)||Et(e))return 1;if(rn(e))return 2}function nn(e,t,r){const n=[];let a=-1;for(;++a<e.length;){const i=e[a].resolveAll;i&&!n.includes(i)&&(t=i(t,r),n.push(i))}return t}const ba={name:"attention",resolveAll:mm,tokenize:gm};function mm(e,t){let r=-1,n,a,i,s,o,l,u,c;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 d=m({},e[n][1].end),f=m({},e[r][1].start);Vo(d,-l),Vo(f,l),s={type:l>1?"strongSequence":"emphasisSequence",start:d,end:m({},e[n][1].end)},o={type:l>1?"strongSequence":"emphasisSequence",start:m({},e[r][1].start),end:f},i={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({},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=We(u,[["enter",e[n][1],t],["exit",e[n][1],t]])),u=We(u,[["enter",a,t],["enter",s,t],["exit",s,t],["enter",i,t]]),u=We(u,nn(t.parser.constructs.insideSpan.null,e.slice(n+1,r),t)),u=We(u,[["exit",i,t],["enter",o,t],["exit",o,t],["exit",a,t]]),e[r][1].end.offset-e[r][1].start.offset?(c=2,u=We(u,[["enter",e[r][1],t],["exit",e[r][1],t]])):c=0,Ue(e,n-1,r-n+3,u),r=n+u.length-c-2;break}}for(r=-1;++r<e.length;)e[r][1].type==="attentionSequence"&&(e[r][1].type="data");return e}function gm(e,t){const r=this.parser.constructs.attentionMarkers.null,n=this.previous,a=Vt(n);let i;return s;function s(l){return i=l,e.enter("attentionSequence"),o(l)}function o(l){if(l===i)return e.consume(l),o;const u=e.exit("attentionSequence"),c=Vt(l),d=!c||c===2&&a||r.includes(l),f=!a||a===2&&c||r.includes(n);return u._open=!!(i===42?d:d&&(a||!f)),u._close=!!(i===42?f:f&&(c||!d)),t(l)}}function Vo(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const ym={name:"autolink",tokenize:bm};function bm(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"),i}function i(h){return Le(h)?(e.consume(h),s):h===64?r(h):u(h)}function s(h){return h===43||h===45||h===46||Ae(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||Ae(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||tn(h)?r(h):(e.consume(h),l)}function u(h){return h===64?(e.consume(h),c):om(h)?(e.consume(h),u):r(h)}function c(h){return Ae(h)?d(h):r(h)}function d(h){return h===46?(e.consume(h),n=0,c):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||Ae(h))&&n++<63){const g=h===45?f:d;return e.consume(h),g}return r(h)}}const yr={partial:!0,tokenize:wm};function wm(e,t,r){return n;function n(i){return Q(i)?ee(e,a,"linePrefix")(i):a(i)}function a(i){return i===null||W(i)?t(i):r(i)}}const Wo={continuation:{tokenize:vm},exit:km,name:"blockQuote",tokenize:xm};function xm(e,t,r){const n=this;return a;function a(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"),i}return r(s)}function i(s){return Q(s)?(e.enter("blockQuotePrefixWhitespace"),e.consume(s),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(s))}}function vm(e,t,r){const n=this;return a;function a(s){return Q(s)?ee(e,i,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(s):i(s)}function i(s){return e.attempt(Wo,t,r)(s)}}function km(e){e.exit("blockQuote")}const Jo={name:"characterEscape",tokenize:Sm};function Sm(e,t,r){return n;function n(i){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(i),e.exit("escapeMarker"),a}function a(i){return um(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):r(i)}}const Ko={name:"characterReference",tokenize:_m};function _m(e,t,r){const n=this;let a=0,i,s;return o;function o(d){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(d),e.exit("characterReferenceMarker"),l}function l(d){return d===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(d),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),i=31,s=Ae,c(d))}function u(d){return d===88||d===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(d),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,s=lm,c):(e.enter("characterReferenceValue"),i=7,s=ya,c(d))}function c(d){if(d===59&&a){const f=e.exit("characterReferenceValue");return s===Ae&&!ga(n.sliceSerialize(f))?r(d):(e.enter("characterReferenceMarker"),e.consume(d),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return s(d)&&a++<i?(e.consume(d),c):r(d)}}const Yo={partial:!0,tokenize:Cm},Go={concrete:!0,name:"codeFenced",tokenize:Tm};function Tm(e,t,r){const n=this,a={partial:!0,tokenize:F};let i=0,s=0,o;return l;function l(_){return u(_)}function u(_){const $=n.events[n.events.length-1];return i=$&&$[1].type==="linePrefix"?$[2].sliceSerialize($[1],!0).length:0,o=_,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),c(_)}function c(_){return _===o?(s++,e.consume(_),c):s<3?r(_):(e.exit("codeFencedFenceSequence"),Q(_)?ee(e,d,"whitespace")(_):d(_))}function d(_){return _===null||W(_)?(e.exit("codeFencedFence"),n.interrupt?t(_):e.check(Yo,k,B)(_)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(_))}function f(_){return _===null||W(_)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),d(_)):Q(_)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),ee(e,h,"whitespace")(_)):_===96&&_===o?r(_):(e.consume(_),f)}function h(_){return _===null||W(_)?d(_):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(_))}function g(_){return _===null||W(_)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),d(_)):_===96&&_===o?r(_):(e.consume(_),g)}function k(_){return e.attempt(a,B,w)(_)}function w(_){return e.enter("lineEnding"),e.consume(_),e.exit("lineEnding"),b}function b(_){return i>0&&Q(_)?ee(e,I,"linePrefix",i+1)(_):I(_)}function I(_){return _===null||W(_)?e.check(Yo,k,B)(_):(e.enter("codeFlowValue"),T(_))}function T(_){return _===null||W(_)?(e.exit("codeFlowValue"),I(_)):(e.consume(_),T)}function B(_){return e.exit("codeFenced"),t(_)}function F(_,$,R){let j=0;return S;function S(D){return _.enter("lineEnding"),_.consume(D),_.exit("lineEnding"),N}function N(D){return _.enter("codeFencedFence"),Q(D)?ee(_,M,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(D):M(D)}function M(D){return D===o?(_.enter("codeFencedFenceSequence"),J(D)):R(D)}function J(D){return D===o?(j++,_.consume(D),J):j>=s?(_.exit("codeFencedFenceSequence"),Q(D)?ee(_,z,"whitespace")(D):z(D)):R(D)}function z(D){return D===null||W(D)?(_.exit("codeFencedFence"),$(D)):R(D)}}}function Cm(e,t,r){const n=this;return a;function a(s){return s===null?r(s):(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),i)}function i(s){return n.parser.lazy[n.now().line]?r(s):t(s)}}const wa={name:"codeIndented",tokenize:Em},Im={partial:!0,tokenize:Am};function Em(e,t,r){const n=this;return a;function a(u){return e.enter("codeIndented"),ee(e,i,"linePrefix",5)(u)}function i(u){const c=n.events[n.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?s(u):r(u)}function s(u){return u===null?l(u):W(u)?e.attempt(Im,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 Am(e,t,r){const n=this;return a;function a(s){return n.parser.lazy[n.now().line]?r(s):W(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),a):ee(e,i,"linePrefix",5)(s)}function i(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)?a(s):r(s)}}const Mm={name:"codeText",previous:Nm,resolve:Pm,tokenize:Lm};function Pm(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 Nm(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Lm(e,t,r){let n=0,a,i;return s;function s(d){return e.enter("codeText"),e.enter("codeTextSequence"),o(d)}function o(d){return d===96?(e.consume(d),n++,o):(e.exit("codeTextSequence"),l(d))}function l(d){return d===null?r(d):d===32?(e.enter("space"),e.consume(d),e.exit("space"),l):d===96?(i=e.enter("codeTextSequence"),a=0,c(d)):W(d)?(e.enter("lineEnding"),e.consume(d),e.exit("lineEnding"),l):(e.enter("codeTextData"),u(d))}function u(d){return d===null||d===32||d===96||W(d)?(e.exit("codeTextData"),l(d)):(e.consume(d),u)}function c(d){return d===96?(e.consume(d),a++,c):a===n?(e.exit("codeTextSequence"),e.exit("codeText"),t(d)):(i.type="codeTextData",u(d))}}class Dm{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 i=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return n&&br(this.left,n),i.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),br(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),br(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);br(this.right,r.reverse())}else{const r=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);br(this.left,r.reverse())}}}function br(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 Xo(e){const t={};let r=-1,n,a,i,s,o,l,u;const c=new Dm(e);for(;++r<c.length;){for(;r in t;)r=t[r];if(n=c.get(r),r&&n[1].type==="chunkFlow"&&c.get(r-1)[1].type==="listItemPrefix"&&(l=n[1]._tokenizer.events,i=0,i<l.length&&l[i][1].type==="lineEndingBlank"&&(i+=2),i<l.length&&l[i][1].type==="content"))for(;++i<l.length&&l[i][1].type!=="content";)l[i][1].type==="chunkText"&&(l[i][1]._isInFirstContentOfListItem=!0,i++);if(n[0]==="enter")n[1].contentType&&(Object.assign(t,Om(c,r)),r=t[r],u=!0);else if(n[1]._container){for(i=r,a=void 0;i--;)if(s=c.get(i),s[1].type==="lineEnding"||s[1].type==="lineEndingBlank")s[0]==="enter"&&(a&&(c.get(a)[1].type="lineEndingBlank"),s[1].type="lineEnding",a=i);else if(!(s[1].type==="linePrefix"||s[1].type==="listItemIndent"))break;a&&(n[1].end=m({},c.get(a)[1].start),o=c.slice(a,r),o.unshift(n),c.splice(a,r-a+1,o))}}return Ue(e,0,Number.POSITIVE_INFINITY,c.slice(0)),!u}function Om(e,t){const r=e.get(t)[1],n=e.get(t)[2];let a=t-1;const i=[];let s=r._tokenizer;s||(s=n.parser[r.contentType](r.start),r._contentTypeTextTrailing&&(s._contentTypeTextTrailing=!0));const o=s.events,l=[],u={};let c,d,f=-1,h=r,g=0,k=0;const w=[k];for(;h;){for(;e.get(++a)[1]!==h;);i.push(a),h._tokenizer||(c=n.sliceStream(h),h.next||c.push(null),d&&s.defineSkip(h.start),h._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=!0),s.write(c),h._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=void 0)),d=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&&(k=f+1,w.push(k),h._tokenizer=void 0,h.previous=void 0,h=h.next);for(s.events=[],h?(h._tokenizer=void 0,h.previous=void 0):w.pop(),f=w.length;f--;){const b=o.slice(w[f],w[f+1]),I=i.pop();l.push([I,I+b.length-1]),e.splice(I,2,b)}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 Fm={resolve:zm,tokenize:Rm},Bm={partial:!0,tokenize:jm};function zm(e){return Xo(e),e}function Rm(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?i(o):W(o)?e.check(Bm,s,i)(o):(e.consume(o),a)}function i(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,a}}function jm(e,t,r){const n=this;return a;function a(s){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),ee(e,i,"linePrefix")}function i(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 Qo(e,t,r,n,a,i,s,o,l){const u=l||Number.POSITIVE_INFINITY;let c=0;return d;function d(b){return b===60?(e.enter(n),e.enter(a),e.enter(i),e.consume(b),e.exit(i),f):b===null||b===32||b===41||tn(b)?r(b):(e.enter(n),e.enter(s),e.enter(o),e.enter("chunkString",{contentType:"string"}),k(b))}function f(b){return b===62?(e.enter(i),e.consume(b),e.exit(i),e.exit(a),e.exit(n),t):(e.enter(o),e.enter("chunkString",{contentType:"string"}),h(b))}function h(b){return b===62?(e.exit("chunkString"),e.exit(o),f(b)):b===null||b===60||W(b)?r(b):(e.consume(b),b===92?g:h)}function g(b){return b===60||b===62||b===92?(e.consume(b),h):h(b)}function k(b){return!c&&(b===null||b===41||ue(b))?(e.exit("chunkString"),e.exit(o),e.exit(s),e.exit(n),t(b)):c<u&&b===40?(e.consume(b),c++,k):b===41?(e.consume(b),c--,k):b===null||b===32||b===40||tn(b)?r(b):(e.consume(b),b===92?w:k)}function w(b){return b===40||b===41||b===92?(e.consume(b),k):k(b)}}function Zo(e,t,r,n,a,i){const s=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(i),c}function c(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(i),e.enter(a),e.consume(h),e.exit(a),e.exit(n),t):W(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),c):(e.enter("chunkString",{contentType:"string"}),d(h))}function d(h){return h===null||h===91||h===93||W(h)||o++>999?(e.exit("chunkString"),c(h)):(e.consume(h),l||(l=!Q(h)),h===92?f:d)}function f(h){return h===91||h===92||h===93?(e.consume(h),o++,d):d(h)}}function el(e,t,r,n,a,i){let s;return o;function o(f){return f===34||f===39||f===40?(e.enter(n),e.enter(a),e.consume(f),e.exit(a),s=f===40?41:f,l):r(f)}function l(f){return f===s?(e.enter(a),e.consume(f),e.exit(a),e.exit(n),t):(e.enter(i),u(f))}function u(f){return f===s?(e.exit(i),l(s)):f===null?r(f):W(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),ee(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),c(f))}function c(f){return f===s||f===null||W(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?d:c)}function d(f){return f===s||f===92?(e.consume(f),c):c(f)}}function wr(e,t){let r;return n;function n(a){return W(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),r=!0,n):Q(a)?ee(e,n,r?"linePrefix":"lineSuffix")(a):t(a)}}const $m={name:"definition",tokenize:Hm},Um={partial:!0,tokenize:qm};function Hm(e,t,r){const n=this;let a;return i;function i(h){return e.enter("definition"),s(h)}function s(h){return Zo.call(n,e,o,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(h)}function o(h){return a=tt(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 ue(h)?wr(e,u)(h):u(h)}function u(h){return Qo(e,c,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(h)}function c(h){return e.attempt(Um,d,d)(h)}function d(h){return Q(h)?ee(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 qm(e,t,r){return n;function n(o){return ue(o)?wr(e,a)(o):r(o)}function a(o){return el(e,i,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function i(o){return Q(o)?ee(e,s,"whitespace")(o):s(o)}function s(o){return o===null||W(o)?t(o):r(o)}}const Vm={name:"hardBreakEscape",tokenize:Wm};function Wm(e,t,r){return n;function n(i){return e.enter("hardBreakEscape"),e.consume(i),a}function a(i){return W(i)?(e.exit("hardBreakEscape"),t(i)):r(i)}}const Jm={name:"headingAtx",resolve:Km,tokenize:Ym};function Km(e,t){let r=e.length-2,n=3,a,i;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},i={type:"chunkText",start:e[n][1].start,end:e[r][1].end,contentType:"text"},Ue(e,n,r-n+1,[["enter",a,t],["enter",i,t],["exit",i,t],["exit",a,t]])),e}function Ym(e,t,r){let n=0;return a;function a(c){return e.enter("atxHeading"),i(c)}function i(c){return e.enter("atxHeadingSequence"),s(c)}function s(c){return c===35&&n++<6?(e.consume(c),s):c===null||ue(c)?(e.exit("atxHeadingSequence"),o(c)):r(c)}function o(c){return c===35?(e.enter("atxHeadingSequence"),l(c)):c===null||W(c)?(e.exit("atxHeading"),t(c)):Q(c)?ee(e,o,"whitespace")(c):(e.enter("atxHeadingText"),u(c))}function l(c){return c===35?(e.consume(c),l):(e.exit("atxHeadingSequence"),o(c))}function u(c){return c===null||c===35||ue(c)?(e.exit("atxHeadingText"),o(c)):(e.consume(c),u)}}const Gm=["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"],tl=["pre","script","style","textarea"],Xm={concrete:!0,name:"htmlFlow",resolveTo:eg,tokenize:tg},Qm={partial:!0,tokenize:ng},Zm={partial:!0,tokenize:rg};function eg(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 tg(e,t,r){const n=this;let a,i,s,o,l;return u;function u(v){return c(v)}function c(v){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(v),d}function d(v){return v===33?(e.consume(v),f):v===47?(e.consume(v),i=!0,k):v===63?(e.consume(v),a=3,n.interrupt?t:x):Le(v)?(e.consume(v),s=String.fromCharCode(v),w):r(v)}function f(v){return v===45?(e.consume(v),a=2,h):v===91?(e.consume(v),a=5,o=0,g):Le(v)?(e.consume(v),a=4,n.interrupt?t:x):r(v)}function h(v){return v===45?(e.consume(v),n.interrupt?t:x):r(v)}function g(v){const U="CDATA[";return v===U.charCodeAt(o++)?(e.consume(v),o===U.length?n.interrupt?t:M:g):r(v)}function k(v){return Le(v)?(e.consume(v),s=String.fromCharCode(v),w):r(v)}function w(v){if(v===null||v===47||v===62||ue(v)){const U=v===47,oe=s.toLowerCase();return!U&&!i&&tl.includes(oe)?(a=1,n.interrupt?t(v):M(v)):Gm.includes(s.toLowerCase())?(a=6,U?(e.consume(v),b):n.interrupt?t(v):M(v)):(a=7,n.interrupt&&!n.parser.lazy[n.now().line]?r(v):i?I(v):T(v))}return v===45||Ae(v)?(e.consume(v),s+=String.fromCharCode(v),w):r(v)}function b(v){return v===62?(e.consume(v),n.interrupt?t:M):r(v)}function I(v){return Q(v)?(e.consume(v),I):S(v)}function T(v){return v===47?(e.consume(v),S):v===58||v===95||Le(v)?(e.consume(v),B):Q(v)?(e.consume(v),T):S(v)}function B(v){return v===45||v===46||v===58||v===95||Ae(v)?(e.consume(v),B):F(v)}function F(v){return v===61?(e.consume(v),_):Q(v)?(e.consume(v),F):T(v)}function _(v){return v===null||v===60||v===61||v===62||v===96?r(v):v===34||v===39?(e.consume(v),l=v,$):Q(v)?(e.consume(v),_):R(v)}function $(v){return v===l?(e.consume(v),l=null,j):v===null||W(v)?r(v):(e.consume(v),$)}function R(v){return v===null||v===34||v===39||v===47||v===60||v===61||v===62||v===96||ue(v)?F(v):(e.consume(v),R)}function j(v){return v===47||v===62||Q(v)?T(v):r(v)}function S(v){return v===62?(e.consume(v),N):r(v)}function N(v){return v===null||W(v)?M(v):Q(v)?(e.consume(v),N):r(v)}function M(v){return v===45&&a===2?(e.consume(v),Y):v===60&&a===1?(e.consume(v),ce):v===62&&a===4?(e.consume(v),Se):v===63&&a===3?(e.consume(v),x):v===93&&a===5?(e.consume(v),me):W(v)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(Qm,ve,J)(v)):v===null||W(v)?(e.exit("htmlFlowData"),J(v)):(e.consume(v),M)}function J(v){return e.check(Zm,z,ve)(v)}function z(v){return e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),D}function D(v){return v===null||W(v)?J(v):(e.enter("htmlFlowData"),M(v))}function Y(v){return v===45?(e.consume(v),x):M(v)}function ce(v){return v===47?(e.consume(v),s="",se):M(v)}function se(v){if(v===62){const U=s.toLowerCase();return tl.includes(U)?(e.consume(v),Se):M(v)}return Le(v)&&s.length<8?(e.consume(v),s+=String.fromCharCode(v),se):M(v)}function me(v){return v===93?(e.consume(v),x):M(v)}function x(v){return v===62?(e.consume(v),Se):v===45&&a===2?(e.consume(v),x):M(v)}function Se(v){return v===null||W(v)?(e.exit("htmlFlowData"),ve(v)):(e.consume(v),Se)}function ve(v){return e.exit("htmlFlow"),t(v)}}function rg(e,t,r){const n=this;return a;function a(s){return W(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),i):r(s)}function i(s){return n.parser.lazy[n.now().line]?r(s):t(s)}}function ng(e,t,r){return n;function n(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(yr,t,r)}}const ag={name:"htmlText",tokenize:ig};function ig(e,t,r){const n=this;let a,i,s;return o;function o(x){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(x),l}function l(x){return x===33?(e.consume(x),u):x===47?(e.consume(x),F):x===63?(e.consume(x),T):Le(x)?(e.consume(x),R):r(x)}function u(x){return x===45?(e.consume(x),c):x===91?(e.consume(x),i=0,g):Le(x)?(e.consume(x),I):r(x)}function c(x){return x===45?(e.consume(x),h):r(x)}function d(x){return x===null?r(x):x===45?(e.consume(x),f):W(x)?(s=d,ce(x)):(e.consume(x),d)}function f(x){return x===45?(e.consume(x),h):d(x)}function h(x){return x===62?Y(x):x===45?f(x):d(x)}function g(x){const Se="CDATA[";return x===Se.charCodeAt(i++)?(e.consume(x),i===Se.length?k:g):r(x)}function k(x){return x===null?r(x):x===93?(e.consume(x),w):W(x)?(s=k,ce(x)):(e.consume(x),k)}function w(x){return x===93?(e.consume(x),b):k(x)}function b(x){return x===62?Y(x):x===93?(e.consume(x),b):k(x)}function I(x){return x===null||x===62?Y(x):W(x)?(s=I,ce(x)):(e.consume(x),I)}function T(x){return x===null?r(x):x===63?(e.consume(x),B):W(x)?(s=T,ce(x)):(e.consume(x),T)}function B(x){return x===62?Y(x):T(x)}function F(x){return Le(x)?(e.consume(x),_):r(x)}function _(x){return x===45||Ae(x)?(e.consume(x),_):$(x)}function $(x){return W(x)?(s=$,ce(x)):Q(x)?(e.consume(x),$):Y(x)}function R(x){return x===45||Ae(x)?(e.consume(x),R):x===47||x===62||ue(x)?j(x):r(x)}function j(x){return x===47?(e.consume(x),Y):x===58||x===95||Le(x)?(e.consume(x),S):W(x)?(s=j,ce(x)):Q(x)?(e.consume(x),j):Y(x)}function S(x){return x===45||x===46||x===58||x===95||Ae(x)?(e.consume(x),S):N(x)}function N(x){return x===61?(e.consume(x),M):W(x)?(s=N,ce(x)):Q(x)?(e.consume(x),N):j(x)}function M(x){return x===null||x===60||x===61||x===62||x===96?r(x):x===34||x===39?(e.consume(x),a=x,J):W(x)?(s=M,ce(x)):Q(x)?(e.consume(x),M):(e.consume(x),z)}function J(x){return x===a?(e.consume(x),a=void 0,D):x===null?r(x):W(x)?(s=J,ce(x)):(e.consume(x),J)}function z(x){return x===null||x===34||x===39||x===60||x===61||x===96?r(x):x===47||x===62||ue(x)?j(x):(e.consume(x),z)}function D(x){return x===47||x===62||ue(x)?j(x):r(x)}function Y(x){return x===62?(e.consume(x),e.exit("htmlTextData"),e.exit("htmlText"),t):r(x)}function ce(x){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),se}function se(x){return Q(x)?ee(e,me,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(x):me(x)}function me(x){return e.enter("htmlTextData"),s(x)}}const xa={name:"labelEnd",resolveAll:ug,resolveTo:cg,tokenize:dg},sg={tokenize:hg},og={tokenize:fg},lg={tokenize:pg};function ug(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&&Ue(e,0,e.length,r),e}function cg(e,t){let r=e.length,n=0,a,i,s,o;for(;r--;)if(a=e[r][1],i){if(a.type==="link"||a.type==="labelLink"&&a._inactive)break;e[r][0]==="enter"&&a.type==="labelLink"&&(a._inactive=!0)}else if(s){if(e[r][0]==="enter"&&(a.type==="labelImage"||a.type==="labelLink")&&!a._balanced&&(i=r,a.type!=="labelLink")){n=2;break}}else a.type==="labelEnd"&&(s=r);const l={type:e[i][1].type==="labelLink"?"link":"image",start:m({},e[i][1].start),end:m({},e[e.length-1][1].end)},u={type:"label",start:m({},e[i][1].start),end:m({},e[s][1].end)},c={type:"labelText",start:m({},e[i+n+2][1].end),end:m({},e[s-2][1].start)};return o=[["enter",l,t],["enter",u,t]],o=We(o,e.slice(i+1,i+n+3)),o=We(o,[["enter",c,t]]),o=We(o,nn(t.parser.constructs.insideSpan.null,e.slice(i+n+4,s-3),t)),o=We(o,[["exit",c,t],e[s-2],e[s-1],["exit",u,t]]),o=We(o,e.slice(s+1)),o=We(o,[["exit",l,t]]),Ue(e,i,e.length,o),e}function dg(e,t,r){const n=this;let a=n.events.length,i,s;for(;a--;)if((n.events[a][1].type==="labelImage"||n.events[a][1].type==="labelLink")&&!n.events[a][1]._balanced){i=n.events[a][1];break}return o;function o(f){return i?i._inactive?d(f):(s=n.parser.defined.includes(tt(n.sliceSerialize({start:i.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(sg,c,s?c:d)(f):f===91?e.attempt(og,c,s?u:d)(f):s?c(f):d(f)}function u(f){return e.attempt(lg,c,d)(f)}function c(f){return t(f)}function d(f){return i._balanced=!0,r(f)}}function hg(e,t,r){return n;function n(d){return e.enter("resource"),e.enter("resourceMarker"),e.consume(d),e.exit("resourceMarker"),a}function a(d){return ue(d)?wr(e,i)(d):i(d)}function i(d){return d===41?c(d):Qo(e,s,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(d)}function s(d){return ue(d)?wr(e,l)(d):c(d)}function o(d){return r(d)}function l(d){return d===34||d===39||d===40?el(e,u,r,"resourceTitle","resourceTitleMarker","resourceTitleString")(d):c(d)}function u(d){return ue(d)?wr(e,c)(d):c(d)}function c(d){return d===41?(e.enter("resourceMarker"),e.consume(d),e.exit("resourceMarker"),e.exit("resource"),t):r(d)}}function fg(e,t,r){const n=this;return a;function a(o){return Zo.call(n,e,i,s,"reference","referenceMarker","referenceString")(o)}function i(o){return n.parser.defined.includes(tt(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)))?t(o):r(o)}function s(o){return r(o)}}function pg(e,t,r){return n;function n(i){return e.enter("reference"),e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),a}function a(i){return i===93?(e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),e.exit("reference"),t):r(i)}}const mg={name:"labelStartImage",resolveAll:xa.resolveAll,tokenize:gg};function gg(e,t,r){const n=this;return a;function a(o){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(o),e.exit("labelImageMarker"),i}function i(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 yg={name:"labelStartLink",resolveAll:xa.resolveAll,tokenize:bg};function bg(e,t,r){const n=this;return a;function a(s){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(s),e.exit("labelMarker"),e.exit("labelLink"),i}function i(s){return s===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(s):t(s)}}const va={name:"lineEnding",tokenize:wg};function wg(e,t){return r;function r(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),ee(e,t,"linePrefix")}}const an={name:"thematicBreak",tokenize:xg};function xg(e,t,r){let n=0,a;return i;function i(u){return e.enter("thematicBreak"),s(u)}function s(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"),Q(u)?ee(e,o,"whitespace")(u):o(u))}}const ze={continuation:{tokenize:_g},exit:Cg,name:"list",tokenize:Sg},vg={partial:!0,tokenize:Ig},kg={partial:!0,tokenize:Tg};function Sg(e,t,r){const n=this,a=n.events[n.events.length-1];let i=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[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:ya(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(an,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 ya(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(yr,n.interrupt?r:c,e.attempt(vg,f,d))}function c(h){return n.containerState.initialBlankLine=!0,i++,f(h)}function d(h){return Q(h)?(e.enter("listItemPrefixWhitespace"),e.consume(h),e.exit("listItemPrefixWhitespace"),f):r(h)}function f(h){return n.containerState.size=i+n.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(h)}}function _g(e,t,r){const n=this;return n.containerState._closeFlow=void 0,e.check(yr,a,i);function a(o){return n.containerState.furtherBlankLines=n.containerState.furtherBlankLines||n.containerState.initialBlankLine,ee(e,t,"listItemIndent",n.containerState.size+1)(o)}function i(o){return n.containerState.furtherBlankLines||!Q(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(kg,t,s)(o))}function s(o){return n.containerState._closeFlow=!0,n.interrupt=void 0,ee(e,e.attempt(ze,t,r),"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function Tg(e,t,r){const n=this;return ee(e,a,"listItemIndent",n.containerState.size+1);function a(i){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(i):r(i)}}function Cg(e){e.exit(this.containerState.type)}function Ig(e,t,r){const n=this;return ee(e,a,"listItemPrefixWhitespace",n.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(i){const s=n.events[n.events.length-1];return!Q(i)&&s&&s[1].type==="listItemPrefixWhitespace"?t(i):r(i)}}const rl={name:"setextUnderline",resolveTo:Eg,tokenize:Ag};function Eg(e,t){let r=e.length,n,a,i;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),!i&&e[r][1].type==="definition"&&(i=r);const s={type:"setextHeading",start:m({},e[n][1].start),end:m({},e[e.length-1][1].end)};return e[a][1].type="setextHeadingText",i?(e.splice(a,0,["enter",s,t]),e.splice(i+1,0,["exit",e[n][1],t]),e[n][1].end=m({},e[i][1].end)):e[n][1]=s,e.push(["exit",s,t]),e}function Ag(e,t,r){const n=this;let a;return i;function i(u){let c=n.events.length,d;for(;c--;)if(n.events[c][1].type!=="lineEnding"&&n.events[c][1].type!=="linePrefix"&&n.events[c][1].type!=="content"){d=n.events[c][1].type==="paragraph";break}return!n.parser.lazy[n.now().line]&&(n.interrupt||d)?(e.enter("setextHeadingLine"),a=u,s(u)):r(u)}function s(u){return e.enter("setextHeadingLineSequence"),o(u)}function o(u){return u===a?(e.consume(u),o):(e.exit("setextHeadingLineSequence"),Q(u)?ee(e,l,"lineSuffix")(u):l(u))}function l(u){return u===null||W(u)?(e.exit("setextHeadingLine"),t(u)):r(u)}}const Mg={tokenize:Pg};function Pg(e){const t=this,r=e.attempt(yr,n,e.attempt(this.parser.constructs.flowInitial,a,ee(e,e.attempt(this.parser.constructs.flow,a,e.attempt(Fm,a)),"linePrefix")));return r;function n(i){if(i===null){e.consume(i);return}return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,r}function a(i){if(i===null){e.consume(i);return}return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,r}}const Ng={resolveAll:al()},Lg=nl("string"),Dg=nl("text");function nl(e){return{resolveAll:al(e==="text"?Og:void 0),tokenize:t};function t(r){const n=this,a=this.parser.constructs[e],i=r.attempt(a,s,o);return s;function s(c){return u(c)?i(c):o(c)}function o(c){if(c===null){r.consume(c);return}return r.enter("data"),r.consume(c),l}function l(c){return u(c)?(r.exit("data"),i(c)):(r.consume(c),l)}function u(c){if(c===null)return!0;const d=a[c];let f=-1;if(d)for(;++f<d.length;){const h=d[f];if(!h.previous||h.previous.call(n,n.previous))return!0}return!1}}}function al(e){return t;function t(r,n){let a=-1,i;for(;++a<=r.length;)i===void 0?r[a]&&r[a][1].type==="data"&&(i=a,a++):(!r[a]||r[a][1].type!=="data")&&(a!==i+2&&(r[i][1].end=r[a-1][1].end,r.splice(i+2,a-i-2),a=i+2),i=void 0);return e?e(r,n):r}}function Og(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 i=a.length,s=-1,o=0,l;for(;i--;){const u=a[i];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){i++;break}}if(t._contentTypeTextTrailing&&r===e.length&&(o=0),o){const u={type:r===e.length||l||o<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?s:n.start._bufferIndex+s,_index:n.start._index+i,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 Fg=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:{null:[42,95]},contentInitial:{91:$m},disable:{null:[]},document:{42:ze,43:ze,45:ze,48:ze,49:ze,50:ze,51:ze,52:ze,53:ze,54:ze,55:ze,56:ze,57:ze,62:Wo},flow:{35:Jm,42:an,45:[rl,an],60:Xm,61:rl,95:an,96:Go,126:Go},flowInitial:{[-2]:wa,[-1]:wa,32:wa},insideSpan:{null:[ba,Ng]},string:{38:Ko,92:Jo},text:{[-5]:va,[-4]:va,[-3]:va,33:mg,38:Ko,42:ba,60:[ym,ag],91:yg,92:[Vm,Jo],93:xa,95:ba,96:Mm}},Symbol.toStringTag,{value:"Module"}));function Bg(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={},i=[];let s=[],o=[];const l={attempt:$(F),check:$(_),consume:I,enter:T,exit:B,interrupt:$(_,{interrupt:!0})},u={code:null,containerState:{},defineSkip:k,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:h,write:d};let c=t.tokenize.call(u,l);return t.resolveAll&&i.push(t),u;function d(N){return s=We(s,N),w(),s[s.length-1]!==null?[]:(R(t,0),u.events=nn(i,u.events,u),u.events)}function f(N,M){return Rg(h(N),M)}function h(N){return zg(s,N)}function g(){const{_bufferIndex:N,_index:M,line:J,column:z,offset:D}=n;return{_bufferIndex:N,_index:M,line:J,column:z,offset:D}}function k(N){a[N.line]=N.column,S()}function w(){let N;for(;n._index<s.length;){const M=s[n._index];if(typeof M=="string")for(N=n._index,n._bufferIndex<0&&(n._bufferIndex=0);n._index===N&&n._bufferIndex<M.length;)b(M.charCodeAt(n._bufferIndex));else b(M)}}function b(N){c=c(N)}function I(N){W(N)?(n.line++,n.column=1,n.offset+=N===-3?2:1,S()):N!==-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=N}function T(N,M){const J=M||{};return J.type=N,J.start=g(),u.events.push(["enter",J,u]),o.push(J),J}function B(N){const M=o.pop();return M.end=g(),u.events.push(["exit",M,u]),M}function F(N,M){R(N,M.from)}function _(N,M){M.restore()}function $(N,M){return J;function J(z,D,Y){let ce,se,me,x;return Array.isArray(z)?ve(z):"tokenize"in z?ve([z]):Se(z);function Se(ne){return _e;function _e(Te){const ge=Te!==null&&ne[Te],He=Te!==null&&ne.null,Kt=[...Array.isArray(ge)?ge:ge?[ge]:[],...Array.isArray(He)?He:He?[He]:[]];return ve(Kt)(Te)}}function ve(ne){return ce=ne,se=0,ne.length===0?Y:v(ne[se])}function v(ne){return _e;function _e(Te){return x=j(),me=ne,ne.partial||(u.currentConstruct=ne),ne.name&&u.parser.constructs.disable.null.includes(ne.name)?oe():ne.tokenize.call(M?Object.assign(Object.create(u),M):u,l,U,oe)(Te)}}function U(ne){return N(me,x),D}function oe(ne){return x.restore(),++se<ce.length?v(ce[se]):Y}}}function R(N,M){N.resolveAll&&!i.includes(N)&&i.push(N),N.resolve&&Ue(u.events,M,u.events.length-M,N.resolve(u.events.slice(M),u)),N.resolveTo&&(u.events=N.resolveTo(u.events,u))}function j(){const N=g(),M=u.previous,J=u.currentConstruct,z=u.events.length,D=Array.from(o);return{from:z,restore:Y};function Y(){n=N,u.previous=M,u.currentConstruct=J,u.events.length=z,o=D,S()}}function S(){n.line in a&&n.column<2&&(n.column=a[n.line],n.offset+=a[n.line]-1)}}function zg(e,t){const r=t.start._index,n=t.start._bufferIndex,a=t.end._index,i=t.end._bufferIndex;let s;if(r===a)s=[e[r].slice(n,i)];else{if(s=e.slice(r,a),n>-1){const o=s[0];typeof o=="string"?s[0]=o.slice(n):s.shift()}i>0&&s.push(e[a].slice(0,i))}return s}function Rg(e,t){let r=-1;const n=[];let a;for(;++r<e.length;){const i=e[r];let s;if(typeof i=="string")s=i;else switch(i){case-5:{s="\r";break}case-4:{s=`
9
9
  `;break}case-3:{s=`\r
10
- `;break}case-2:{s=t?" ":" ";break}case-1:{if(!t&&a)continue;s=" ";break}default:s=String.fromCharCode(i)}a=i===-2,n.push(s)}return n.join("")}function Fg(e){const n={constructs:jo([Ng,...(e||{}).extensions||[]]),content:a(sm),defined:[],document:a(lm),flow:a(Cg),lazy:{},string:a(Ag),text:a(Pg)};return n;function a(i){return s;function s(o){return Lg(n,i,o)}}}function Bg(e){for(;!Go(e););return e}const nl=/[\0\t\n\r]/g;function zg(){let e=1,t="",r=!0,n;return a;function a(i,s,o){const l=[];let u,d,c,f,h;for(i=t+(typeof i=="string"?i.toString():new TextDecoder(s||void 0).decode(i)),c=0,t="",r&&(i.charCodeAt(0)===65279&&c++,r=void 0);c<i.length;){if(nl.lastIndex=c,u=nl.exec(i),f=u&&u.index!==void 0?u.index:i.length,h=i.charCodeAt(f),!u){t=i.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(i.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 Rg=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function jg(e){return e.replace(Rg,$g)}function $g(e,t,r){if(t)return t;if(r.charCodeAt(0)===35){const a=r.charCodeAt(1),i=a===120||a===88;return $o(r.slice(i?2:1),i?16:10)}return ma(r)||e}const al={}.hasOwnProperty;function Ug(e,t,r){return typeof t!="string"&&(r=t,t=void 0),Hg(r)(Bg(Fg(r).document().write(zg()(e,t,!0))))}function Hg(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(wt),autolinkProtocol:U,autolinkEmail:U,atxHeading:i(Pe),blockQuote:i(yt),characterEscape:U,characterReference:U,codeFenced:i(Jt),codeFencedFenceInfo:s,codeFencedFenceMeta:s,codeIndented:i(Jt,s),codeText:i(Kt,s),codeTextData:U,data:U,codeFlowValue:U,definition:i(Gt),definitionDestinationString:s,definitionLabelString:s,definitionTitleString:s,emphasis:i(mn),hardBreakEscape:i(gn),hardBreakTrailing:i(gn),htmlFlow:i(bt,s),htmlFlowData:U,htmlText:i(bt,s),htmlTextData:U,image:i(yn),label:s,link:i(wt),listItem:i(Za),listItemValue:f,listOrdered:i(Ir,c),listUnordered:i(Ir),paragraph:i(bn),reference:v,referenceString:s,resourceDestinationString:s,resourceTitleString:s,setextHeading:i(Pe),strong:i(xt),thematicBreak:i(wn)},exit:{atxHeading:l(),atxHeadingSequence:z,autolink:l(),autolinkEmail:ot,autolinkProtocol:Qe,blockQuote:l(),characterEscapeValue:k,characterReferenceMarkerHexadecimal:Xe,characterReferenceMarkerNumeric:Xe,characterReferenceValue:pe,characterReference:gt,codeFenced:l(x),codeFencedFence:S,codeFencedFenceInfo:h,codeFencedFenceMeta:y,codeFlowValue:k,codeIndented:l(b),codeText:l(F),codeTextData:k,data:k,definition:l(),definitionDestinationString:L,definitionLabelString:_,definitionTitleString:T,emphasis:l(),hardBreakEscape:l(M),hardBreakTrailing:l(M),htmlFlow:l(H),htmlFlowData:k,htmlText:l(R),htmlTextData:k,image:l(J),label:Z,labelText:re,lineEnding:D,link:l(j),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:ve,resourceDestinationString:w,resourceTitleString:ae,resource:xe,setextHeading:l(B),setextHeadingLineSequence:q,setextHeadingText:I,strong:l(),thematicBreak:l()}};il(t,(e||{}).mdastExtensions||[]);const r={};return n;function n(A){let O={type:"root",children:[]};const G={stack:[O],tokenStack:[],config:t,enter:o,exit:u,buffer:s,resume:d,data:r},Q=[];let oe=-1;for(;++oe<A.length;)if(A[oe][1].type==="listOrdered"||A[oe][1].type==="listUnordered")if(A[oe][0]==="enter")Q.push(oe);else{const Ue=Q.pop();oe=a(A,Ue,oe)}for(oe=-1;++oe<A.length;){const Ue=t[A[oe][0]];al.call(Ue,A[oe][1].type)&&Ue[A[oe][1].type].call(Object.assign({sliceSerialize:A[oe][2].sliceSerialize},G),A[oe][1])}if(G.tokenStack.length>0){const Ue=G.tokenStack[G.tokenStack.length-1];(Ue[1]||sl).call(G,void 0,Ue[0])}for(O.position={start:mt(A.length>0?A[0][1].start:{line:1,column:1,offset:0}),end:mt(A.length>0?A[A.length-2][1].end:{line:1,column:1,offset:0})},oe=-1;++oe<t.transforms.length;)O=t.transforms[oe](O)||O;return O}function a(A,O,G){let Q=O-1,oe=-1,Ue=!1,V,te,ie,He;for(;++Q<=G;){const be=A[Q];switch(be[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{be[0]==="enter"?oe++:oe--,He=void 0;break}case"lineEndingBlank":{be[0]==="enter"&&(V&&!He&&!oe&&!ie&&(ie=Q),He=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:He=void 0}if(!oe&&be[0]==="enter"&&be[1].type==="listItemPrefix"||oe===-1&&be[0]==="exit"&&(be[1].type==="listUnordered"||be[1].type==="listOrdered")){if(V){let lt=Q;for(te=void 0;lt--;){const ut=A[lt];if(ut[1].type==="lineEnding"||ut[1].type==="lineEndingBlank"){if(ut[0]==="exit")continue;te&&(A[te][1].type="lineEndingBlank",Ue=!0),ut[1].type="lineEnding",te=lt}else if(!(ut[1].type==="linePrefix"||ut[1].type==="blockQuotePrefix"||ut[1].type==="blockQuotePrefixWhitespace"||ut[1].type==="blockQuoteMarker"||ut[1].type==="listItemIndent"))break}ie&&(!te||ie<te)&&(V._spread=!0),V.end=Object.assign({},te?A[te][1].start:be[1].end),A.splice(te||Q,0,["exit",V,be[2]]),Q++,G++}if(be[1].type==="listItemPrefix"){const lt={type:"listItem",_spread:!1,start:Object.assign({},be[1].start),end:void 0};V=lt,A.splice(Q,0,["enter",lt,be[2]]),Q++,G++,ie=void 0,He=!0}}}return A[O][1]._spread=Ue,G}function i(A,O){return G;function G(Q){o.call(this,A(Q),Q),O&&O.call(this,Q)}}function s(){this.stack.push({type:"fragment",children:[]})}function o(A,O,G){this.stack[this.stack.length-1].children.push(A),this.stack.push(A),this.tokenStack.push([O,G||void 0]),A.position={start:mt(O.start),end:void 0}}function l(A){return O;function O(G){A&&A.call(this,G),u.call(this,G)}}function u(A,O){const G=this.stack.pop(),Q=this.tokenStack.pop();if(Q)Q[0].type!==A.type&&(O?O.call(this,A,Q[0]):(Q[1]||sl).call(this,A,Q[0]));else throw new Error("Cannot close `"+A.type+"` ("+pr({start:A.start,end:A.end})+"): it’s not open");G.position.end=mt(A.end)}function d(){return pa(this.stack.pop())}function c(){this.data.expectingFirstListItemValue=!0}function f(A){if(this.data.expectingFirstListItemValue){const O=this.stack[this.stack.length-2];O.start=Number.parseInt(this.sliceSerialize(A),10),this.data.expectingFirstListItemValue=void 0}}function h(){const A=this.resume(),O=this.stack[this.stack.length-1];O.lang=A}function y(){const A=this.resume(),O=this.stack[this.stack.length-1];O.meta=A}function S(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function x(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A.replace(/(\r?\n|\r)$/g,"")}function _(A){const O=this.resume(),G=this.stack[this.stack.length-1];G.label=O,G.identifier=Ge(this.sliceSerialize(A)).toLowerCase()}function T(){const A=this.resume(),O=this.stack[this.stack.length-1];O.title=A}function L(){const A=this.resume(),O=this.stack[this.stack.length-1];O.url=A}function z(A){const O=this.stack[this.stack.length-1];if(!O.depth){const G=this.sliceSerialize(A).length;O.depth=G}}function I(){this.data.setextHeadingSlurpLineEnding=!0}function q(A){const O=this.stack[this.stack.length-1];O.depth=this.sliceSerialize(A).codePointAt(0)===61?1:2}function B(){this.data.setextHeadingSlurpLineEnding=void 0}function U(A){const G=this.stack[this.stack.length-1].children;let Q=G[G.length-1];(!Q||Q.type!=="text")&&(Q=Ze(),Q.position={start:mt(A.start),end:void 0},G.push(Q)),this.stack.push(Q)}function k(A){const O=this.stack.pop();O.value+=this.sliceSerialize(A),O.position.end=mt(A.end)}function D(A){const O=this.stack[this.stack.length-1];if(this.data.atHardBreak){const G=O.children[O.children.length-1];G.position.end=mt(A.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(O.type)&&(U.call(this,A),k.call(this,A))}function M(){this.data.atHardBreak=!0}function H(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A}function R(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A}function F(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A}function j(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const O=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=O,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 O=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=O,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function re(A){const O=this.sliceSerialize(A),G=this.stack[this.stack.length-2];G.label=jg(O),G.identifier=Ge(O).toLowerCase()}function Z(){const A=this.stack[this.stack.length-1],O=this.resume(),G=this.stack[this.stack.length-1];if(this.data.inReference=!0,G.type==="link"){const Q=A.children;G.children=Q}else G.alt=O}function w(){const A=this.resume(),O=this.stack[this.stack.length-1];O.url=A}function ae(){const A=this.resume(),O=this.stack[this.stack.length-1];O.title=A}function xe(){this.data.inReference=void 0}function v(){this.data.referenceType="collapsed"}function ve(A){const O=this.resume(),G=this.stack[this.stack.length-1];G.label=O,G.identifier=Ge(this.sliceSerialize(A)).toLowerCase(),this.data.referenceType="full"}function Xe(A){this.data.characterReferenceType=A.type}function pe(A){const O=this.sliceSerialize(A),G=this.data.characterReferenceType;let Q;G?(Q=$o(O,G==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Q=ma(O);const oe=this.stack[this.stack.length-1];oe.value+=Q}function gt(A){const O=this.stack.pop();O.position.end=mt(A.end)}function Qe(A){k.call(this,A);const O=this.stack[this.stack.length-1];O.url=this.sliceSerialize(A)}function ot(A){k.call(this,A);const O=this.stack[this.stack.length-1];O.url="mailto:"+this.sliceSerialize(A)}function yt(){return{type:"blockquote",children:[]}}function Jt(){return{type:"code",lang:null,meta:null,value:""}}function Kt(){return{type:"inlineCode",value:""}}function Gt(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function mn(){return{type:"emphasis",children:[]}}function Pe(){return{type:"heading",depth:0,children:[]}}function gn(){return{type:"break"}}function bt(){return{type:"html",value:""}}function yn(){return{type:"image",title:null,url:"",alt:null}}function wt(){return{type:"link",title:null,url:"",children:[]}}function Ir(A){return{type:"list",ordered:A.type==="listOrdered",start:null,spread:A._spread,children:[]}}function Za(A){return{type:"listItem",spread:A._spread,checked:null,children:[]}}function bn(){return{type:"paragraph",children:[]}}function xt(){return{type:"strong",children:[]}}function Ze(){return{type:"text",value:""}}function wn(){return{type:"thematicBreak"}}}function mt(e){return{line:e.line,column:e.column,offset:e.offset}}function il(e,t){let r=-1;for(;++r<t.length;){const n=t[r];Array.isArray(n)?il(e,n):qg(e,n)}}function qg(e,t){let r;for(r in t)if(al.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+"` ("+pr({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+pr({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+pr({start:t.start,end:t.end})+") is still open")}function Vg(e){const t=this;t.parser=r;function r(n){return Ug(n,E(m(m({},t.data("settings")),e),{extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]}))}}function Wg(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 Jg(e,t){const r={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,r),[e.applyData(t,r),{type:"text",value:`
11
- `}]}function Kg(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 i={type:"element",tagName:"code",properties:n,children:[{type:"text",value:r}]};return t.meta&&(i.data={meta:t.meta}),e.patch(t,i),i=e.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},e.patch(t,i),i}function Gg(e,t){const r={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Yg(e,t){const r={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Xg(e,t){const r=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=String(t.identifier).toUpperCase(),a=Ht(n.toLowerCase()),i=e.footnoteOrder.indexOf(n);let s,o=e.footnoteCounts.get(n);o===void 0?(o=0,e.footnoteOrder.push(n),s=e.footnoteOrder.length):s=i+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(s)}]};e.patch(t,l);const u={type:"element",tagName:"sup",properties:{},children:[l]};return e.patch(t,u),e.applyData(t,u)}function Qg(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 Zg(e,t){if(e.options.allowDangerousHtml){const r={type:"raw",value:t.value};return e.patch(t,r),e.applyData(t,r)}}function ol(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),i=a[0];i&&i.type==="text"?i.value="["+i.value:a.unshift({type:"text",value:"["});const s=a[a.length-1];return s&&s.type==="text"?s.value+=n:a.push({type:"text",value:n}),a}function ey(e,t){const r=String(t.identifier).toUpperCase(),n=e.definitionById.get(r);if(!n)return ol(e,t);const a={src:Ht(n.url||""),alt:t.alt};n.title!==null&&n.title!==void 0&&(a.title=n.title);const i={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,i),e.applyData(t,i)}function ty(e,t){const r={src:Ht(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 ry(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 ny(e,t){const r=String(t.identifier).toUpperCase(),n=e.definitionById.get(r);if(!n)return ol(e,t);const a={href:Ht(n.url||"")};n.title!==null&&n.title!==void 0&&(a.title=n.title);const i={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function ay(e,t){const r={href:Ht(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 iy(e,t,r){const n=e.all(t),a=r?sy(r):ll(t),i={},s=[];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:[]}),i.className=["task-list-item"]}let o=-1;for(;++o<n.length;){const d=n[o];(a||o!==0||d.type!=="element"||d.tagName!=="p")&&s.push({type:"text",value:`
13
- `}),d.type==="element"&&d.tagName==="p"&&!a?s.push(...d.children):s.push(d)}const l=n[n.length-1];l&&(a||l.type!=="element"||l.tagName!=="p")&&s.push({type:"text",value:`
14
- `});const u={type:"element",tagName:"li",properties:i,children:s};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=ll(r[n])}return t}function ll(e){const t=e.spread;return t==null?e.children.length>1:t}function oy(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 s=n[a];if(s.type==="element"&&s.tagName==="li"&&s.properties&&Array.isArray(s.properties.className)&&s.properties.className.includes("task-list-item")){r.className=["contains-task-list"];break}}const i={type:"element",tagName:t.ordered?"ol":"ul",properties:r,children:e.wrap(n,!0)};return e.patch(t,i),e.applyData(t,i)}function ly(e,t){const r={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function uy(e,t){const r={type:"root",children:e.wrap(e.all(t))};return e.patch(t,r),e.applyData(t,r)}function cy(e,t){const r={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function dy(e,t){const r=e.all(t),n=r.shift(),a=[];if(n){const s={type:"element",tagName:"thead",properties:{},children:e.wrap([n],!0)};e.patch(t.children[0],s),a.push(s)}if(r.length>0){const s={type:"element",tagName:"tbody",properties:{},children:e.wrap(r,!0)},o=la(t.children[1]),l=Eo(t.children[t.children.length-1]);o&&l&&(s.position={start:o,end:l}),a.push(s)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(a,!0)};return e.patch(t,i),e.applyData(t,i)}function hy(e,t,r){const n=r?r.children:void 0,i=(n?n.indexOf(t):1)===0?"th":"td",s=r&&r.type==="table"?r.align:void 0,o=s?s.length:t.children.length;let l=-1;const u=[];for(;++l<o;){const c=t.children[l],f={},h=s?s[l]:void 0;h&&(f.align=h);let y={type:"element",tagName:i,properties:f,children:[]};c&&(y.children=e.all(c),e.patch(c,y),y=e.applyData(c,y)),u.push(y)}const d={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(t,d),e.applyData(t,d)}function fy(e,t){const r={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}const ul=9,cl=32;function py(e){const t=String(e),r=/\r?\n|\r/g;let n=r.exec(t),a=0;const i=[];for(;n;)i.push(dl(t.slice(a,n.index),a>0,!0),n[0]),a=n.index+n[0].length,n=r.exec(t);return i.push(dl(t.slice(a),a>0,!1)),i.join("")}function dl(e,t,r){let n=0,a=e.length;if(t){let i=e.codePointAt(n);for(;i===ul||i===cl;)n++,i=e.codePointAt(n)}if(r){let i=e.codePointAt(a-1);for(;i===ul||i===cl;)a--,i=e.codePointAt(a-1)}return a>n?e.slice(n,a):""}function my(e,t){const r={type:"text",value:py(String(t.value))};return e.patch(t,r),e.applyData(t,r)}function gy(e,t){const r={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,r),e.applyData(t,r)}const yy={blockquote:Wg,break:Jg,code:Kg,delete:Gg,emphasis:Yg,footnoteReference:Xg,heading:Qg,html:Zg,imageReference:ey,image:ty,inlineCode:ry,linkReference:ny,link:ay,listItem:iy,list:oy,paragraph:ly,root:uy,strong:cy,table:dy,tableCell:fy,tableRow:hy,text:my,thematicBreak:gy,toml:nn,yaml:nn,definition:nn,footnoteDefinition:nn};function nn(){}const hl=-1,an=0,wr=1,sn=2,va=3,Sa=4,ka=5,_a=6,fl=7,pl=8,ml=typeof self=="object"?self:globalThis,by=(e,t)=>{const r=(a,i)=>(e.set(i,a),a),n=a=>{if(e.has(a))return e.get(a);const[i,s]=t[a];switch(i){case an:case hl:return r(s,a);case wr:{const o=r([],a);for(const l of s)o.push(n(l));return o}case sn:{const o=r({},a);for(const[l,u]of s)o[n(l)]=n(u);return o}case va:return r(new Date(s),a);case Sa:{const{source:o,flags:l}=s;return r(new RegExp(o,l),a)}case ka:{const o=r(new Map,a);for(const[l,u]of s)o.set(n(l),n(u));return o}case _a:{const o=r(new Set,a);for(const l of s)o.add(n(l));return o}case fl:{const{name:o,message:l}=s;return r(new ml[o](l),a)}case pl:return r(BigInt(s),a);case"BigInt":return r(Object(BigInt(s)),a);case"ArrayBuffer":return r(new Uint8Array(s).buffer,s);case"DataView":{const{buffer:o}=new Uint8Array(s);return r(new DataView(o),s)}}return r(new ml[i](s),a)};return n},gl=e=>by(new Map,e)(0),Vt="",{toString:wy}={},{keys:xy}=Object,xr=e=>{const t=typeof e;if(t!=="object"||!e)return[an,t];const r=wy.call(e).slice(8,-1);switch(r){case"Array":return[wr,Vt];case"Object":return[sn,Vt];case"Date":return[va,Vt];case"RegExp":return[Sa,Vt];case"Map":return[ka,Vt];case"Set":return[_a,Vt];case"DataView":return[wr,r]}return r.includes("Array")?[wr,r]:r.includes("Error")?[fl,r]:[sn,r]},on=([e,t])=>e===an&&(t==="function"||t==="symbol"),vy=(e,t,r,n)=>{const a=(s,o)=>{const l=n.push(s)-1;return r.set(o,l),l},i=s=>{if(r.has(s))return r.get(s);let[o,l]=xr(s);switch(o){case an:{let d=s;switch(l){case"bigint":o=pl,d=s.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+l);d=null;break;case"undefined":return a([hl],s)}return a([o,d],s)}case wr:{if(l){let f=s;return l==="DataView"?f=new Uint8Array(s.buffer):l==="ArrayBuffer"&&(f=new Uint8Array(s)),a([l,[...f]],s)}const d=[],c=a([o,d],s);for(const f of s)d.push(i(f));return c}case sn:{if(l)switch(l){case"BigInt":return a([l,s.toString()],s);case"Boolean":case"Number":case"String":return a([l,s.valueOf()],s)}if(t&&"toJSON"in s)return i(s.toJSON());const d=[],c=a([o,d],s);for(const f of xy(s))(e||!on(xr(s[f])))&&d.push([i(f),i(s[f])]);return c}case va:return a([o,s.toISOString()],s);case Sa:{const{source:d,flags:c}=s;return a([o,{source:d,flags:c}],s)}case ka:{const d=[],c=a([o,d],s);for(const[f,h]of s)(e||!(on(xr(f))||on(xr(h))))&&d.push([i(f),i(h)]);return c}case _a:{const d=[],c=a([o,d],s);for(const f of s)(e||!on(xr(f)))&&d.push(i(f));return c}}const{message:u}=s;return a([o,{name:l,message:u}],s)};return i},yl=(e,{json:t,lossy:r}={})=>{const n=[];return vy(!(t||r),!!t,new Map,n)(e),n},ln=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?gl(yl(e,t)):structuredClone(e):(e,t)=>gl(yl(e,t));function Sy(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 ky(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||Sy,n=e.options.footnoteBackLabel||ky,a=e.options.footnoteLabel||"Footnotes",i=e.options.footnoteLabelTagName||"h2",s=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=Ht(c.toLowerCase());let h=0;const y=[],S=e.footnoteCounts.get(c);for(;S!==void 0&&++h<=S;){y.length>0&&y.push({type:"text",value:" "});let _=typeof r=="string"?r:r(l,h);typeof _=="string"&&(_={type:"text",value:_}),y.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(_)?_:[_]})}const x=d[d.length-1];if(x&&x.type==="element"&&x.tagName==="p"){const _=x.children[x.children.length-1];_&&_.type==="text"?_.value+=" ":x.children.push({type:"text",value:" "}),x.children.push(...y)}else d.push(...y);const b={type:"element",tagName:"li",properties:{id:t+"fn-"+f},children:e.wrap(d,!0)};e.patch(u,b),o.push(b)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:E(m({},ln(s)),{id:"footnote-label"}),children:[{type:"text",value:a}]},{type:"text",value:`
10
+ `;break}case-2:{s=t?" ":" ";break}case-1:{if(!t&&a)continue;s=" ";break}default:s=String.fromCharCode(i)}a=i===-2,n.push(s)}return n.join("")}function jg(e){const n={constructs:Uo([Fg,...(e||{}).extensions||[]]),content:a(cm),defined:[],document:a(hm),flow:a(Mg),lazy:{},string:a(Lg),text:a(Dg)};return n;function a(i){return s;function s(o){return Bg(n,i,o)}}}function $g(e){for(;!Xo(e););return e}const il=/[\0\t\n\r]/g;function Ug(){let e=1,t="",r=!0,n;return a;function a(i,s,o){const l=[];let u,c,d,f,h;for(i=t+(typeof i=="string"?i.toString():new TextDecoder(s||void 0).decode(i)),d=0,t="",r&&(i.charCodeAt(0)===65279&&d++,r=void 0);d<i.length;){if(il.lastIndex=d,u=il.exec(i),f=u&&u.index!==void 0?u.index:i.length,h=i.charCodeAt(f),!u){t=i.slice(d);break}if(h===10&&d===f&&n)l.push(-3),n=void 0;else switch(n&&(l.push(-5),n=void 0),d<f&&(l.push(i.slice(d,f)),e+=f-d),h){case 0:{l.push(65533),e++;break}case 9:{for(c=Math.ceil(e/4)*4,l.push(-2);e++<c;)l.push(-1);break}case 10:{l.push(-4),e=1;break}default:n=!0,e=1}d=f+1}return o&&(n&&l.push(-5),t&&l.push(t),l.push(null)),l}}const Hg=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function qg(e){return e.replace(Hg,Vg)}function Vg(e,t,r){if(t)return t;if(r.charCodeAt(0)===35){const a=r.charCodeAt(1),i=a===120||a===88;return Ho(r.slice(i?2:1),i?16:10)}return ga(r)||e}const sl={}.hasOwnProperty;function Wg(e,t,r){return typeof t!="string"&&(r=t,t=void 0),Jg(r)($g(jg(r).document().write(Ug()(e,t,!0))))}function Jg(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(Ar),autolinkProtocol:j,autolinkEmail:j,atxHeading:i(Er),blockQuote:i(He),characterEscape:j,characterReference:j,codeFenced:i(Kt),codeFencedFenceInfo:s,codeFencedFenceMeta:s,codeIndented:i(Kt,s),codeText:i(ti,s),codeTextData:j,data:j,codeFlowValue:j,definition:i(Yt),definitionDestinationString:s,definitionLabelString:s,definitionTitleString:s,emphasis:i(Gt),hardBreakEscape:i(Oe),hardBreakTrailing:i(Oe),htmlFlow:i(yn,s),htmlFlowData:j,htmlText:i(yn,s),htmlTextData:j,image:i(Pt),label:s,link:i(Ar),listItem:i(bn),listItemValue:f,listOrdered:i(yt,d),listUnordered:i(yt),paragraph:i(ri),reference:v,referenceString:s,resourceDestinationString:s,resourceTitleString:s,setextHeading:i(Er),strong:i(wn),thematicBreak:i(nt)},exit:{atxHeading:l(),atxHeadingSequence:F,autolink:l(),autolinkEmail:ge,autolinkProtocol:Te,blockQuote:l(),characterEscapeValue:S,characterReferenceMarkerHexadecimal:oe,characterReferenceMarkerNumeric:oe,characterReferenceValue:ne,characterReference:_e,codeFenced:l(w),codeFencedFence:k,codeFencedFenceInfo:h,codeFencedFenceMeta:g,codeFlowValue:S,codeIndented:l(b),codeText:l(D),codeTextData:S,data:S,definition:l(),definitionDestinationString:B,definitionLabelString:I,definitionTitleString:T,emphasis:l(),hardBreakEscape:l(M),hardBreakTrailing:l(M),htmlFlow:l(J),htmlFlowData:S,htmlText:l(z),htmlTextData:S,image:l(ce),label:me,labelText:se,lineEnding:N,link:l(Y),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:U,resourceDestinationString:x,resourceTitleString:Se,resource:ve,setextHeading:l(R),setextHeadingLineSequence:$,setextHeadingText:_,strong:l(),thematicBreak:l()}};ol(t,(e||{}).mdastExtensions||[]);const r={};return n;function n(A){let O={type:"root",children:[]};const K={stack:[O],tokenStack:[],config:t,enter:o,exit:u,buffer:s,resume:c,data:r},Z=[];let ae=-1;for(;++ae<A.length;)if(A[ae][1].type==="listOrdered"||A[ae][1].type==="listUnordered")if(A[ae][0]==="enter")Z.push(ae);else{const Fe=Z.pop();ae=a(A,Fe,ae)}for(ae=-1;++ae<A.length;){const Fe=t[A[ae][0]];sl.call(Fe,A[ae][1].type)&&Fe[A[ae][1].type].call(Object.assign({sliceSerialize:A[ae][2].sliceSerialize},K),A[ae][1])}if(K.tokenStack.length>0){const Fe=K.tokenStack[K.tokenStack.length-1];(Fe[1]||ll).call(K,void 0,Fe[0])}for(O.position={start:gt(A.length>0?A[0][1].start:{line:1,column:1,offset:0}),end:gt(A.length>0?A[A.length-2][1].end:{line:1,column:1,offset:0})},ae=-1;++ae<t.transforms.length;)O=t.transforms[ae](O)||O;return O}function a(A,O,K){let Z=O-1,ae=-1,Fe=!1,wt,q,ie,te;for(;++Z<=K;){const we=A[Z];switch(we[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{we[0]==="enter"?ae++:ae--,te=void 0;break}case"lineEndingBlank":{we[0]==="enter"&&(wt&&!te&&!ae&&!ie&&(ie=Z),te=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:te=void 0}if(!ae&&we[0]==="enter"&&we[1].type==="listItemPrefix"||ae===-1&&we[0]==="exit"&&(we[1].type==="listUnordered"||we[1].type==="listOrdered")){if(wt){let Ke=Z;for(q=void 0;Ke--;){const Ye=A[Ke];if(Ye[1].type==="lineEnding"||Ye[1].type==="lineEndingBlank"){if(Ye[0]==="exit")continue;q&&(A[q][1].type="lineEndingBlank",Fe=!0),Ye[1].type="lineEnding",q=Ke}else if(!(Ye[1].type==="linePrefix"||Ye[1].type==="blockQuotePrefix"||Ye[1].type==="blockQuotePrefixWhitespace"||Ye[1].type==="blockQuoteMarker"||Ye[1].type==="listItemIndent"))break}ie&&(!q||ie<q)&&(wt._spread=!0),wt.end=Object.assign({},q?A[q][1].start:we[1].end),A.splice(q||Z,0,["exit",wt,we[2]]),Z++,K++}if(we[1].type==="listItemPrefix"){const Ke={type:"listItem",_spread:!1,start:Object.assign({},we[1].start),end:void 0};wt=Ke,A.splice(Z,0,["enter",Ke,we[2]]),Z++,K++,ie=void 0,te=!0}}}return A[O][1]._spread=Fe,K}function i(A,O){return K;function K(Z){o.call(this,A(Z),Z),O&&O.call(this,Z)}}function s(){this.stack.push({type:"fragment",children:[]})}function o(A,O,K){this.stack[this.stack.length-1].children.push(A),this.stack.push(A),this.tokenStack.push([O,K||void 0]),A.position={start:gt(O.start),end:void 0}}function l(A){return O;function O(K){A&&A.call(this,K),u.call(this,K)}}function u(A,O){const K=this.stack.pop(),Z=this.tokenStack.pop();if(Z)Z[0].type!==A.type&&(O?O.call(this,A,Z[0]):(Z[1]||ll).call(this,A,Z[0]));else throw new Error("Cannot close `"+A.type+"` ("+mr({start:A.start,end:A.end})+"): it’s not open");K.position.end=gt(A.end)}function c(){return ma(this.stack.pop())}function d(){this.data.expectingFirstListItemValue=!0}function f(A){if(this.data.expectingFirstListItemValue){const O=this.stack[this.stack.length-2];O.start=Number.parseInt(this.sliceSerialize(A),10),this.data.expectingFirstListItemValue=void 0}}function h(){const A=this.resume(),O=this.stack[this.stack.length-1];O.lang=A}function g(){const A=this.resume(),O=this.stack[this.stack.length-1];O.meta=A}function k(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function w(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A.replace(/(\r?\n|\r)$/g,"")}function I(A){const O=this.resume(),K=this.stack[this.stack.length-1];K.label=O,K.identifier=tt(this.sliceSerialize(A)).toLowerCase()}function T(){const A=this.resume(),O=this.stack[this.stack.length-1];O.title=A}function B(){const A=this.resume(),O=this.stack[this.stack.length-1];O.url=A}function F(A){const O=this.stack[this.stack.length-1];if(!O.depth){const K=this.sliceSerialize(A).length;O.depth=K}}function _(){this.data.setextHeadingSlurpLineEnding=!0}function $(A){const O=this.stack[this.stack.length-1];O.depth=this.sliceSerialize(A).codePointAt(0)===61?1:2}function R(){this.data.setextHeadingSlurpLineEnding=void 0}function j(A){const K=this.stack[this.stack.length-1].children;let Z=K[K.length-1];(!Z||Z.type!=="text")&&(Z=bt(),Z.position={start:gt(A.start),end:void 0},K.push(Z)),this.stack.push(Z)}function S(A){const O=this.stack.pop();O.value+=this.sliceSerialize(A),O.position.end=gt(A.end)}function N(A){const O=this.stack[this.stack.length-1];if(this.data.atHardBreak){const K=O.children[O.children.length-1];K.position.end=gt(A.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(O.type)&&(j.call(this,A),S.call(this,A))}function M(){this.data.atHardBreak=!0}function J(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A}function z(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A}function D(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A}function Y(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const O=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=O,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function ce(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const O=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=O,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function se(A){const O=this.sliceSerialize(A),K=this.stack[this.stack.length-2];K.label=qg(O),K.identifier=tt(O).toLowerCase()}function me(){const A=this.stack[this.stack.length-1],O=this.resume(),K=this.stack[this.stack.length-1];if(this.data.inReference=!0,K.type==="link"){const Z=A.children;K.children=Z}else K.alt=O}function x(){const A=this.resume(),O=this.stack[this.stack.length-1];O.url=A}function Se(){const A=this.resume(),O=this.stack[this.stack.length-1];O.title=A}function ve(){this.data.inReference=void 0}function v(){this.data.referenceType="collapsed"}function U(A){const O=this.resume(),K=this.stack[this.stack.length-1];K.label=O,K.identifier=tt(this.sliceSerialize(A)).toLowerCase(),this.data.referenceType="full"}function oe(A){this.data.characterReferenceType=A.type}function ne(A){const O=this.sliceSerialize(A),K=this.data.characterReferenceType;let Z;K?(Z=Ho(O,K==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Z=ga(O);const ae=this.stack[this.stack.length-1];ae.value+=Z}function _e(A){const O=this.stack.pop();O.position.end=gt(A.end)}function Te(A){S.call(this,A);const O=this.stack[this.stack.length-1];O.url=this.sliceSerialize(A)}function ge(A){S.call(this,A);const O=this.stack[this.stack.length-1];O.url="mailto:"+this.sliceSerialize(A)}function He(){return{type:"blockquote",children:[]}}function Kt(){return{type:"code",lang:null,meta:null,value:""}}function ti(){return{type:"inlineCode",value:""}}function Yt(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Gt(){return{type:"emphasis",children:[]}}function Er(){return{type:"heading",depth:0,children:[]}}function Oe(){return{type:"break"}}function yn(){return{type:"html",value:""}}function Pt(){return{type:"image",title:null,url:"",alt:null}}function Ar(){return{type:"link",title:null,url:"",children:[]}}function yt(A){return{type:"list",ordered:A.type==="listOrdered",start:null,spread:A._spread,children:[]}}function bn(A){return{type:"listItem",spread:A._spread,checked:null,children:[]}}function ri(){return{type:"paragraph",children:[]}}function wn(){return{type:"strong",children:[]}}function bt(){return{type:"text",value:""}}function nt(){return{type:"thematicBreak"}}}function gt(e){return{line:e.line,column:e.column,offset:e.offset}}function ol(e,t){let r=-1;for(;++r<t.length;){const n=t[r];Array.isArray(n)?ol(e,n):Kg(e,n)}}function Kg(e,t){let r;for(r in t)if(sl.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 ll(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+mr({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+mr({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+mr({start:t.start,end:t.end})+") is still open")}function Yg(e){const t=this;t.parser=r;function r(n){return Wg(n,E(m(m({},t.data("settings")),e),{extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]}))}}function Gg(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 Xg(e,t){const r={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,r),[e.applyData(t,r),{type:"text",value:`
11
+ `}]}function Qg(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 i={type:"element",tagName:"code",properties:n,children:[{type:"text",value:r}]};return t.meta&&(i.data={meta:t.meta}),e.patch(t,i),i=e.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},e.patch(t,i),i}function Zg(e,t){const r={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function ey(e,t){const r={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function ty(e,t){const r=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=String(t.identifier).toUpperCase(),a=qt(n.toLowerCase()),i=e.footnoteOrder.indexOf(n);let s,o=e.footnoteCounts.get(n);o===void 0?(o=0,e.footnoteOrder.push(n),s=e.footnoteOrder.length):s=i+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(s)}]};e.patch(t,l);const u={type:"element",tagName:"sup",properties:{},children:[l]};return e.patch(t,u),e.applyData(t,u)}function ry(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 ny(e,t){if(e.options.allowDangerousHtml){const r={type:"raw",value:t.value};return e.patch(t,r),e.applyData(t,r)}}function ul(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),i=a[0];i&&i.type==="text"?i.value="["+i.value:a.unshift({type:"text",value:"["});const s=a[a.length-1];return s&&s.type==="text"?s.value+=n:a.push({type:"text",value:n}),a}function ay(e,t){const r=String(t.identifier).toUpperCase(),n=e.definitionById.get(r);if(!n)return ul(e,t);const a={src:qt(n.url||""),alt:t.alt};n.title!==null&&n.title!==void 0&&(a.title=n.title);const i={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,i),e.applyData(t,i)}function iy(e,t){const r={src:qt(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 sy(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 oy(e,t){const r=String(t.identifier).toUpperCase(),n=e.definitionById.get(r);if(!n)return ul(e,t);const a={href:qt(n.url||"")};n.title!==null&&n.title!==void 0&&(a.title=n.title);const i={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function ly(e,t){const r={href:qt(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 uy(e,t,r){const n=e.all(t),a=r?cy(r):cl(t),i={},s=[];if(typeof t.checked=="boolean"){const c=n[0];let d;c&&c.type==="element"&&c.tagName==="p"?d=c:(d={type:"element",tagName:"p",properties:{},children:[]},n.unshift(d)),d.children.length>0&&d.children.unshift({type:"text",value:" "}),d.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let o=-1;for(;++o<n.length;){const c=n[o];(a||o!==0||c.type!=="element"||c.tagName!=="p")&&s.push({type:"text",value:`
13
+ `}),c.type==="element"&&c.tagName==="p"&&!a?s.push(...c.children):s.push(c)}const l=n[n.length-1];l&&(a||l.type!=="element"||l.tagName!=="p")&&s.push({type:"text",value:`
14
+ `});const u={type:"element",tagName:"li",properties:i,children:s};return e.patch(t,u),e.applyData(t,u)}function cy(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=cl(r[n])}return t}function cl(e){const t=e.spread;return t==null?e.children.length>1:t}function dy(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 s=n[a];if(s.type==="element"&&s.tagName==="li"&&s.properties&&Array.isArray(s.properties.className)&&s.properties.className.includes("task-list-item")){r.className=["contains-task-list"];break}}const i={type:"element",tagName:t.ordered?"ol":"ul",properties:r,children:e.wrap(n,!0)};return e.patch(t,i),e.applyData(t,i)}function hy(e,t){const r={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function fy(e,t){const r={type:"root",children:e.wrap(e.all(t))};return e.patch(t,r),e.applyData(t,r)}function py(e,t){const r={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function my(e,t){const r=e.all(t),n=r.shift(),a=[];if(n){const s={type:"element",tagName:"thead",properties:{},children:e.wrap([n],!0)};e.patch(t.children[0],s),a.push(s)}if(r.length>0){const s={type:"element",tagName:"tbody",properties:{},children:e.wrap(r,!0)},o=ua(t.children[1]),l=Mo(t.children[t.children.length-1]);o&&l&&(s.position={start:o,end:l}),a.push(s)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(a,!0)};return e.patch(t,i),e.applyData(t,i)}function gy(e,t,r){const n=r?r.children:void 0,i=(n?n.indexOf(t):1)===0?"th":"td",s=r&&r.type==="table"?r.align:void 0,o=s?s.length:t.children.length;let l=-1;const u=[];for(;++l<o;){const d=t.children[l],f={},h=s?s[l]:void 0;h&&(f.align=h);let g={type:"element",tagName:i,properties:f,children:[]};d&&(g.children=e.all(d),e.patch(d,g),g=e.applyData(d,g)),u.push(g)}const c={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(t,c),e.applyData(t,c)}function yy(e,t){const r={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}const dl=9,hl=32;function by(e){const t=String(e),r=/\r?\n|\r/g;let n=r.exec(t),a=0;const i=[];for(;n;)i.push(fl(t.slice(a,n.index),a>0,!0),n[0]),a=n.index+n[0].length,n=r.exec(t);return i.push(fl(t.slice(a),a>0,!1)),i.join("")}function fl(e,t,r){let n=0,a=e.length;if(t){let i=e.codePointAt(n);for(;i===dl||i===hl;)n++,i=e.codePointAt(n)}if(r){let i=e.codePointAt(a-1);for(;i===dl||i===hl;)a--,i=e.codePointAt(a-1)}return a>n?e.slice(n,a):""}function wy(e,t){const r={type:"text",value:by(String(t.value))};return e.patch(t,r),e.applyData(t,r)}function xy(e,t){const r={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,r),e.applyData(t,r)}const vy={blockquote:Gg,break:Xg,code:Qg,delete:Zg,emphasis:ey,footnoteReference:ty,heading:ry,html:ny,imageReference:ay,image:iy,inlineCode:sy,linkReference:oy,link:ly,listItem:uy,list:dy,paragraph:hy,root:fy,strong:py,table:my,tableCell:yy,tableRow:gy,text:wy,thematicBreak:xy,toml:sn,yaml:sn,definition:sn,footnoteDefinition:sn};function sn(){}const pl=-1,on=0,xr=1,ln=2,ka=3,Sa=4,_a=5,Ta=6,ml=7,gl=8,yl=typeof self=="object"?self:globalThis,ky=(e,t)=>{const r=(a,i)=>(e.set(i,a),a),n=a=>{if(e.has(a))return e.get(a);const[i,s]=t[a];switch(i){case on:case pl:return r(s,a);case xr:{const o=r([],a);for(const l of s)o.push(n(l));return o}case ln:{const o=r({},a);for(const[l,u]of s)o[n(l)]=n(u);return o}case ka:return r(new Date(s),a);case Sa:{const{source:o,flags:l}=s;return r(new RegExp(o,l),a)}case _a:{const o=r(new Map,a);for(const[l,u]of s)o.set(n(l),n(u));return o}case Ta:{const o=r(new Set,a);for(const l of s)o.add(n(l));return o}case ml:{const{name:o,message:l}=s;return r(new yl[o](l),a)}case gl:return r(BigInt(s),a);case"BigInt":return r(Object(BigInt(s)),a);case"ArrayBuffer":return r(new Uint8Array(s).buffer,s);case"DataView":{const{buffer:o}=new Uint8Array(s);return r(new DataView(o),s)}}return r(new yl[i](s),a)};return n},bl=e=>ky(new Map,e)(0),Wt="",{toString:Sy}={},{keys:_y}=Object,vr=e=>{const t=typeof e;if(t!=="object"||!e)return[on,t];const r=Sy.call(e).slice(8,-1);switch(r){case"Array":return[xr,Wt];case"Object":return[ln,Wt];case"Date":return[ka,Wt];case"RegExp":return[Sa,Wt];case"Map":return[_a,Wt];case"Set":return[Ta,Wt];case"DataView":return[xr,r]}return r.includes("Array")?[xr,r]:r.includes("Error")?[ml,r]:[ln,r]},un=([e,t])=>e===on&&(t==="function"||t==="symbol"),Ty=(e,t,r,n)=>{const a=(s,o)=>{const l=n.push(s)-1;return r.set(o,l),l},i=s=>{if(r.has(s))return r.get(s);let[o,l]=vr(s);switch(o){case on:{let c=s;switch(l){case"bigint":o=gl,c=s.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+l);c=null;break;case"undefined":return a([pl],s)}return a([o,c],s)}case xr:{if(l){let f=s;return l==="DataView"?f=new Uint8Array(s.buffer):l==="ArrayBuffer"&&(f=new Uint8Array(s)),a([l,[...f]],s)}const c=[],d=a([o,c],s);for(const f of s)c.push(i(f));return d}case ln:{if(l)switch(l){case"BigInt":return a([l,s.toString()],s);case"Boolean":case"Number":case"String":return a([l,s.valueOf()],s)}if(t&&"toJSON"in s)return i(s.toJSON());const c=[],d=a([o,c],s);for(const f of _y(s))(e||!un(vr(s[f])))&&c.push([i(f),i(s[f])]);return d}case ka:return a([o,s.toISOString()],s);case Sa:{const{source:c,flags:d}=s;return a([o,{source:c,flags:d}],s)}case _a:{const c=[],d=a([o,c],s);for(const[f,h]of s)(e||!(un(vr(f))||un(vr(h))))&&c.push([i(f),i(h)]);return d}case Ta:{const c=[],d=a([o,c],s);for(const f of s)(e||!un(vr(f)))&&c.push(i(f));return d}}const{message:u}=s;return a([o,{name:l,message:u}],s)};return i},wl=(e,{json:t,lossy:r}={})=>{const n=[];return Ty(!(t||r),!!t,new Map,n)(e),n},cn=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?bl(wl(e,t)):structuredClone(e):(e,t)=>bl(wl(e,t));function Cy(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 Iy(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function Ey(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=e.options.footnoteBackContent||Cy,n=e.options.footnoteBackLabel||Iy,a=e.options.footnoteLabel||"Footnotes",i=e.options.footnoteLabelTagName||"h2",s=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 c=e.all(u),d=String(u.identifier).toUpperCase(),f=qt(d.toLowerCase());let h=0;const g=[],k=e.footnoteCounts.get(d);for(;k!==void 0&&++h<=k;){g.length>0&&g.push({type:"text",value:" "});let I=typeof r=="string"?r:r(l,h);typeof I=="string"&&(I={type:"text",value:I}),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(I)?I:[I]})}const w=c[c.length-1];if(w&&w.type==="element"&&w.tagName==="p"){const I=w.children[w.children.length-1];I&&I.type==="text"?I.value+=" ":w.children.push({type:"text",value:" "}),w.children.push(...g)}else c.push(...g);const b={type:"element",tagName:"li",properties:{id:t+"fn-"+f},children:e.wrap(c,!0)};e.patch(u,b),o.push(b)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:E(m({},cn(s)),{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 un=(function(e){if(e==null)return Ey;if(typeof e=="function")return cn(e);if(typeof e=="object")return Array.isArray(e)?Ty(e):Cy(e);if(typeof e=="string")return Iy(e);throw new Error("Expected function, string, or object as test")});function Ty(e){const t=[];let r=-1;for(;++r<e.length;)t[r]=un(e[r]);return cn(n);function n(...a){let i=-1;for(;++i<t.length;)if(t[i].apply(this,a))return!0;return!1}}function Cy(e){const t=e;return cn(r);function r(n){const a=n;let i;for(i in e)if(a[i]!==t[i])return!1;return!0}}function Iy(e){return cn(t);function t(r){return r&&r.type===e}}function cn(e){return t;function t(r,n,a){return!!(Ay(r)&&e.call(this,r,typeof n=="number"?n:void 0,a||void 0))}}function Ey(){return!0}function Ay(e){return e!==null&&typeof e=="object"&&"type"in e}function Av(e){return e}const bl=[],Py=!0,Ta=!1,My="skip";function wl(e,t,r,n){let a;typeof t=="function"&&typeof r!="function"?(n=r,r=t):a=t;const i=un(a),s=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,y,S,x;if((!t||i(l,u,d[d.length-1]||void 0))&&(h=Ny(r(l,d)),h[0]===Ta))return h;if("children"in l&&l.children){const b=l;if(b.children&&h[0]!==My)for(S=(n?b.children.length:-1)+s,x=d.concat(b);S>-1&&S<b.children.length;){const _=b.children[S];if(y=o(_,S,x)(),y[0]===Ta)return y;S=typeof y[1]=="number"?y[1]:S+s}}return h}}}function Ny(e){return Array.isArray(e)?e:typeof e=="number"?[Py,e]:e==null?bl:[e]}function Ca(e,t,r,n){let a,i,s;typeof t=="function"&&typeof r!="function"?(i=void 0,s=t,a=r):(i=t,s=r,a=n),wl(e,i,o,a);function o(l,u){const d=u[u.length-1],c=d?d.children.indexOf(l):void 0;return s(l,c,d)}}const Ia={}.hasOwnProperty,Ly={};function Dy(e,t){const r=t||Ly,n=new Map,a=new Map,i=new Map,s=m(m({},yy),r.handlers),o={all:u,applyData:Fy,definitionById:n,footnoteById:a,footnoteCounts:i,footnoteOrder:[],handlers:s,one:l,options:r,patch:Oy,wrap:zy};return Ca(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(Ia.call(o.handlers,f)&&h)return h(o,d,c);if(o.options.passThrough&&o.options.passThrough.includes(f)){if("children"in d){const S=d,{children:x}=S,b=W(S,["children"]),_=ln(b);return _.children=o.all(d),_}return ln(d)}return(o.options.unknownHandler||By)(o,d,c)}function u(d){const c=[];if("children"in d){const f=d.children;let h=-1;for(;++h<f.length;){const y=o.one(f[h],d);if(y){if(h&&f[h-1].type==="break"&&(!Array.isArray(y)&&y.type==="text"&&(y.value=xl(y.value)),!Array.isArray(y)&&y.type==="element")){const S=y.children[0];S&&S.type==="text"&&(S.value=xl(S.value))}Array.isArray(y)?c.push(...y):c.push(y)}}}return c}}function Oy(e,t){e.position&&(t.position=Np(e))}function Fy(e,t){let r=t;if(e&&e.data){const n=e.data.hName,a=e.data.hChildren,i=e.data.hProperties;if(typeof n=="string")if(r.type==="element")r.tagName=n;else{const s="children"in r?r.children:[r];r={type:"element",tagName:n,properties:{},children:s}}r.type==="element"&&i&&Object.assign(r.properties,ln(i)),"children"in r&&r.children&&a!==null&&a!==void 0&&(r.children=a)}return r}function By(e,t){const r=t.data||{},n="value"in t&&!(Ia.call(r,"hProperties")||Ia.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 zy(e,t){const r=[];let n=-1;for(t&&r.push({type:"text",value:`
16
+ `}]}}const dn=(function(e){if(e==null)return Ny;if(typeof e=="function")return hn(e);if(typeof e=="object")return Array.isArray(e)?Ay(e):My(e);if(typeof e=="string")return Py(e);throw new Error("Expected function, string, or object as test")});function Ay(e){const t=[];let r=-1;for(;++r<e.length;)t[r]=dn(e[r]);return hn(n);function n(...a){let i=-1;for(;++i<t.length;)if(t[i].apply(this,a))return!0;return!1}}function My(e){const t=e;return hn(r);function r(n){const a=n;let i;for(i in e)if(a[i]!==t[i])return!1;return!0}}function Py(e){return hn(t);function t(r){return r&&r.type===e}}function hn(e){return t;function t(r,n,a){return!!(Ly(r)&&e.call(this,r,typeof n=="number"?n:void 0,a||void 0))}}function Ny(){return!0}function Ly(e){return e!==null&&typeof e=="object"&&"type"in e}function Uv(e){return e}const xl=[],Dy=!0,Ca=!1,Oy="skip";function vl(e,t,r,n){let a;typeof t=="function"&&typeof r!="function"?(n=r,r=t):a=t;const i=dn(a),s=n?-1:1;o(e,void 0,[])();function o(l,u,c){const d=l&&typeof l=="object"?l:{};if(typeof d.type=="string"){const h=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(l.type+(h?"<"+h+">":""))+")"})}return f;function f(){let h=xl,g,k,w;if((!t||i(l,u,c[c.length-1]||void 0))&&(h=Fy(r(l,c)),h[0]===Ca))return h;if("children"in l&&l.children){const b=l;if(b.children&&h[0]!==Oy)for(k=(n?b.children.length:-1)+s,w=c.concat(b);k>-1&&k<b.children.length;){const I=b.children[k];if(g=o(I,k,w)(),g[0]===Ca)return g;k=typeof g[1]=="number"?g[1]:k+s}}return h}}}function Fy(e){return Array.isArray(e)?e:typeof e=="number"?[Dy,e]:e==null?xl:[e]}function Ia(e,t,r,n){let a,i,s;typeof t=="function"&&typeof r!="function"?(i=void 0,s=t,a=r):(i=t,s=r,a=n),vl(e,i,o,a);function o(l,u){const c=u[u.length-1],d=c?c.children.indexOf(l):void 0;return s(l,d,c)}}const Ea={}.hasOwnProperty,By={};function zy(e,t){const r=t||By,n=new Map,a=new Map,i=new Map,s=m(m({},vy),r.handlers),o={all:u,applyData:jy,definitionById:n,footnoteById:a,footnoteCounts:i,footnoteOrder:[],handlers:s,one:l,options:r,patch:Ry,wrap:Uy};return Ia(e,function(c){if(c.type==="definition"||c.type==="footnoteDefinition"){const d=c.type==="definition"?n:a,f=String(c.identifier).toUpperCase();d.has(f)||d.set(f,c)}}),o;function l(c,d){const f=c.type,h=o.handlers[f];if(Ea.call(o.handlers,f)&&h)return h(o,c,d);if(o.options.passThrough&&o.options.passThrough.includes(f)){if("children"in c){const k=c,{children:w}=k,b=V(k,["children"]),I=cn(b);return I.children=o.all(c),I}return cn(c)}return(o.options.unknownHandler||$y)(o,c,d)}function u(c){const d=[];if("children"in c){const f=c.children;let h=-1;for(;++h<f.length;){const g=o.one(f[h],c);if(g){if(h&&f[h-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=kl(g.value)),!Array.isArray(g)&&g.type==="element")){const k=g.children[0];k&&k.type==="text"&&(k.value=kl(k.value))}Array.isArray(g)?d.push(...g):d.push(g)}}}return d}}function Ry(e,t){e.position&&(t.position=Fp(e))}function jy(e,t){let r=t;if(e&&e.data){const n=e.data.hName,a=e.data.hChildren,i=e.data.hProperties;if(typeof n=="string")if(r.type==="element")r.tagName=n;else{const s="children"in r?r.children:[r];r={type:"element",tagName:n,properties:{},children:s}}r.type==="element"&&i&&Object.assign(r.properties,cn(i)),"children"in r&&r.children&&a!==null&&a!==void 0&&(r.children=a)}return r}function $y(e,t){const r=t.data||{},n="value"in t&&!(Ea.call(r,"hProperties")||Ea.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 Uy(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 xl(e){let t=0,r=e.charCodeAt(t);for(;r===9||r===32;)t++,r=e.charCodeAt(t);return e.slice(t)}function vl(e,t){const r=Dy(e,t),n=r.one(e,void 0),a=_y(r),i=Array.isArray(n)?{type:"root",children:n}:n||{type:"root",children:[]};return a&&i.children.push({type:"text",value:`
20
- `},a),i}function Ry(e,t){return e&&"run"in e?function(r,n){return P(this,null,function*(){const a=vl(r,m({file:n},t));yield e.run(a,n)})}:function(r,n){return vl(r,m({file:n},e||t))}}function Sl(e){if(e)throw e}var Ea,kl;function jy(){if(kl)return Ea;kl=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]"},i=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 Ea=function l(){var u,d,c,f,h,y,S=arguments[0],x=1,b=arguments.length,_=!1;for(typeof S=="boolean"&&(_=S,S=arguments[1]||{},x=2),(S==null||typeof S!="object"&&typeof S!="function")&&(S={});x<b;++x)if(u=arguments[x],u!=null)for(d in u)c=o(S,d),f=o(u,d),S!==f&&(_&&f&&(i(f)||(h=a(f)))?(h?(h=!1,y=c&&a(c)?c:[]):y=c&&i(c)?c:{},s(S,{name:d,newValue:l(_,y,f)})):typeof f!="undefined"&&s(S,{name:d,newValue:f}));return S},Ea}var $y=jy();const Aa=Ar($y);function Pa(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 Uy(){const e=[],t={run:r,use:n};return t;function r(...a){let i=-1;const s=a.pop();if(typeof s!="function")throw new TypeError("Expected function as last argument, not "+s);o(null,...a);function o(l,...u){const d=e[++i];let c=-1;if(l){s(l);return}for(;++c<a.length;)(u[c]===null||u[c]===void 0)&&(u[c]=a[c]);a=u,d?Hy(d,o)(...u):s(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 Hy(e,t){let r;return n;function n(...s){const o=e.length>s.length;let l;o&&s.push(a);try{l=e.apply(this,s)}catch(u){const d=u;if(o&&r)throw d;return a(d)}o||(l&&l.then&&typeof l.then=="function"?l.then(i,a):l instanceof Error?a(l):i(l))}function a(s,...o){r||(r=!0,t(s,...o))}function i(s){a(null,s)}}const rt={basename:qy,dirname:Vy,extname:Wy,join:Jy,sep:"/"};function qy(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');vr(e);let r=0,n=-1,a=e.length,i;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(i){r=a+1;break}}else n<0&&(i=!0,n=a+1);return n<0?"":e.slice(r,n)}if(t===e)return"";let s=-1,o=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(i){r=a+1;break}}else s<0&&(i=!0,s=a+1),o>-1&&(e.codePointAt(a)===t.codePointAt(o--)?o<0&&(n=a):(o=-1,n=s));return r===n?n=s:n<0&&(n=e.length),e.slice(r,n)}function Vy(e){if(vr(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 Wy(e){vr(e);let t=e.length,r=-1,n=0,a=-1,i=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?a<0?a=t:i!==1&&(i=1):a>-1&&(i=-1)}return a<0||r<0||i===0||i===1&&a===r-1&&a===n+1?"":e.slice(a,r)}function Jy(...e){let t=-1,r;for(;++t<e.length;)vr(e[t]),e[t]&&(r=r===void 0?e[t]:r+"/"+e[t]);return r===void 0?".":Ky(r)}function Ky(e){vr(e);const t=e.codePointAt(0)===47;let r=Gy(e,!t);return r.length===0&&!t&&(r="."),r.length>0&&e.codePointAt(e.length-1)===47&&(r+="/"),t?"/"+r:r}function Gy(e,t){let r="",n=0,a=-1,i=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(!(a===s-1||i===1))if(a!==s-1&&i===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=s,i=0;continue}}else if(r.length>0){r="",n=0,a=s,i=0;continue}}t&&(r=r.length>0?r+"/..":"..",n=2)}else r.length>0?r+="/"+e.slice(a+1,s):r=e.slice(a+1,s),n=s-a-1;a=s,i=0}else o===46&&i>-1?i++:i=-1}return r}function vr(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const Yy={cwd:Xy};function Xy(){return"/"}function Ma(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function Qy(e){if(typeof e=="string")e=new URL(e);else if(!Ma(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 Zy(e)}function Zy(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 Na=["history","path","basename","stem","extname","dirname"];class _l{constructor(t){let r;t?Ma(t)?r={path:t}:typeof t=="string"||eb(t)?r={value:t}:r=t:r={},this.cwd="cwd"in r?"":Yy.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let n=-1;for(;++n<Na.length;){const i=Na[n];i in r&&r[i]!==void 0&&r[i]!==null&&(this[i]=i==="history"?[...r[i]]:r[i])}let a;for(a in r)Na.includes(a)||(this[a]=r[a])}get basename(){return typeof this.path=="string"?rt.basename(this.path):void 0}set basename(t){Da(t,"basename"),La(t,"basename"),this.path=rt.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?rt.dirname(this.path):void 0}set dirname(t){Tl(this.basename,"dirname"),this.path=rt.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?rt.extname(this.path):void 0}set extname(t){if(La(t,"extname"),Tl(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=rt.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Ma(t)&&(t=Qy(t)),Da(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?rt.basename(this.path,this.extname):void 0}set stem(t){Da(t,"stem"),La(t,"stem"),this.path=rt.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 ke(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 La(e,t){if(e&&e.includes(rt.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+rt.sep+"`")}function Da(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function Tl(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function eb(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const tb=(function(e){const n=this.constructor.prototype,a=n[e],i=function(){return a.apply(i,arguments)};return Object.setPrototypeOf(i,n),i}),rb={}.hasOwnProperty;class Oa extends tb{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=Uy()}copy(){const t=new Oa;let r=-1;for(;++r<this.attachers.length;){const n=this.attachers[r];t.use(...n)}return t.data(Aa(!0,{},this.namespace)),t}data(t,r){return typeof t=="string"?arguments.length===2?(za("data",this.frozen),this.namespace[t]=r,this):rb.call(this.namespace,t)&&this.namespace[t]||void 0:t?(za("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=dn(t),n=this.parser||this.Parser;return Fa("parse",n),n(String(r),r)}process(t,r){const n=this;return this.freeze(),Fa("process",this.parser||this.Parser),Ba("process",this.compiler||this.Compiler),r?a(void 0,r):new Promise(a);function a(i,s){const o=dn(t),l=n.parse(o);n.run(l,o,function(d,c,f){if(d||!c||!f)return u(d);const h=c,y=n.stringify(h,f);ib(y)?f.value=y:f.result=y,u(d,f)});function u(d,c){d||!c?s(d):i?i(c):r(void 0,c)}}}processSync(t){let r=!1,n;return this.freeze(),Fa("processSync",this.parser||this.Parser),Ba("processSync",this.compiler||this.Compiler),this.process(t,a),Il("processSync","process",r),n;function a(i,s){r=!0,Sl(i),n=s}}run(t,r,n){Cl(t),this.freeze();const a=this.transformers;return!n&&typeof r=="function"&&(n=r,r=void 0),n?i(void 0,n):new Promise(i);function i(s,o){const l=dn(r);a.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,a;return this.run(t,r,i),Il("runSync","run",n),a;function i(s,o){Sl(s),a=o,n=!0}}stringify(t,r){this.freeze();const n=dn(r),a=this.compiler||this.Compiler;return Ba("stringify",a),Cl(t),a(t,n)}use(t,...r){const n=this.attachers,a=this.namespace;if(za("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 i(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&&(a.settings=Aa(!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];i(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,...y]=d;const S=n[f][1];Pa(S)&&Pa(h)&&(h=Aa(!0,S,h)),n[f]=[u,h,...y]}}}}const nb=new Oa().freeze();function Fa(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Ba(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function za(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 Cl(e){if(!Pa(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Il(e,t,r){if(!r)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function dn(e){return ab(e)?e:new _l(e)}function ab(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function ib(e){return typeof e=="string"||sb(e)}function sb(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const ob="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",El=[],Al={allowDangerousHtml:!0},lb=/^(https?|ircs?|mailto|xmpp)$/i,ub=[{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 cb(e){const t=db(e),r=hb(e);return fb(t.runSync(t.parse(r),r),e)}function db(e){const t=e.rehypePlugins||El,r=e.remarkPlugins||El,n=e.remarkRehypeOptions?m(m({},e.remarkRehypeOptions),Al):Al;return nb().use(Vg).use(r).use(Ry,n).use(t)}function hb(e){const t=e.children||"",r=new _l;return typeof t=="string"&&(r.value=t),r}function fb(e,t){const r=t.allowedElements,n=t.allowElement,a=t.components,i=t.disallowedElements,s=t.skipHtml,o=t.unwrapDisallowed,l=t.urlTransform||pb;for(const d of ub)Object.hasOwn(t,d.from)&&(""+d.from+(d.to?"use `"+d.to+"` instead":"remove it")+ob+d.id,void 0);return Ca(e,u),Bp(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 s?f.children.splice(c,1):f.children[c]={type:"text",value:d.value},c;if(d.type==="element"){let h;for(h in fa)if(Object.hasOwn(fa,h)&&Object.hasOwn(d.properties,h)){const y=d.properties[h],S=fa[h];(S===null||S.includes(d.tagName))&&(d.properties[h]=l(String(y||""),h,d))}}if(d.type==="element"){let h=r?!r.includes(d.tagName):i?i.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||lb.test(e.slice(0,t))?e:""}var mb=(e,t)=>typeof e=="string"?e===t:JSON.stringify(e)===JSON.stringify(t),gb=(e,t)=>{if(!e||!t)return!1;const r=n=>{const o=n||{},{position:a,data:i}=o;return W(o,["position","data"])};return JSON.stringify(r(e.properties))===JSON.stringify(r(t.properties))&&mb(e.children,t.children)},Ra=(e,t)=>gb(e.node,t.node),yb=(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:i}=l,s=W(l,["node"]);return p.jsx(n,m({},s))};return[t,g.memo(a,Ra)]})),ja=g.createContext(null),Pl=()=>g.useContext(ja)!==null,bb=r=>{var n=r,{children:e}=n,t=W(n,["children"]);return p.jsx(ja.Provider,{value:t,children:e})},wb=g.memo(bb,Ra),xb=r=>{var n=r,{node:e}=n,t=W(n,["node"]);return p.jsx("pre",m({},t))},vb=r=>{var n=r,{node:e}=n,t=W(n,["node"]);return p.jsx("code",m({},t))},$a=({node:e,components:{Pre:t,Code:r},code:n})=>p.jsx(t,{children:p.jsx(r,{node:e,children:n})}),Sb=()=>null,kb=({node:e,components:{Pre:t,Code:r,SyntaxHighlighter:n,CodeHeader:a},language:i,code:s})=>{const o=g.useMemo(()=>({Pre:t,Code:r}),[t,r]),l=i?n:$a;return p.jsxs(p.Fragment,{children:[p.jsx(a,{node:e,language:i,code:s}),p.jsx(l,{node:e,components:o,language:i!=null?i:"unknown",code:s})]})},Ua={exports:{}};var Ml;function _b(){return Ml||(Ml=1,(function(e){(function(){var t={}.hasOwnProperty;function r(){for(var i="",s=0;s<arguments.length;s++){var o=arguments[s];o&&(i=a(i,n(o)))}return i}function n(i){if(typeof i=="string"||typeof i=="number")return i;if(typeof i!="object")return"";if(Array.isArray(i))return r.apply(null,i);if(i.toString!==Object.prototype.toString&&!i.toString.toString().includes("[native code]"))return i.toString();var s="";for(var o in i)t.call(i,o)&&i[o]&&(s=a(s,o));return s}function a(i,s){return s?i?i+" "+s:i+s:i}e.exports?(r.default=r,e.exports=r):window.classNames=r})()})(Ua)),Ua.exports}var Tb=_b();const Nl=Ar(Tb);var Ll=r=>{var n=r,{className:e}=n,t=W(n,["className"]);return s=>{var o=s,{className:a}=o,i=W(o,["className"]);return m(m({className:Nl(e,a)},t),i)}},Cb=l=>{var u=l,{node:e,components:{Pre:t,Code:r,SyntaxHighlighter:n,CodeHeader:a},componentsByLanguage:i={},children:s}=u,o=W(u,["node","components","componentsByLanguage","children"]);var _,T,L,z,I,q;const d=g.useContext(ja),c=Ll(d),f=Ct(B=>p.jsx(t,m({},c(B)))),h=Ll(o),y=Ct(B=>p.jsx(r,m({},h(B)))),S=(T=(_=/language-(\w+)/.exec(o.className||""))==null?void 0:_[1])!=null?T:"";if(typeof s!="string")return p.jsx($a,{node:e,components:{Pre:f,Code:y},code:s});const x=(z=(L=i[S])==null?void 0:L.SyntaxHighlighter)!=null?z:n,b=(q=(I=i[S])==null?void 0:I.CodeHeader)!=null?q:a;return p.jsx(kb,{node:e,components:{Pre:f,Code:y,SyntaxHighlighter:x,CodeHeader:b},language:S||"unknown",code:s})},Ib=a=>{var i=a,{node:e,components:t,componentsByLanguage:r}=i,n=W(i,["node","components","componentsByLanguage"]);return Pl()?p.jsx(Cb,m({node:e,components:t,componentsByLanguage:r},n)):p.jsx(t.Code,m({},n))},Eb=g.memo(Ib,(e,t)=>e.components===t.components&&e.componentsByLanguage===t.componentsByLanguage&&Ra(e,t)),{useSmooth:Ab,useSmoothStatus:Pb,withSmoothContextProvider:Mb}=jh,Nb=i=>{var s=i,{components:e,componentsByLanguage:t,smooth:r=!0,preprocess:n}=s,a=W(s,["components","componentsByLanguage","smooth","preprocess"]);const o=Is(),l=g.useMemo(()=>n?E(m({},o),{text:n(o.text)}):o,[o,n]),{text:u}=Ab(l,r),{pre:d=xb,code:c=vb,SyntaxHighlighter:f=$a,CodeHeader:h=Sb}=e!=null?e:{},y=g.useMemo(()=>({Pre:d,Code:c,SyntaxHighlighter:f,CodeHeader:h}),[d,c,f,h]),S=Ct(b=>p.jsx(Eb,m({components:y,componentsByLanguage:t},b))),x=g.useMemo(()=>{const I=e!=null?e:{},{pre:b,code:_,SyntaxHighlighter:T,CodeHeader:L}=I,z=W(I,["pre","code","SyntaxHighlighter","CodeHeader"]);return E(m({},z),{pre:wb,code:S})},[S,e]);return p.jsx(cb,E(m({components:x},a),{children:u}))},Dl=g.forwardRef((i,a)=>{var s=i,{className:e,containerProps:t,containerComponent:r="div"}=s,n=W(s,["className","containerProps","containerComponent"]);const o=Pb();return p.jsx(r,E(m({"data-status":o.type},t),{className:Nl(e,t==null?void 0:t.className),ref:a,children:p.jsx(Nb,m({},n))}))});Dl.displayName="MarkdownTextPrimitive";var Lb=Mb(Dl);function Ol(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 Db(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Ob(e,t,r){const a=un((r||{}).ignore||[]),i=Fb(t);let s=-1;for(;++s<i.length;)wl(e,"text",o);function o(u,d){let c=-1,f;for(;++c<d.length;){const h=d[c],y=f?f.children:void 0;if(a(h,y?y.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=i[s][0],h=i[s][1];let y=0;const x=c.children.indexOf(u);let b=!1,_=[];f.lastIndex=0;let T=f.exec(u.value);for(;T;){const L=T.index,z={index:T.index,input:T.input,stack:[...d,u]};let I=h(...T,z);if(typeof I=="string"&&(I=I.length>0?{type:"text",value:I}:void 0),I===!1?f.lastIndex=L+1:(y!==L&&_.push({type:"text",value:u.value.slice(y,L)}),Array.isArray(I)?_.push(...I):I&&_.push(I),y=L+T[0].length,b=!0),!f.global)break;T=f.exec(u.value)}return b?(y<u.value.length&&_.push({type:"text",value:u.value.slice(y)}),c.children.splice(x,1,..._)):_=[u],x+_.length}}function Fb(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([Bb(a[0]),zb(a[1])])}return t}function Bb(e){return typeof e=="string"?new RegExp(Db(e),"g"):e}function zb(e){return typeof e=="function"?e:function(){return e}}const Ha="phrasing",qa=["autolink","link","image","label"];function Rb(){return{transforms:[Wb],enter:{literalAutolink:$b,literalAutolinkEmail:Va,literalAutolinkHttp:Va,literalAutolinkWww:Va},exit:{literalAutolink:Vb,literalAutolinkEmail:qb,literalAutolinkHttp:Ub,literalAutolinkWww:Hb}}}function jb(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Ha,notInConstruct:qa},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Ha,notInConstruct:qa},{character:":",before:"[ps]",after:"\\/",inConstruct:Ha,notInConstruct:qa}]}}function $b(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Va(e){this.config.enter.autolinkProtocol.call(this,e)}function Ub(e){this.config.exit.autolinkProtocol.call(this,e)}function Hb(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 qb(e){this.config.exit.autolinkEmail.call(this,e)}function Vb(e){this.exit(e)}function Wb(e){Ob(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,Jb],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),Kb]],{ignore:["link","linkReference"]})}function Jb(e,t,r,n,a){let i="";if(!Fl(a)||(/^w/i.test(t)&&(r=t+r,t="",i="http://"),!Gb(r)))return!1;const s=Yb(r+n);if(!s[0])return!1;const o={type:"link",title:null,url:i+t+s[0],children:[{type:"text",value:t+s[0]}]};return s[1]?[o,{type:"text",value:s[1]}]:o}function Kb(e,t,r,n){return!Fl(n,!0)||/[-\d_]$/.test(r)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+r,children:[{type:"text",value:t+"@"+r}]}}function Gb(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 Yb(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=Ol(e,"(");let i=Ol(e,")");for(;n!==-1&&a>i;)e+=r.slice(0,n+1),r=r.slice(n+1),n=r.indexOf(")"),i++;return[e,r]}function Fl(e,t){const r=e.input.charCodeAt(e.index-1);return(e.index===0||Et(r)||en(r))&&(!t||r!==47)}Bl.peek=iw;function Xb(){this.buffer()}function Qb(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function Zb(){this.buffer()}function ew(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function tw(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=Ge(this.sliceSerialize(e)).toLowerCase(),r.label=t}function rw(e){this.exit(e)}function nw(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=Ge(this.sliceSerialize(e)).toLowerCase(),r.label=t}function aw(e){this.exit(e)}function iw(){return"["}function Bl(e,t,r,n){const a=r.createTracker(n);let i=a.move("[^");const s=r.enter("footnoteReference"),o=r.enter("reference");return i+=a.move(r.safe(r.associationId(e),{after:"]",before:i})),o(),s(),i+=a.move("]"),i}function sw(){return{enter:{gfmFootnoteCallString:Xb,gfmFootnoteCall:Qb,gfmFootnoteDefinitionLabelString:Zb,gfmFootnoteDefinition:ew},exit:{gfmFootnoteCallString:tw,gfmFootnoteCall:rw,gfmFootnoteDefinitionLabelString:nw,gfmFootnoteDefinition:aw}}}function ow(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:r,footnoteReference:Bl},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function r(n,a,i,s){const o=i.createTracker(s);let l=o.move("[^");const u=i.enter("footnoteDefinition"),d=i.enter("label");return l+=o.move(i.safe(i.associationId(n),{before:l,after:"]"})),d(),l+=o.move("]:"),n.children&&n.children.length>0&&(o.shift(4),l+=o.move((t?`
21
- `:" ")+i.indentLines(i.containerFlow(n,o.current()),t?zl:lw))),u(),l}}function lw(e,t,r){return t===0?e:zl(e,t,r)}function zl(e,t,r){return(r?"":" ")+e}const uw=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Rl.peek=pw;function cw(){return{canContainEols:["delete"],enter:{strikethrough:hw},exit:{strikethrough:fw}}}function dw(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:uw}],handlers:{delete:Rl}}}function hw(e){this.enter({type:"delete",children:[]},e)}function fw(e){this.exit(e)}function Rl(e,t,r,n){const a=r.createTracker(n),i=r.enter("strikethrough");let s=a.move("~~");return s+=r.containerPhrasing(e,E(m({},a.current()),{before:s,after:"~"})),s+=a.move("~~"),i(),s}function pw(){return"~"}function mw(e){return e.length}function gw(e,t){const r=t||{},n=(r.align||[]).concat(),a=r.stringLength||mw,i=[],s=[],o=[],l=[];let u=0,d=-1;for(;++d<e.length;){const S=[],x=[];let b=-1;for(e[d].length>u&&(u=e[d].length);++b<e[d].length;){const _=yw(e[d][b]);if(r.alignDelimiters!==!1){const T=a(_);x[b]=T,(l[b]===void 0||T>l[b])&&(l[b]=T)}S.push(_)}s[d]=S,o[d]=x}let c=-1;if(typeof n=="object"&&"length"in n)for(;++c<u;)i[c]=jl(n[c]);else{const S=jl(n);for(;++c<u;)i[c]=S}c=-1;const f=[],h=[];for(;++c<u;){const S=i[c];let x="",b="";S===99?(x=":",b=":"):S===108?x=":":S===114&&(b=":");let _=r.alignDelimiters===!1?1:Math.max(1,l[c]-x.length-b.length);const T=x+"-".repeat(_)+b;r.alignDelimiters!==!1&&(_=x.length+_+b.length,_>l[c]&&(l[c]=_),h[c]=_),f[c]=T}s.splice(1,0,f),o.splice(1,0,h),d=-1;const y=[];for(;++d<s.length;){const S=s[d],x=o[d];c=-1;const b=[];for(;++c<u;){const _=S[c]||"";let T="",L="";if(r.alignDelimiters!==!1){const z=l[c]-(x[c]||0),I=i[c];I===114?T=" ".repeat(z):I===99?z%2?(T=" ".repeat(z/2+.5),L=" ".repeat(z/2-.5)):(T=" ".repeat(z/2),L=T):L=" ".repeat(z)}r.delimiterStart!==!1&&!c&&b.push("|"),r.padding!==!1&&!(r.alignDelimiters===!1&&_==="")&&(r.delimiterStart!==!1||c)&&b.push(" "),r.alignDelimiters!==!1&&b.push(T),b.push(_),r.alignDelimiters!==!1&&b.push(L),r.padding!==!1&&b.push(" "),(r.delimiterEnd!==!1||c!==u-1)&&b.push("|")}y.push(r.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return y.join(`
22
- `)}function yw(e){return e==null?"":String(e)}function jl(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 bw(e,t,r,n){const a=r.enter("blockquote"),i=r.createTracker(n);i.move("> "),i.shift(2);const s=r.indentLines(r.containerFlow(e,i.current()),ww);return a(),s}function ww(e,t,r){return">"+(r?"":" ")+e}function xw(e,t){return $l(e,t.inConstruct,!0)&&!$l(e,t.notInConstruct,!1)}function $l(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 Ul(e,t,r,n){let a=-1;for(;++a<r.unsafe.length;)if(r.unsafe[a].character===`
23
- `&&xw(r.stack,r.unsafe[a]))return/[ \t]/.test(n.before)?"":" ";return`\\
24
- `}function vw(e,t){const r=String(e);let n=r.indexOf(t),a=n,i=0,s=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;n!==-1;)n===a?++i>s&&(s=i):i=1,a=n+t.length,n=r.indexOf(t,a);return s}function Sw(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 kw(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 _w(e,t,r,n){const a=kw(r),i=e.value||"",s=a==="`"?"GraveAccent":"Tilde";if(Sw(e,r)){const c=r.enter("codeIndented"),f=r.indentLines(i,Tw);return c(),f}const o=r.createTracker(n),l=a.repeat(Math.max(vw(i,a)+1,3)),u=r.enter("codeFenced");let d=o.move(l);if(e.lang){const c=r.enter(`codeFencedLang${s}`);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${s}`);d+=o.move(" "),d+=o.move(r.safe(e.meta,m({before:d,after:`
25
- `,encode:["`"]},o.current()))),c()}return d+=o.move(`
26
- `),i&&(d+=o.move(i+`
27
- `)),d+=o.move(l),u(),d}function Tw(e,t,r){return(r?"":" ")+e}function Wa(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 Cw(e,t,r,n){const a=Wa(r),i=a==='"'?"Quote":"Apostrophe",s=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${i}`),u+=l.move(" "+a),u+=l.move(r.safe(e.title,m({before:u,after:a},l.current()))),u+=l.move(a),o()),s(),u}function Iw(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 Sr(e){return"&#x"+e.toString(16).toUpperCase()+";"}function hn(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}}Hl.peek=Ew;function Hl(e,t,r,n){const a=Iw(r),i=r.enter("emphasis"),s=r.createTracker(n),o=s.move(a);let l=s.move(r.containerPhrasing(e,m({after:a,before:o},s.current())));const u=l.charCodeAt(0),d=hn(n.before.charCodeAt(n.before.length-1),u,a);d.inside&&(l=Sr(u)+l.slice(1));const c=l.charCodeAt(l.length-1),f=hn(n.after.charCodeAt(0),c,a);f.inside&&(l=l.slice(0,-1)+Sr(c));const h=s.move(a);return i(),r.attentionEncodeSurroundingInfo={after:f.outside,before:d.outside},o+l+h}function Ew(e,t,r){return r.options.emphasis||"*"}function Aw(e,t){let r=!1;return Ca(e,function(n){if("value"in n&&/\r?\n|\r/.test(n.value)||n.type==="break")return r=!0,Ta}),!!((!e.depth||e.depth<3)&&pa(e)&&(t.options.setext||r))}function Pw(e,t,r,n){const a=Math.max(Math.min(6,e.depth||1),1),i=r.createTracker(n);if(Aw(e,r)){const d=r.enter("headingSetext"),c=r.enter("phrasing"),f=r.containerPhrasing(e,E(m({},i.current()),{before:`
19
+ `}),r}function kl(e){let t=0,r=e.charCodeAt(t);for(;r===9||r===32;)t++,r=e.charCodeAt(t);return e.slice(t)}function Sl(e,t){const r=zy(e,t),n=r.one(e,void 0),a=Ey(r),i=Array.isArray(n)?{type:"root",children:n}:n||{type:"root",children:[]};return a&&i.children.push({type:"text",value:`
20
+ `},a),i}function Hy(e,t){return e&&"run"in e?function(r,n){return P(this,null,function*(){const a=Sl(r,m({file:n},t));yield e.run(a,n)})}:function(r,n){return Sl(r,m({file:n},e||t))}}function _l(e){if(e)throw e}var Aa,Tl;function qy(){if(Tl)return Aa;Tl=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]"},i=function(u){if(!u||t.call(u)!=="[object Object]")return!1;var c=e.call(u,"constructor"),d=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!c&&!d)return!1;var f;for(f in u);return typeof f=="undefined"||e.call(u,f)},s=function(u,c){r&&c.name==="__proto__"?r(u,c.name,{enumerable:!0,configurable:!0,value:c.newValue,writable:!0}):u[c.name]=c.newValue},o=function(u,c){if(c==="__proto__")if(e.call(u,c)){if(n)return n(u,c).value}else return;return u[c]};return Aa=function l(){var u,c,d,f,h,g,k=arguments[0],w=1,b=arguments.length,I=!1;for(typeof k=="boolean"&&(I=k,k=arguments[1]||{},w=2),(k==null||typeof k!="object"&&typeof k!="function")&&(k={});w<b;++w)if(u=arguments[w],u!=null)for(c in u)d=o(k,c),f=o(u,c),k!==f&&(I&&f&&(i(f)||(h=a(f)))?(h?(h=!1,g=d&&a(d)?d:[]):g=d&&i(d)?d:{},s(k,{name:c,newValue:l(I,g,f)})):typeof f!="undefined"&&s(k,{name:c,newValue:f}));return k},Aa}var Vy=qy();const Ma=Pr(Vy);function Pa(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 Wy(){const e=[],t={run:r,use:n};return t;function r(...a){let i=-1;const s=a.pop();if(typeof s!="function")throw new TypeError("Expected function as last argument, not "+s);o(null,...a);function o(l,...u){const c=e[++i];let d=-1;if(l){s(l);return}for(;++d<a.length;)(u[d]===null||u[d]===void 0)&&(u[d]=a[d]);a=u,c?Jy(c,o)(...u):s(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 Jy(e,t){let r;return n;function n(...s){const o=e.length>s.length;let l;o&&s.push(a);try{l=e.apply(this,s)}catch(u){const c=u;if(o&&r)throw c;return a(c)}o||(l&&l.then&&typeof l.then=="function"?l.then(i,a):l instanceof Error?a(l):i(l))}function a(s,...o){r||(r=!0,t(s,...o))}function i(s){a(null,s)}}const st={basename:Ky,dirname:Yy,extname:Gy,join:Xy,sep:"/"};function Ky(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');kr(e);let r=0,n=-1,a=e.length,i;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(i){r=a+1;break}}else n<0&&(i=!0,n=a+1);return n<0?"":e.slice(r,n)}if(t===e)return"";let s=-1,o=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(i){r=a+1;break}}else s<0&&(i=!0,s=a+1),o>-1&&(e.codePointAt(a)===t.codePointAt(o--)?o<0&&(n=a):(o=-1,n=s));return r===n?n=s:n<0&&(n=e.length),e.slice(r,n)}function Yy(e){if(kr(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 Gy(e){kr(e);let t=e.length,r=-1,n=0,a=-1,i=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?a<0?a=t:i!==1&&(i=1):a>-1&&(i=-1)}return a<0||r<0||i===0||i===1&&a===r-1&&a===n+1?"":e.slice(a,r)}function Xy(...e){let t=-1,r;for(;++t<e.length;)kr(e[t]),e[t]&&(r=r===void 0?e[t]:r+"/"+e[t]);return r===void 0?".":Qy(r)}function Qy(e){kr(e);const t=e.codePointAt(0)===47;let r=Zy(e,!t);return r.length===0&&!t&&(r="."),r.length>0&&e.codePointAt(e.length-1)===47&&(r+="/"),t?"/"+r:r}function Zy(e,t){let r="",n=0,a=-1,i=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(!(a===s-1||i===1))if(a!==s-1&&i===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=s,i=0;continue}}else if(r.length>0){r="",n=0,a=s,i=0;continue}}t&&(r=r.length>0?r+"/..":"..",n=2)}else r.length>0?r+="/"+e.slice(a+1,s):r=e.slice(a+1,s),n=s-a-1;a=s,i=0}else o===46&&i>-1?i++:i=-1}return r}function kr(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const eb={cwd:tb};function tb(){return"/"}function Na(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function rb(e){if(typeof e=="string")e=new URL(e);else if(!Na(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 nb(e)}function nb(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 La=["history","path","basename","stem","extname","dirname"];class Cl{constructor(t){let r;t?Na(t)?r={path:t}:typeof t=="string"||ab(t)?r={value:t}:r=t:r={},this.cwd="cwd"in r?"":eb.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let n=-1;for(;++n<La.length;){const i=La[n];i in r&&r[i]!==void 0&&r[i]!==null&&(this[i]=i==="history"?[...r[i]]:r[i])}let a;for(a in r)La.includes(a)||(this[a]=r[a])}get basename(){return typeof this.path=="string"?st.basename(this.path):void 0}set basename(t){Oa(t,"basename"),Da(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){Il(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(Da(t,"extname"),Il(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){Na(t)&&(t=rb(t)),Oa(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){Oa(t,"stem"),Da(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 Ee(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 Da(e,t){if(e&&e.includes(st.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+st.sep+"`")}function Oa(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function Il(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function ab(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const ib=(function(e){const n=this.constructor.prototype,a=n[e],i=function(){return a.apply(i,arguments)};return Object.setPrototypeOf(i,n),i}),sb={}.hasOwnProperty;class Fa extends ib{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=Wy()}copy(){const t=new Fa;let r=-1;for(;++r<this.attachers.length;){const n=this.attachers[r];t.use(...n)}return t.data(Ma(!0,{},this.namespace)),t}data(t,r){return typeof t=="string"?arguments.length===2?(Ra("data",this.frozen),this.namespace[t]=r,this):sb.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Ra("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=fn(t),n=this.parser||this.Parser;return Ba("parse",n),n(String(r),r)}process(t,r){const n=this;return this.freeze(),Ba("process",this.parser||this.Parser),za("process",this.compiler||this.Compiler),r?a(void 0,r):new Promise(a);function a(i,s){const o=fn(t),l=n.parse(o);n.run(l,o,function(c,d,f){if(c||!d||!f)return u(c);const h=d,g=n.stringify(h,f);ub(g)?f.value=g:f.result=g,u(c,f)});function u(c,d){c||!d?s(c):i?i(d):r(void 0,d)}}}processSync(t){let r=!1,n;return this.freeze(),Ba("processSync",this.parser||this.Parser),za("processSync",this.compiler||this.Compiler),this.process(t,a),Al("processSync","process",r),n;function a(i,s){r=!0,_l(i),n=s}}run(t,r,n){El(t),this.freeze();const a=this.transformers;return!n&&typeof r=="function"&&(n=r,r=void 0),n?i(void 0,n):new Promise(i);function i(s,o){const l=fn(r);a.run(t,l,u);function u(c,d,f){const h=d||t;c?o(c):s?s(h):n(void 0,h,f)}}}runSync(t,r){let n=!1,a;return this.run(t,r,i),Al("runSync","run",n),a;function i(s,o){_l(s),a=o,n=!0}}stringify(t,r){this.freeze();const n=fn(r),a=this.compiler||this.Compiler;return za("stringify",a),El(t),a(t,n)}use(t,...r){const n=this.attachers,a=this.namespace;if(Ra("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 i(u){if(typeof u=="function")l(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[c,...d]=u;l(c,d)}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&&(a.settings=Ma(!0,a.settings,u.settings))}function o(u){let c=-1;if(u!=null)if(Array.isArray(u))for(;++c<u.length;){const d=u[c];i(d)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function l(u,c){let d=-1,f=-1;for(;++d<n.length;)if(n[d][0]===u){f=d;break}if(f===-1)n.push([u,...c]);else if(c.length>0){let[h,...g]=c;const k=n[f][1];Pa(k)&&Pa(h)&&(h=Ma(!0,k,h)),n[f]=[u,h,...g]}}}}const ob=new Fa().freeze();function Ba(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function za(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Ra(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 El(e){if(!Pa(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Al(e,t,r){if(!r)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function fn(e){return lb(e)?e:new Cl(e)}function lb(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function ub(e){return typeof e=="string"||cb(e)}function cb(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const db="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Ml=[],Pl={allowDangerousHtml:!0},hb=/^(https?|ircs?|mailto|xmpp)$/i,fb=[{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 pb(e){const t=mb(e),r=gb(e);return yb(t.runSync(t.parse(r),r),e)}function mb(e){const t=e.rehypePlugins||Ml,r=e.remarkPlugins||Ml,n=e.remarkRehypeOptions?m(m({},e.remarkRehypeOptions),Pl):Pl;return ob().use(Yg).use(r).use(Hy,n).use(t)}function gb(e){const t=e.children||"",r=new Cl;return typeof t=="string"&&(r.value=t),r}function yb(e,t){const r=t.allowedElements,n=t.allowElement,a=t.components,i=t.disallowedElements,s=t.skipHtml,o=t.unwrapDisallowed,l=t.urlTransform||bb;for(const c of fb)Object.hasOwn(t,c.from)&&(""+c.from+(c.to?"use `"+c.to+"` instead":"remove it")+db+c.id,void 0);return Ia(e,u),$p(e,{Fragment:p.Fragment,components:a,ignoreInvalidStyle:!0,jsx:p.jsx,jsxs:p.jsxs,passKeys:!0,passNode:!0});function u(c,d,f){if(c.type==="raw"&&f&&typeof d=="number")return s?f.children.splice(d,1):f.children[d]={type:"text",value:c.value},d;if(c.type==="element"){let h;for(h in pa)if(Object.hasOwn(pa,h)&&Object.hasOwn(c.properties,h)){const g=c.properties[h],k=pa[h];(k===null||k.includes(c.tagName))&&(c.properties[h]=l(String(g||""),h,c))}}if(c.type==="element"){let h=r?!r.includes(c.tagName):i?i.includes(c.tagName):!1;if(!h&&n&&typeof d=="number"&&(h=!n(c,d,f)),h&&f&&typeof d=="number")return o&&c.children?f.children.splice(d,1,...c.children):f.children.splice(d,1),d}}}function bb(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||hb.test(e.slice(0,t))?e:""}var wb=(e,t)=>typeof e=="string"?e===t:JSON.stringify(e)===JSON.stringify(t),xb=(e,t)=>{if(!e||!t)return!1;const r=n=>{const o=n||{},{position:a,data:i}=o;return V(o,["position","data"])};return JSON.stringify(r(e.properties))===JSON.stringify(r(t.properties))&&wb(e.children,t.children)},ja=(e,t)=>xb(e.node,t.node),vb=(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:i}=l,s=V(l,["node"]);return p.jsx(n,m({},s))};return[t,y.memo(a,ja)]})),$a=y.createContext(null),Nl=()=>y.useContext($a)!==null,kb=r=>{var n=r,{children:e}=n,t=V(n,["children"]);return p.jsx($a.Provider,{value:t,children:e})},Sb=y.memo(kb,ja),_b=r=>{var n=r,{node:e}=n,t=V(n,["node"]);return p.jsx("pre",m({},t))},Tb=r=>{var n=r,{node:e}=n,t=V(n,["node"]);return p.jsx("code",m({},t))},Ua=({node:e,components:{Pre:t,Code:r},code:n})=>p.jsx(t,{children:p.jsx(r,{node:e,children:n})}),Cb=()=>null,Ib=({node:e,components:{Pre:t,Code:r,SyntaxHighlighter:n,CodeHeader:a},language:i,code:s})=>{const o=y.useMemo(()=>({Pre:t,Code:r}),[t,r]),l=i?n:Ua;return p.jsxs(p.Fragment,{children:[p.jsx(a,{node:e,language:i,code:s}),p.jsx(l,{node:e,components:o,language:i!=null?i:"unknown",code:s})]})},Ha={exports:{}};var Ll;function Eb(){return Ll||(Ll=1,(function(e){(function(){var t={}.hasOwnProperty;function r(){for(var i="",s=0;s<arguments.length;s++){var o=arguments[s];o&&(i=a(i,n(o)))}return i}function n(i){if(typeof i=="string"||typeof i=="number")return i;if(typeof i!="object")return"";if(Array.isArray(i))return r.apply(null,i);if(i.toString!==Object.prototype.toString&&!i.toString.toString().includes("[native code]"))return i.toString();var s="";for(var o in i)t.call(i,o)&&i[o]&&(s=a(s,o));return s}function a(i,s){return s?i?i+" "+s:i+s:i}e.exports?(r.default=r,e.exports=r):window.classNames=r})()})(Ha)),Ha.exports}var Ab=Eb();const Dl=Pr(Ab);var Ol=r=>{var n=r,{className:e}=n,t=V(n,["className"]);return s=>{var o=s,{className:a}=o,i=V(o,["className"]);return m(m({className:Dl(e,a)},t),i)}},Mb=l=>{var u=l,{node:e,components:{Pre:t,Code:r,SyntaxHighlighter:n,CodeHeader:a},componentsByLanguage:i={},children:s}=u,o=V(u,["node","components","componentsByLanguage","children"]);var I,T,B,F,_,$;const c=y.useContext($a),d=Ol(c),f=Tt(R=>p.jsx(t,m({},d(R)))),h=Ol(o),g=Tt(R=>p.jsx(r,m({},h(R)))),k=(T=(I=/language-(\w+)/.exec(o.className||""))==null?void 0:I[1])!=null?T:"";if(typeof s!="string")return p.jsx(Ua,{node:e,components:{Pre:f,Code:g},code:s});const w=(F=(B=i[k])==null?void 0:B.SyntaxHighlighter)!=null?F:n,b=($=(_=i[k])==null?void 0:_.CodeHeader)!=null?$:a;return p.jsx(Ib,{node:e,components:{Pre:f,Code:g,SyntaxHighlighter:w,CodeHeader:b},language:k||"unknown",code:s})},Pb=a=>{var i=a,{node:e,components:t,componentsByLanguage:r}=i,n=V(i,["node","components","componentsByLanguage"]);return Nl()?p.jsx(Mb,m({node:e,components:t,componentsByLanguage:r},n)):p.jsx(t.Code,m({},n))},Nb=y.memo(Pb,(e,t)=>e.components===t.components&&e.componentsByLanguage===t.componentsByLanguage&&ja(e,t)),{useSmooth:Lb,useSmoothStatus:Db,withSmoothContextProvider:Ob}=qh,Fb=i=>{var s=i,{components:e,componentsByLanguage:t,smooth:r=!0,preprocess:n}=s,a=V(s,["components","componentsByLanguage","smooth","preprocess"]);const o=Ms(),l=y.useMemo(()=>n?E(m({},o),{text:n(o.text)}):o,[o,n]),{text:u}=Lb(l,r),{pre:c=_b,code:d=Tb,SyntaxHighlighter:f=Ua,CodeHeader:h=Cb}=e!=null?e:{},g=y.useMemo(()=>({Pre:c,Code:d,SyntaxHighlighter:f,CodeHeader:h}),[c,d,f,h]),k=Tt(b=>p.jsx(Nb,m({components:g,componentsByLanguage:t},b))),w=y.useMemo(()=>{const _=e!=null?e:{},{pre:b,code:I,SyntaxHighlighter:T,CodeHeader:B}=_,F=V(_,["pre","code","SyntaxHighlighter","CodeHeader"]);return E(m({},F),{pre:Sb,code:k})},[k,e]);return p.jsx(pb,E(m({components:w},a),{children:u}))},Fl=y.forwardRef((i,a)=>{var s=i,{className:e,containerProps:t,containerComponent:r="div"}=s,n=V(s,["className","containerProps","containerComponent"]);const o=Db();return p.jsx(r,E(m({"data-status":o.type},t),{className:Dl(e,t==null?void 0:t.className),ref:a,children:p.jsx(Fb,m({},n))}))});Fl.displayName="MarkdownTextPrimitive";var Bb=Ob(Fl);function Bl(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 zb(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Rb(e,t,r){const a=dn((r||{}).ignore||[]),i=jb(t);let s=-1;for(;++s<i.length;)vl(e,"text",o);function o(u,c){let d=-1,f;for(;++d<c.length;){const h=c[d],g=f?f.children:void 0;if(a(h,g?g.indexOf(h):void 0,f))return;f=h}if(f)return l(u,c)}function l(u,c){const d=c[c.length-1],f=i[s][0],h=i[s][1];let g=0;const w=d.children.indexOf(u);let b=!1,I=[];f.lastIndex=0;let T=f.exec(u.value);for(;T;){const B=T.index,F={index:T.index,input:T.input,stack:[...c,u]};let _=h(...T,F);if(typeof _=="string"&&(_=_.length>0?{type:"text",value:_}:void 0),_===!1?f.lastIndex=B+1:(g!==B&&I.push({type:"text",value:u.value.slice(g,B)}),Array.isArray(_)?I.push(..._):_&&I.push(_),g=B+T[0].length,b=!0),!f.global)break;T=f.exec(u.value)}return b?(g<u.value.length&&I.push({type:"text",value:u.value.slice(g)}),d.children.splice(w,1,...I)):I=[u],w+I.length}}function jb(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([$b(a[0]),Ub(a[1])])}return t}function $b(e){return typeof e=="string"?new RegExp(zb(e),"g"):e}function Ub(e){return typeof e=="function"?e:function(){return e}}const qa="phrasing",Va=["autolink","link","image","label"];function Hb(){return{transforms:[Gb],enter:{literalAutolink:Vb,literalAutolinkEmail:Wa,literalAutolinkHttp:Wa,literalAutolinkWww:Wa},exit:{literalAutolink:Yb,literalAutolinkEmail:Kb,literalAutolinkHttp:Wb,literalAutolinkWww:Jb}}}function qb(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:qa,notInConstruct:Va},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:qa,notInConstruct:Va},{character:":",before:"[ps]",after:"\\/",inConstruct:qa,notInConstruct:Va}]}}function Vb(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Wa(e){this.config.enter.autolinkProtocol.call(this,e)}function Wb(e){this.config.exit.autolinkProtocol.call(this,e)}function Jb(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 Kb(e){this.config.exit.autolinkEmail.call(this,e)}function Yb(e){this.exit(e)}function Gb(e){Rb(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,Xb],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),Qb]],{ignore:["link","linkReference"]})}function Xb(e,t,r,n,a){let i="";if(!zl(a)||(/^w/i.test(t)&&(r=t+r,t="",i="http://"),!Zb(r)))return!1;const s=ew(r+n);if(!s[0])return!1;const o={type:"link",title:null,url:i+t+s[0],children:[{type:"text",value:t+s[0]}]};return s[1]?[o,{type:"text",value:s[1]}]:o}function Qb(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 Zb(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 ew(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=Bl(e,"(");let i=Bl(e,")");for(;n!==-1&&a>i;)e+=r.slice(0,n+1),r=r.slice(n+1),n=r.indexOf(")"),i++;return[e,r]}function zl(e,t){const r=e.input.charCodeAt(e.index-1);return(e.index===0||Et(r)||rn(r))&&(!t||r!==47)}Rl.peek=uw;function tw(){this.buffer()}function rw(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function nw(){this.buffer()}function aw(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function iw(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=tt(this.sliceSerialize(e)).toLowerCase(),r.label=t}function sw(e){this.exit(e)}function ow(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=tt(this.sliceSerialize(e)).toLowerCase(),r.label=t}function lw(e){this.exit(e)}function uw(){return"["}function Rl(e,t,r,n){const a=r.createTracker(n);let i=a.move("[^");const s=r.enter("footnoteReference"),o=r.enter("reference");return i+=a.move(r.safe(r.associationId(e),{after:"]",before:i})),o(),s(),i+=a.move("]"),i}function cw(){return{enter:{gfmFootnoteCallString:tw,gfmFootnoteCall:rw,gfmFootnoteDefinitionLabelString:nw,gfmFootnoteDefinition:aw},exit:{gfmFootnoteCallString:iw,gfmFootnoteCall:sw,gfmFootnoteDefinitionLabelString:ow,gfmFootnoteDefinition:lw}}}function dw(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:r,footnoteReference:Rl},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function r(n,a,i,s){const o=i.createTracker(s);let l=o.move("[^");const u=i.enter("footnoteDefinition"),c=i.enter("label");return l+=o.move(i.safe(i.associationId(n),{before:l,after:"]"})),c(),l+=o.move("]:"),n.children&&n.children.length>0&&(o.shift(4),l+=o.move((t?`
21
+ `:" ")+i.indentLines(i.containerFlow(n,o.current()),t?jl:hw))),u(),l}}function hw(e,t,r){return t===0?e:jl(e,t,r)}function jl(e,t,r){return(r?"":" ")+e}const fw=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];$l.peek=bw;function pw(){return{canContainEols:["delete"],enter:{strikethrough:gw},exit:{strikethrough:yw}}}function mw(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:fw}],handlers:{delete:$l}}}function gw(e){this.enter({type:"delete",children:[]},e)}function yw(e){this.exit(e)}function $l(e,t,r,n){const a=r.createTracker(n),i=r.enter("strikethrough");let s=a.move("~~");return s+=r.containerPhrasing(e,E(m({},a.current()),{before:s,after:"~"})),s+=a.move("~~"),i(),s}function bw(){return"~"}function ww(e){return e.length}function xw(e,t){const r=t||{},n=(r.align||[]).concat(),a=r.stringLength||ww,i=[],s=[],o=[],l=[];let u=0,c=-1;for(;++c<e.length;){const k=[],w=[];let b=-1;for(e[c].length>u&&(u=e[c].length);++b<e[c].length;){const I=vw(e[c][b]);if(r.alignDelimiters!==!1){const T=a(I);w[b]=T,(l[b]===void 0||T>l[b])&&(l[b]=T)}k.push(I)}s[c]=k,o[c]=w}let d=-1;if(typeof n=="object"&&"length"in n)for(;++d<u;)i[d]=Ul(n[d]);else{const k=Ul(n);for(;++d<u;)i[d]=k}d=-1;const f=[],h=[];for(;++d<u;){const k=i[d];let w="",b="";k===99?(w=":",b=":"):k===108?w=":":k===114&&(b=":");let I=r.alignDelimiters===!1?1:Math.max(1,l[d]-w.length-b.length);const T=w+"-".repeat(I)+b;r.alignDelimiters!==!1&&(I=w.length+I+b.length,I>l[d]&&(l[d]=I),h[d]=I),f[d]=T}s.splice(1,0,f),o.splice(1,0,h),c=-1;const g=[];for(;++c<s.length;){const k=s[c],w=o[c];d=-1;const b=[];for(;++d<u;){const I=k[d]||"";let T="",B="";if(r.alignDelimiters!==!1){const F=l[d]-(w[d]||0),_=i[d];_===114?T=" ".repeat(F):_===99?F%2?(T=" ".repeat(F/2+.5),B=" ".repeat(F/2-.5)):(T=" ".repeat(F/2),B=T):B=" ".repeat(F)}r.delimiterStart!==!1&&!d&&b.push("|"),r.padding!==!1&&!(r.alignDelimiters===!1&&I==="")&&(r.delimiterStart!==!1||d)&&b.push(" "),r.alignDelimiters!==!1&&b.push(T),b.push(I),r.alignDelimiters!==!1&&b.push(B),r.padding!==!1&&b.push(" "),(r.delimiterEnd!==!1||d!==u-1)&&b.push("|")}g.push(r.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return g.join(`
22
+ `)}function vw(e){return e==null?"":String(e)}function Ul(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 kw(e,t,r,n){const a=r.enter("blockquote"),i=r.createTracker(n);i.move("> "),i.shift(2);const s=r.indentLines(r.containerFlow(e,i.current()),Sw);return a(),s}function Sw(e,t,r){return">"+(r?"":" ")+e}function _w(e,t){return Hl(e,t.inConstruct,!0)&&!Hl(e,t.notInConstruct,!1)}function Hl(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 ql(e,t,r,n){let a=-1;for(;++a<r.unsafe.length;)if(r.unsafe[a].character===`
23
+ `&&_w(r.stack,r.unsafe[a]))return/[ \t]/.test(n.before)?"":" ";return`\\
24
+ `}function Tw(e,t){const r=String(e);let n=r.indexOf(t),a=n,i=0,s=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;n!==-1;)n===a?++i>s&&(s=i):i=1,a=n+t.length,n=r.indexOf(t,a);return s}function Cw(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 Iw(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 Ew(e,t,r,n){const a=Iw(r),i=e.value||"",s=a==="`"?"GraveAccent":"Tilde";if(Cw(e,r)){const d=r.enter("codeIndented"),f=r.indentLines(i,Aw);return d(),f}const o=r.createTracker(n),l=a.repeat(Math.max(Tw(i,a)+1,3)),u=r.enter("codeFenced");let c=o.move(l);if(e.lang){const d=r.enter(`codeFencedLang${s}`);c+=o.move(r.safe(e.lang,m({before:c,after:" ",encode:["`"]},o.current()))),d()}if(e.lang&&e.meta){const d=r.enter(`codeFencedMeta${s}`);c+=o.move(" "),c+=o.move(r.safe(e.meta,m({before:c,after:`
25
+ `,encode:["`"]},o.current()))),d()}return c+=o.move(`
26
+ `),i&&(c+=o.move(i+`
27
+ `)),c+=o.move(l),u(),c}function Aw(e,t,r){return(r?"":" ")+e}function Ja(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 Mw(e,t,r,n){const a=Ja(r),i=a==='"'?"Quote":"Apostrophe",s=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${i}`),u+=l.move(" "+a),u+=l.move(r.safe(e.title,m({before:u,after:a},l.current()))),u+=l.move(a),o()),s(),u}function Pw(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 Sr(e){return"&#x"+e.toString(16).toUpperCase()+";"}function pn(e,t,r){const n=Vt(e),a=Vt(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}}Vl.peek=Nw;function Vl(e,t,r,n){const a=Pw(r),i=r.enter("emphasis"),s=r.createTracker(n),o=s.move(a);let l=s.move(r.containerPhrasing(e,m({after:a,before:o},s.current())));const u=l.charCodeAt(0),c=pn(n.before.charCodeAt(n.before.length-1),u,a);c.inside&&(l=Sr(u)+l.slice(1));const d=l.charCodeAt(l.length-1),f=pn(n.after.charCodeAt(0),d,a);f.inside&&(l=l.slice(0,-1)+Sr(d));const h=s.move(a);return i(),r.attentionEncodeSurroundingInfo={after:f.outside,before:c.outside},o+l+h}function Nw(e,t,r){return r.options.emphasis||"*"}function Lw(e,t){let r=!1;return Ia(e,function(n){if("value"in n&&/\r?\n|\r/.test(n.value)||n.type==="break")return r=!0,Ca}),!!((!e.depth||e.depth<3)&&ma(e)&&(t.options.setext||r))}function Dw(e,t,r,n){const a=Math.max(Math.min(6,e.depth||1),1),i=r.createTracker(n);if(Lw(e,r)){const c=r.enter("headingSetext"),d=r.enter("phrasing"),f=r.containerPhrasing(e,E(m({},i.current()),{before:`
29
29
  `,after:`
30
- `}));return c(),d(),f+`
30
+ `}));return d(),c(),f+`
31
31
  `+(a===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
32
32
  `))+1))}const s="#".repeat(a),o=r.enter("headingAtx"),l=r.enter("phrasing");i.move(s+" ");let u=r.containerPhrasing(e,m({before:"# ",after:`
33
- `},i.current()));return/^[\t ]/.test(u)&&(u=Sr(u.charCodeAt(0))+u.slice(1)),u=u?s+" "+u:s,r.options.closeAtx&&(u+=" "+s),l(),o(),u}ql.peek=Mw;function ql(e){return e.value||""}function Mw(){return"<"}Vl.peek=Nw;function Vl(e,t,r,n){const a=Wa(r),i=a==='"'?"Quote":"Apostrophe",s=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${i}`),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(")"),s(),u}function Nw(){return"!"}Wl.peek=Lw;function Wl(e,t,r,n){const a=e.referenceType,i=r.enter("imageReference");let s=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+"]["),s();const d=r.stack;r.stack=[],s=r.enter("reference");const c=r.safe(r.associationId(e),m({before:l,after:"]"},o.current()));return s(),r.stack=d,i(),a==="full"||!u||u!==c?l+=o.move(c+"]"):a==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function Lw(){return"!"}Jl.peek=Dw;function Jl(e,t,r){let n=e.value||"",a="`",i=-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+" ");++i<r.unsafe.length;){const s=r.unsafe[i],o=r.compilePattern(s);let l;if(s.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 Dw(){return"`"}function Kl(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))}Gl.peek=Ow;function Gl(e,t,r,n){const a=Wa(r),i=a==='"'?"Quote":"Apostrophe",s=r.createTracker(n);let o,l;if(Kl(e,r)){const d=r.stack;r.stack=[],o=r.enter("autolink");let c=s.move("<");return c+=s.move(r.containerPhrasing(e,m({before:c,after:">"},s.current()))),c+=s.move(">"),o(),r.stack=d,c}o=r.enter("link"),l=r.enter("label");let u=s.move("[");return u+=s.move(r.containerPhrasing(e,m({before:u,after:"]("},s.current()))),u+=s.move("]("),l(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(l=r.enter("destinationLiteral"),u+=s.move("<"),u+=s.move(r.safe(e.url,m({before:u,after:">"},s.current()))),u+=s.move(">")):(l=r.enter("destinationRaw"),u+=s.move(r.safe(e.url,m({before:u,after:e.title?" ":")"},s.current())))),l(),e.title&&(l=r.enter(`title${i}`),u+=s.move(" "+a),u+=s.move(r.safe(e.title,m({before:u,after:a},s.current()))),u+=s.move(a),l()),u+=s.move(")"),o(),u}function Ow(e,t,r){return Kl(e,r)?"<":"["}Yl.peek=Fw;function Yl(e,t,r,n){const a=e.referenceType,i=r.enter("linkReference");let s=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+"]["),s();const d=r.stack;r.stack=[],s=r.enter("reference");const c=r.safe(r.associationId(e),m({before:l,after:"]"},o.current()));return s(),r.stack=d,i(),a==="full"||!u||u!==c?l+=o.move(c+"]"):a==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function Fw(){return"["}function Ja(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 Bw(e){const t=Ja(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 zw(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 Xl(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"),i=r.bulletCurrent;let s=e.ordered?zw(r):Ja(r);const o=e.ordered?s==="."?")":".":Bw(r);let l=t&&r.bulletLastUsed?s===r.bulletLastUsed:!1;if(!e.ordered){const d=e.children?e.children[0]:void 0;if((s==="*"||s==="-")&&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),Xl(r)===s&&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&&(s=o),r.bulletCurrent=s;const u=r.containerFlow(e,n);return r.bulletLastUsed=s,r.bulletCurrent=i,a(),u}function jw(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 $w(e,t,r,n){const a=jw(r);let i=r.bulletCurrent||Ja(r);t&&t.type==="list"&&t.ordered&&(i=(typeof t.start=="number"&&t.start>-1?t.start:1)+(r.options.incrementListMarker===!1?0:t.children.indexOf(e))+i);let s=i.length+1;(a==="tab"||a==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(s=Math.ceil(s/4)*4);const o=r.createTracker(n);o.move(i+" ".repeat(s-i.length)),o.shift(s);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(s))+c:(h?i:i+" ".repeat(s-i.length))+c}}function Uw(e,t,r,n){const a=r.enter("paragraph"),i=r.enter("phrasing"),s=r.containerPhrasing(e,n);return i(),a(),s}const Hw=un(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function qw(e,t,r,n){return(e.children.some(function(s){return Hw(s)})?r.containerPhrasing:r.containerFlow).call(r,e,n)}function Vw(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}Ql.peek=Ww;function Ql(e,t,r,n){const a=Vw(r),i=r.enter("strong"),s=r.createTracker(n),o=s.move(a+a);let l=s.move(r.containerPhrasing(e,m({after:a,before:o},s.current())));const u=l.charCodeAt(0),d=hn(n.before.charCodeAt(n.before.length-1),u,a);d.inside&&(l=Sr(u)+l.slice(1));const c=l.charCodeAt(l.length-1),f=hn(n.after.charCodeAt(0),c,a);f.inside&&(l=l.slice(0,-1)+Sr(c));const h=s.move(a+a);return i(),r.attentionEncodeSurroundingInfo={after:f.outside,before:d.outside},o+l+h}function Ww(e,t,r){return r.options.strong||"*"}function Jw(e,t,r,n){return r.safe(e.value,n)}function Kw(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 Gw(e,t,r){const n=(Xl(r)+(r.options.ruleSpaces?" ":"")).repeat(Kw(r));return r.options.ruleSpaces?n.slice(0,-1):n}const Zl={blockquote:bw,break:Ul,code:_w,definition:Cw,emphasis:Hl,hardBreak:Ul,heading:Pw,html:ql,image:Vl,imageReference:Wl,inlineCode:Jl,link:Gl,linkReference:Yl,list:Rw,listItem:$w,paragraph:Uw,root:qw,strong:Ql,text:Jw,thematicBreak:Gw};function Yw(){return{enter:{table:Xw,tableData:eu,tableHeader:eu,tableRow:Zw},exit:{codeText:ex,table:Qw,tableData:Ka,tableHeader:Ka,tableRow:Ka}}}function Xw(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 Qw(e){this.exit(e),this.data.inTable=void 0}function Zw(e){this.enter({type:"tableRow",children:[]},e)}function Ka(e){this.exit(e)}function eu(e){this.enter({type:"tableCell",children:[]},e)}function ex(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,tx));const r=this.stack[this.stack.length-1];r.type,r.value=t,this.exit(e)}function tx(e,t){return t==="|"?t:e}function rx(e){const t=e||{},r=t.tableCellPadding,n=t.tablePipeAlign,a=t.stringLength,i=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:s,tableCell:l,tableRow:o}};function s(h,y,S,x){return u(d(h,S,x),h.align)}function o(h,y,S,x){const b=c(h,S,x),_=u([b]);return _.slice(0,_.indexOf(`
35
- `))}function l(h,y,S,x){const b=S.enter("tableCell"),_=S.enter("phrasing"),T=S.containerPhrasing(h,E(m({},x),{before:i,after:i}));return _(),b(),T}function u(h,y){return gw(h,{align:y,alignDelimiters:n,padding:r,stringLength:a})}function d(h,y,S){const x=h.children;let b=-1;const _=[],T=y.enter("table");for(;++b<x.length;)_[b]=c(x[b],y,S);return T(),_}function c(h,y,S){const x=h.children;let b=-1;const _=[],T=y.enter("tableRow");for(;++b<x.length;)_[b]=l(x[b],h,y,S);return T(),_}function f(h,y,S){let x=Zl.inlineCode(h,y,S);return S.stack.includes("tableCell")&&(x=x.replace(/\|/g,"\\$&")),x}}function nx(){return{exit:{taskListCheckValueChecked:tu,taskListCheckValueUnchecked:tu,paragraph:ix}}}function ax(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:sx}}}function tu(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function ix(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 i=-1,s;for(;++i<a.length;){const o=a[i];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 sx(e,t,r,n){const a=e.children[0],i=typeof e.checked=="boolean"&&a&&a.type==="paragraph",s="["+(e.checked?"x":" ")+"] ",o=r.createTracker(n);i&&o.move(s);let l=Zl.listItem(e,t,r,m(m({},n),o.current()));return i&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),l;function u(d){return d+s}}function ox(){return[Rb(),sw(),cw(),Yw(),nx()]}function lx(e){return{extensions:[jb(),ow(e),dw(),rx(e),ax()]}}const ux={tokenize:mx,partial:!0},ru={tokenize:gx,partial:!0},nu={tokenize:yx,partial:!0},au={tokenize:bx,partial:!0},cx={tokenize:wx,partial:!0},iu={name:"wwwAutolink",tokenize:fx,previous:ou},su={name:"protocolAutolink",tokenize:px,previous:lu},st={name:"emailAutolink",tokenize:hx,previous:uu},nt={};function dx(){return{text:nt}}let At=48;for(;At<123;)nt[At]=st,At++,At===58?At=65:At===91&&(At=97);nt[43]=st,nt[45]=st,nt[46]=st,nt[95]=st,nt[72]=[st,su],nt[104]=[st,su],nt[87]=[st,iu],nt[119]=[st,iu];function hx(e,t,r){const n=this;let a,i;return s;function s(c){return!Ga(c)||!uu.call(n,n.previous)||Ya(n.events)?r(c):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),o(c))}function o(c){return Ga(c)?(e.consume(c),o):c===64?(e.consume(c),l):r(c)}function l(c){return c===46?e.check(cx,d,u)(c):c===45||c===95||_e(c)?(i=!0,e.consume(c),l):d(c)}function u(c){return e.consume(c),a=!0,l}function d(c){return i&&a&&Ee(n.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(c)):r(c)}}function fx(e,t,r){const n=this;return a;function a(s){return s!==87&&s!==119||!ou.call(n,n.previous)||Ya(n.events)?r(s):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(ux,e.attempt(ru,e.attempt(nu,i),r),r)(s))}function i(s){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(s)}}function px(e,t,r){const n=this;let a="",i=!1;return s;function s(c){return(c===72||c===104)&&lu.call(n,n.previous)&&!Ya(n.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),a+=String.fromCodePoint(c),e.consume(c),o):r(c)}function o(c){if(Ee(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),i?u:(i=!0,l)):r(c)}function u(c){return c===null||Zr(c)||ue(c)||Et(c)||en(c)?r(c):e.attempt(ru,e.attempt(nu,d),r)(c)}function d(c){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(c)}}function mx(e,t,r){let n=0;return a;function a(s){return(s===87||s===119)&&n<3?(n++,e.consume(s),a):s===46&&n===3?(e.consume(s),i):r(s)}function i(s){return s===null?r(s):t(s)}}function gx(e,t,r){let n,a,i;return s;function s(u){return u===46||u===95?e.check(au,l,o)(u):u===null||ue(u)||Et(u)||u!==45&&en(u)?l(u):(i=!0,e.consume(u),s)}function o(u){return u===95?n=!0:(a=n,n=void 0),e.consume(u),s}function l(u){return a||n||!i?r(u):t(u)}}function yx(e,t){let r=0,n=0;return a;function a(s){return s===40?(r++,e.consume(s),a):s===41&&n<r?i(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(au,t,i)(s):s===null||ue(s)||Et(s)?t(s):(e.consume(s),a)}function i(s){return s===41&&n++,e.consume(s),a}}function bx(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),i):o===93?(e.consume(o),a):o===60||o===null||ue(o)||Et(o)?t(o):r(o)}function a(o){return o===null||o===40||o===91||ue(o)||Et(o)?t(o):n(o)}function i(o){return Ee(o)?s(o):r(o)}function s(o){return o===59?(e.consume(o),n):Ee(o)?(e.consume(o),s):r(o)}}function wx(e,t,r){return n;function n(i){return e.consume(i),a}function a(i){return _e(i)?r(i):t(i)}}function ou(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||ue(e)}function lu(e){return!Ee(e)}function uu(e){return!(e===47||Ga(e))}function Ga(e){return e===43||e===45||e===46||e===95||_e(e)}function Ya(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 xx={tokenize:Ex,partial:!0};function vx(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Tx,continuation:{tokenize:Cx},exit:Ix}},text:{91:{name:"gfmFootnoteCall",tokenize:_x},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Sx,resolveTo:kx}}}}function Sx(e,t,r){const n=this;let a=n.events.length;const i=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let s;for(;a--;){const l=n.events[a][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=Ge(n.sliceSerialize({start:s.end,end:n.now()}));return u.codePointAt(0)!==94||!i.includes(u.slice(1))?r(l):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(l),e.exit("gfmFootnoteCallLabelMarker"),t(l))}}function kx(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 i={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},e[e.length-1][1].start)},s={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},o=[e[r+1],e[r+2],["enter",n,t],e[r+3],e[r+4],["enter",a,t],["exit",a,t],["enter",i,t],["enter",s,t],["exit",s,t],["exit",i,t],e[e.length-2],e[e.length-1],["exit",n,t]];return e.splice(r,e.length-r+1,...o),e}function _x(e,t,r){const n=this,a=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let i=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(i>999||c===93&&!s||c===null||c===91||ue(c))return r(c);if(c===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return a.includes(Ge(n.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(c)}return ue(c)||(s=!0),i++,e.consume(c),c===92?d:u}function d(c){return c===91||c===92||c===93?(e.consume(c),i++,u):u(c)}}function Tx(e,t,r){const n=this,a=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let i,s=0,o;return l;function l(y){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(y){return y===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",d):r(y)}function d(y){if(s>999||y===93&&!o||y===null||y===91||ue(y))return r(y);if(y===93){e.exit("chunkString");const S=e.exit("gfmFootnoteDefinitionLabelString");return i=Ge(n.sliceSerialize(S)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(y),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return ue(y)||(o=!0),s++,e.consume(y),y===92?c:d}function c(y){return y===91||y===92||y===93?(e.consume(y),s++,d):d(y)}function f(y){return y===58?(e.enter("definitionMarker"),e.consume(y),e.exit("definitionMarker"),a.includes(i)||a.push(i),ne(e,h,"gfmFootnoteDefinitionWhitespace")):r(y)}function h(y){return t(y)}}function Cx(e,t,r){return e.check(gr,t,e.attempt(xx,t,r))}function Ix(e){e.exit("gfmFootnoteDefinition")}function Ex(e,t,r){const n=this;return ne(e,a,"gfmFootnoteDefinitionIndent",5);function a(i){const s=n.events[n.events.length-1];return s&&s[1].type==="gfmFootnoteDefinitionIndent"&&s[2].sliceSerialize(s[1],!0).length===4?t(i):r(i)}}function Ax(e){let r=(e||{}).singleTilde;const n={name:"strikethrough",tokenize:i,resolveAll:a};return r==null&&(r=!0),{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function a(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&&Fe(f,f.length,0,tn(h,s.slice(u+1,l),o)),Fe(f,f.length,0,[["exit",c,o],["enter",s[l][1],o],["exit",s[l][1],o],["exit",d,o]]),Fe(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 i(s,o,l){const u=this.previous,d=this.events;let c=0;return f;function f(y){return u===126&&d[d.length-1][1].type!=="characterEscape"?l(y):(s.enter("strikethroughSequenceTemporary"),h(y))}function h(y){const S=qt(u);if(y===126)return c>1?l(y):(s.consume(y),c++,h);if(c<2&&!r)return l(y);const x=s.exit("strikethroughSequenceTemporary"),b=qt(y);return x._open=!b||b===2&&!!S,x._close=!S||S===2&&!!b,o(y)}}}class Px{constructor(){this.map=[]}add(t,r,n){Mx(this,t,r,n)}consume(t){if(this.map.sort(function(i,s){return i[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 a=n.pop();for(;a;){for(const i of a)t.push(i);a=n.pop()}this.map.length=0}}function Mx(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 Nx(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 i=n.length-1;n[i]=n[i]==="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 Lx(){return{flow:{null:{name:"table",tokenize:Dx,resolveAll:Ox}}}}function Dx(e,t,r){const n=this;let a=0,i=0,s;return o;function o(k){let D=n.events.length-1;for(;D>-1;){const R=n.events[D][1].type;if(R==="lineEnding"||R==="linePrefix")D--;else break}const M=D>-1?n.events[D][1].type:null,H=M==="tableHead"||M==="tableRow"?I:l;return H===I&&n.parser.lazy[n.now().line]?r(k):H(k)}function l(k){return e.enter("tableHead"),e.enter("tableRow"),u(k)}function u(k){return k===124||(s=!0,i+=1),d(k)}function d(k){return k===null?r(k):K(k)?i>1?(i=0,n.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),h):r(k):ee(k)?ne(e,d,"whitespace")(k):(i+=1,s&&(s=!1,a+=1),k===124?(e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),s=!0,d):(e.enter("data"),c(k)))}function c(k){return k===null||k===124||ue(k)?(e.exit("data"),d(k)):(e.consume(k),k===92?f:c)}function f(k){return k===92||k===124?(e.consume(k),c):c(k)}function h(k){return n.interrupt=!1,n.parser.lazy[n.now().line]?r(k):(e.enter("tableDelimiterRow"),s=!1,ee(k)?ne(e,y,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(k):y(k))}function y(k){return k===45||k===58?x(k):k===124?(s=!0,e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),S):z(k)}function S(k){return ee(k)?ne(e,x,"whitespace")(k):x(k)}function x(k){return k===58?(i+=1,s=!0,e.enter("tableDelimiterMarker"),e.consume(k),e.exit("tableDelimiterMarker"),b):k===45?(i+=1,b(k)):k===null||K(k)?L(k):z(k)}function b(k){return k===45?(e.enter("tableDelimiterFiller"),_(k)):z(k)}function _(k){return k===45?(e.consume(k),_):k===58?(s=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(k),e.exit("tableDelimiterMarker"),T):(e.exit("tableDelimiterFiller"),T(k))}function T(k){return ee(k)?ne(e,L,"whitespace")(k):L(k)}function L(k){return k===124?y(k):k===null||K(k)?!s||a!==i?z(k):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(k)):z(k)}function z(k){return r(k)}function I(k){return e.enter("tableRow"),q(k)}function q(k){return k===124?(e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),q):k===null||K(k)?(e.exit("tableRow"),t(k)):ee(k)?ne(e,q,"whitespace")(k):(e.enter("data"),B(k))}function B(k){return k===null||k===124||ue(k)?(e.exit("data"),q(k)):(e.consume(k),k===92?U:B)}function U(k){return k===92||k===124?(e.consume(k),B):B(k)}}function Ox(e,t){let r=-1,n=!0,a=0,i=[0,0,0,0],s=[0,0,0,0],o=!1,l=0,u,d,c;const f=new Px;for(;++r<e.length;){const h=e[r],y=h[1];h[0]==="enter"?y.type==="tableHead"?(o=!1,l!==0&&(cu(f,t,l,u,d),d=void 0,l=0),u={type:"table",start:Object.assign({},y.start),end:Object.assign({},y.end)},f.add(r,0,[["enter",u,t]])):y.type==="tableRow"||y.type==="tableDelimiterRow"?(n=!0,c=void 0,i=[0,0,0,0],s=[0,r+1,0,0],o&&(o=!1,d={type:"tableBody",start:Object.assign({},y.start),end:Object.assign({},y.end)},f.add(r,0,[["enter",d,t]])),a=y.type==="tableDelimiterRow"?2:d?3:1):a&&(y.type==="data"||y.type==="tableDelimiterMarker"||y.type==="tableDelimiterFiller")?(n=!1,s[2]===0&&(i[1]!==0&&(s[0]=s[1],c=fn(f,t,i,a,void 0,c),i=[0,0,0,0]),s[2]=r)):y.type==="tableCellDivider"&&(n?n=!1:(i[1]!==0&&(s[0]=s[1],c=fn(f,t,i,a,void 0,c)),i=s,s=[i[1],r,0,0])):y.type==="tableHead"?(o=!0,l=r):y.type==="tableRow"||y.type==="tableDelimiterRow"?(l=r,i[1]!==0?(s[0]=s[1],c=fn(f,t,i,a,r,c)):s[1]!==0&&(c=fn(f,t,s,a,r,c)),a=0):a&&(y.type==="data"||y.type==="tableDelimiterMarker"||y.type==="tableDelimiterFiller")&&(s[3]=r)}for(l!==0&&cu(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=Nx(t.events,r))}return e}function fn(e,t,r,n,a,i){const s=n===1?"tableHeader":n===2?"tableDelimiter":"tableData",o="tableContent";r[0]!==0&&(i.end=Object.assign({},Wt(t.events,r[0])),e.add(r[0],0,[["exit",i,t]]));const l=Wt(t.events,r[1]);if(i={type:s,start:Object.assign({},l),end:Object.assign({},l)},e.add(r[1],0,[["enter",i,t]]),r[2]!==0){const u=Wt(t.events,r[2]),d=Wt(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 y=r[2]+1,S=r[3]-r[2]-1;e.add(y,S,[])}}e.add(r[3]+1,0,[["exit",c,t]])}return a!==void 0&&(i.end=Object.assign({},Wt(t.events,a)),e.add(a,0,[["exit",i,t]]),i=void 0),i}function cu(e,t,r,n,a){const i=[],s=Wt(t.events,r);a&&(a.end=Object.assign({},s),i.push(["exit",a,t])),n.end=Object.assign({},s),i.push(["exit",n,t]),e.add(r+1,0,i)}function Wt(e,t){const r=e[t],n=r[0]==="enter"?"start":"end";return r[1][n]}const Fx={name:"tasklistCheck",tokenize:zx};function Bx(){return{text:{91:Fx}}}function zx(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"),i)}function i(l){return ue(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 K(l)?t(l):ee(l)?e.check({tokenize:Rx},t,r)(l):r(l)}}function Rx(e,t,r){return ne(e,n,"whitespace");function n(a){return a===null?r(a):t(a)}}function jx(e){return jo([dx(),vx(),Ax(e),Lx(),Bx()])}const $x={};function Ux(e){const t=this,r=e||$x,n=t.data(),a=n.micromarkExtensions||(n.micromarkExtensions=[]),i=n.fromMarkdownExtensions||(n.fromMarkdownExtensions=[]),s=n.toMarkdownExtensions||(n.toMarkdownExtensions=[]);a.push(jx(r)),i.push(ox()),s.push(lx(r))}function ye(...e){return e.filter(Boolean).join(" ")}const Hx=({content:e})=>p.jsx(Lb,{remarkPlugins:[Ux],className:"cuadra-aui-md",components:Wx,children:e}),du=g.memo(Hx),qx=({language:e,code:t})=>{const{isCopied:r,copyToClipboard:n}=Vx(),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(Du,{className:"cuadra-h-4 cuadra-w-4"}),r&&p.jsx(Nu,{className:"cuadra-h-4 cuadra-w-4"})]})]})},Vx=({copiedDuration:e=3e3}={})=>{const[t,r]=g.useState(!1);return{isCopied:t,copyToClipboard:a=>{a&&navigator.clipboard.writeText(a).then(()=>{r(!0),setTimeout(()=>r(!1),e)})}}},Wx=yb({h1:r=>{var n=r,{className:e}=n,t=W(n,["className"]);return p.jsx("h1",m({className:ye("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=W(n,["className"]);return p.jsx("h2",m({className:ye("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=W(n,["className"]);return p.jsx("h3",m({className:ye("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=W(n,["className"]);return p.jsx("h4",m({className:ye("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=W(n,["className"]);return p.jsx("h5",m({className:ye("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=W(n,["className"]);return p.jsx("h6",m({className:ye("cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand",e)},t))},p:r=>{var n=r,{className:e}=n,t=W(n,["className"]);return p.jsx("p",m({className:ye("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=W(n,["className"]);return p.jsx("a",m({className:ye("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=W(n,["className"]);return p.jsx("blockquote",m({className:ye("cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand",e)},t))},ul:r=>{var n=r,{className:e}=n,t=W(n,["className"]);return p.jsx("ul",m({className:ye("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=W(n,["className"]);return p.jsx("ol",m({className:ye("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=W(n,["className"]);return p.jsx("hr",m({className:ye("cuadra-my-5 cuadra-border-b",e)},t))},table:r=>{var n=r,{className:e}=n,t=W(n,["className"]);return p.jsx("table",m({className:ye("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=W(n,["className"]);return p.jsx("th",m({className:ye("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=W(n,["className"]);return p.jsx("td",m({className:ye("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=W(n,["className"]);return p.jsx("tr",m({className:ye("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=W(n,["className"]);return p.jsx("sup",m({className:ye("[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand",e)},t))},pre:r=>{var n=r,{className:e}=n,t=W(n,["className"]);return p.jsx("pre",m({className:ye("cuadra-overflow-x-auto 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=W(a,["className"]);const i=Pl();return p.jsx("code",m({className:ye(!i&&"cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand",t)},r))},CodeHeader:qx}),hu=["Sending question…","Understanding your need…","Scanning data…","Comparing results…","Composing answer…"];function Jx({active:e}){const[t,r]=g.useState(0);return g.useEffect(()=>{if(!e){r(0);return}const n=window.setInterval(()=>{r(a=>a>=hu.length-1?(window.clearInterval(n),a):a+1)},2500);return()=>window.clearInterval(n)},[e]),e?p.jsxs("span",{className:"cuadra-text-xs cuadra-text-muted-foreground cuadra-font-brand",children:["Thinking… ",hu[t]]}):null}const fu=g.forwardRef(function({welcomeTitle:t="Hi, how can I help you today?",welcomeSubtitle:r="Start exploring our platform and discover what you can build.",extraTopPadding:n,suggestions:a,inputPlaceholder:i="Type your message...",enableAttachments:s=!1,preMadeResponseDelay:o=1e3,streamingSpeed:l=50},u){const d=ns(),c=de(),[f,h]=g.useState(!1),[y,S]=g.useState(null),[x,b]=g.useState(!1),[_,T]=g.useState(!1),L=g.useCallback((B,U,k)=>{var D,M;if(!_)try{const H=(D=k==null?void 0:k.streamingSpeed)!=null?D:l,R=(M=k==null?void 0:k.delay)!=null?M:o;ip(B,U,H,R),c.composer().setText(B),setTimeout(()=>{c.composer().send()},10)}catch(H){console.error("Pre-made QA error:",H)}},[_,l,o,c]),z=g.useCallback(B=>{try{c.composer().setText(B),setTimeout(()=>{c.composer().send()},10)}catch(U){}},[c]),I=g.useCallback(B=>P(null,null,function*(){var U;if(!(_||!d))try{if(B.response){const k=(U=B.responseDelay)!=null?U:o;yield L(B.prompt,B.response,{delay:k,streamingSpeed:l})}else z(B.prompt)}catch(k){}}),[d,_,o,l,L,z]),q=g.useCallback(()=>{try{const B=window.__cuadraThreadListRuntime;B!=null&&B.switchToNewThread&&B.switchToNewThread()}catch(B){}},[]);return g.useImperativeHandle(u,()=>({sendMessage:z,sendPreMadeQA:L,clearChat:q}),[z,L,q]),g.useEffect(()=>{var B,U;if(!d){h(!1);return}try{const k=d==null?void 0:d.store;if(!k){h(!1);return}const D=(B=k.subscribe)==null?void 0:B.call(k,H=>{const R=H==null?void 0:H.threadId,F=(H==null?void 0:H.messages)||[],j=(H==null?void 0:H.isLoadingHistory)||!1,J=F.length;R&&R!==y&&S(R),h(j&&J===0);const Z=F.some(w=>w.role==="assistant"&&!!w.content&&(Array.isArray(w.content)?w.content.some(ae=>typeof ae=="object"&&(ae!=null&&ae.text)?ae.text.trim().length>0:!1):typeof w.content=="string"?w.content.trim().length>0:!1));b(Z)}),M=(U=k.getState)==null?void 0:U.call(k);if(M){const H=M==null?void 0:M.threadId,R=(M==null?void 0:M.messages)||[],F=(M==null?void 0:M.isLoadingHistory)||!1,j=R.length;H&&H!==y&&S(H),h(F&&j===0);const re=R.some(Z=>Z.role==="assistant"&&!!Z.content&&(Array.isArray(Z.content)?Z.content.some(w=>typeof w=="object"&&(w!=null&&w.text)?w.text.trim().length>0:!1):typeof Z.content=="string"?Z.content.trim().length>0:!1));b(re)}return()=>{D&&D()}}catch(k){h(!1)}},[d,y]),p.jsxs(Ks,{className:"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full",children:[p.jsx(Qs,{className:"cuadra-w-full cuadra-bg-inherit cuadra-px-4 cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto cuadra-relative scrollbar-thin cuadra-pt-4",style:n?{paddingTop:n}:void 0,children:f?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-2",children:[p.jsx(ai,{className:"cuadra-h-6 cuadra-w-6 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(p.Fragment,{children:[p.jsx(Gs,{children:p.jsx(Kx,{title:t,subtitle:r,suggestions:a,onSuggestionClick:I,isProcessing:_})}),p.jsx(Yf,{components:{UserMessage:Gx,AssistantMessage:Yx}}),p.jsx(Ys,{running:!0,children:!x&&p.jsx("div",{className:"cuadra-mt-2 cuadra-max-w-2xl",children:p.jsx(Jx,{active:!0})})})]})}),p.jsxs("div",{className:"cuadra-w-full cuadra-mt-3 cuadra-border-t cuadra-border-border cuadra-pt-4",children:[s&&p.jsx(Js,{components:{Attachment:()=>{const B=se(({attachment:U})=>U);return B?p.jsxs("div",{className:"cuadra-relative cuadra-inline-flex cuadra-items-center cuadra-gap-2 cuadra-mb-2 cuadra-px-2 cuadra-py-1 cuadra-rounded-md cuadra-bg-muted cuadra-border cuadra-border-border",children:[p.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground font-brand",children:B.name||"Attachment"}),p.jsx(nf,{asChild:!0,children:p.jsx("button",{type:"button",className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-4 cuadra-rounded hover:cuadra-bg-background cuadra-transition-colors","aria-label":"Remove attachment",children:p.jsx(_n,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})})]}):null}}}),p.jsxs(zs,{className:"cuadra-relative !cuadra-relative cuadra-flex-1 cuadra-w-full",children:[p.jsx(Vs,{asChild:!0,children:p.jsx("textarea",{rows:3,placeholder:i,className:"cuadra-flex cuadra-min-h-[80px] cuadra-w-full cuadra-rounded-md cuadra-border cuadra-border-border cuadra-bg-background cuadra-px-3 cuadra-py-2 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:{paddingRight:s?"5rem":"3rem",fontSize:"1rem",borderWidth:"1px"}})}),s&&p.jsx(jf,{multiple:!0,asChild:!0,children:p.jsx("button",{type:"button",className:"!cuadra-absolute !cuadra-bottom-2 !cuadra-right-12 cuadra-size-8 cuadra-rounded-md hover:cuadra-bg-muted cuadra-transition-colors cuadra-flex cuadra-items-center cuadra-justify-center cuadra-border cuadra-border-border",style:{position:"absolute",bottom:"0.5rem",right:"3rem"},"aria-label":"Attach file",children:p.jsx(ii,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground",strokeWidth:1.5})})}),p.jsx(vf,{asChild:!0,children:p.jsx("button",{className:"!cuadra-absolute !cuadra-bottom-2 !cuadra-right-2 cuadra-size-8 cuadra-rounded-md cuadra-shadow-sm hover:cuadra-opacity-90 disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed cuadra-flex cuadra-items-center cuadra-justify-center",style:{position:"absolute",bottom:"0.5rem",right:"0.5rem",backgroundColor:"var(--cuadra-primary)",color:"hsl(var(--cuadra-primary-foreground))"},"aria-label":"Send message",type:"button",children:p.jsx(Mu,{className:"cuadra-h-4 cuadra-w-4"})})})]})]})]})});function Kx({title:e,subtitle:t,suggestions:r,onSuggestionClick:n,isProcessing:a}){return p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-h-full cuadra-py-12 cuadra-px-4 cuadra-overflow-y-auto scrollbar-hide",children:p.jsxs("div",{className:"cuadra-text-center cuadra-max-w-3xl cuadra-w-full cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-min-h-full",children:[p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-mb-8",children:[p.jsx("h2",{className:"cuadra-text-lg cuadra-font-normal cuadra-text-foreground cuadra-mb-2 font-brand",children:e}),p.jsx("p",{className:"cuadra-text-muted-foreground font-brand",children:t})]}),r&&r.length>0&&p.jsx("div",{className:"cuadra-grid cuadra-grid-cols-2 cuadra-gap-2 cuadra-pb-4 cuadra-w-full cuadra-max-w-2xl",children:r.map((i,s)=>p.jsx("button",{type:"button",onClick:()=>n(i),disabled:a,className:"cuadra-w-full cuadra-text-center cuadra-px-4 cuadra-py-3 cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-bg-background cuadra-text-sm cuadra-text-foreground font-brand cuadra-cursor-pointer focus:cuadra-outline-none focus:cuadra-ring-0 disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed",style:{borderWidth:"1px"},children:i.prompt},`suggestion-${s}`))})]})})}function Gx(){return p.jsxs(Xn,{className:"cuadra-grid cuadra-w-full cuadra-auto-rows-auto cuadra-grid-cols-[minmax(72px,1fr)_auto] cuadra-gap-y-2 cuadra-py-3 [&:where(>*)]:cuadra-col-start-2",children:[p.jsx(Fs,{components:{Attachment:()=>{var i;const e=se(({attachment:s})=>s);if(!e)return null;const t=e.type==="image",r=e.file,n=(i=e.content)==null?void 0:i.find(s=>s.type==="image"),a=r?URL.createObjectURL(r):n==null?void 0:n.image;return p.jsx("div",{className:"cuadra-col-start-2 cuadra-row-start-1 cuadra-mb-2 cuadra-max-w-[calc(42rem*0.8)]",children:t&&a?p.jsx("img",{src:a,alt:e.name||"Attachment",className:"cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-max-h-64 cuadra-max-w-full cuadra-object-contain",style:{borderWidth:"1px"}}):p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-bg-muted cuadra-px-3 cuadra-py-2",children:[p.jsx(ii,{className:"cuadra-h-4 cuadra-w-4 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-bg-muted cuadra-text-foreground cuadra-col-start-2 cuadra-row-start-2 cuadra-max-w-[calc(42rem*0.8)] cuadra-break-words cuadra-rounded-3xl cuadra-border cuadra-border-border cuadra-px-5 cuadra-py-2.5 font-brand",style:{maxWidth:"calc(42rem * 0.8)",borderRadius:"1.5rem",backgroundColor:"var(--cuadra-muted)",color:"hsl(var(--cuadra-foreground))",paddingLeft:"1.25rem",paddingRight:"1.25rem",paddingTop:"0.625rem",paddingBottom:"0.625rem",wordBreak:"break-word",borderWidth:"1px"},children:p.jsx(Qn,{components:{Text:({text:e})=>p.jsx(du,{content:e||""})}})})]})}function Yx(){return p.jsx(Xn,{className:"cuadra-relative cuadra-grid cuadra-w-full cuadra-grid-cols-[auto_auto_1fr] cuadra-grid-rows-[auto_1fr] cuadra-py-3",children:p.jsx("div",{className:"cuadra-text-foreground cuadra-col-span-2 cuadra-col-start-2 cuadra-row-start-1 cuadra-my-1.5 cuadra-max-w-[90%] cuadra-break-words cuadra-leading-7 font-brand",style:{maxWidth:"90%",marginTop:"0.375rem",marginBottom:"0.375rem"},children:p.jsx(Qn,{components:{Text:({text:e})=>p.jsx(du,{content:e||""})}})})})}const pu=({className:e="",theme:t="system"})=>{const r=()=>{if(typeof window=="undefined")return"light";if(t==="system"){const s=localStorage.getItem("theme");return s||(window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light")}return t},[n,a]=g.useState(r);g.useEffect(()=>{t!=="system"&&a(t)},[t]),g.useEffect(()=>{const s=document.documentElement;s.classList.remove("light","dark"),s.classList.add(n),t==="system"&&localStorage.setItem("theme",n)},[n,t]);const i=()=>{t==="system"&&a(s=>s==="light"?"dark":"light")};return p.jsx("button",{type:"button","aria-label":"Toggle theme",onClick:i,disabled:t!=="system",className:`cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed ${e}`,children:p.jsx(Lu,{className:`cuadra-h-4 cuadra-w-4 cuadra-transition-colors ${n==="dark"?"cuadra-text-primary":"cuadra-text-gray-400"}`})})};function Xx({onThreadSelect:e}){var x,b;const t=as(),r=$d(_=>_.threadId),[n,a]=g.useState(null),i=(t==null?void 0:t.id)===r,s=n===(t==null?void 0:t.id),[o,l]=g.useState(!1),[u,d]=g.useState((t==null?void 0:t.title)||""),[c,f]=g.useState(!1),[h,y]=g.useState(!1),S=()=>P(null,null,function*(){if(!(t!=null&&t.remoteId)||!u||u===t.title){l(!1);return}try{y(!0);const _=window.__cuadraThreadListAdapter;_&&typeof _.rename=="function"&&(yield _.rename(t.remoteId,u)),l(!1),f(!1)}catch(_){l(!1),f(!1)}finally{y(!1)}});return g.useEffect(()=>{t!=null&&t.title&&!o&&d(t.title)},[t==null?void 0:t.title,o]),t?p.jsxs(so,{className:`group cuadra-relative cuadra-flex cuadra-items-center cuadra-rounded-lg cuadra-transition-colors cuadra-cursor-pointer cuadra-border cuadra-mb-2 ${i?"cuadra-bg-muted cuadra-border-border":"cuadra-border-transparent hover:cuadra-bg-muted hover:cuadra-border-border"}`,style:{marginBottom:"0.5rem"},onMouseEnter:()=>a(t.id),onMouseLeave:()=>a(null),children:[p.jsx(ep,{className:"cuadra-p-3 cuadra-flex-1 cuadra-flex cuadra-items-center cuadra-min-w-0 cuadra-cursor-pointer",onClick:()=>e==null?void 0:e(),children:p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-min-w-0 cuadra-flex-1 cuadra-items-start cuadra-text-left",children:o?p.jsx("input",{className:"cuadra-flex cuadra-w-full cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus-visible:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 font-brand",value:u,onChange:_=>d(_.target.value),onKeyDown:_=>{_.key==="Enter"&&S(),_.key==="Escape"&&(l(!1),d(t.title||""))},disabled:h,autoFocus:!0,onClick:_=>_.stopPropagation()}):p.jsxs(p.Fragment,{children:[p.jsx("span",{className:"cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-truncate font-brand",children:(((x=t.title)==null?void 0:x.length)||0)>60?`${(b=t.title)==null?void 0:b.slice(0,60)}…`:t.title||"Chat"}),t.updatedAt&&p.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground cuadra-mt-1 font-brand",children:new Date(t.updatedAt).toLocaleDateString()})]})})}),p.jsx("div",{className:"cuadra-mr-2 cuadra-flex-shrink-0 cuadra-w-6 cuadra-h-6 cuadra-flex cuadra-items-center cuadra-justify-center",children:(s||i||c)&&p.jsxs("div",{className:"cuadra-relative",children:[p.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-background/50 cuadra-transition-colors",onClick:_=>{_.stopPropagation(),f(!c)},"aria-label":"Thread options",children:p.jsx(Ou,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"})}),c&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:()=>f(!1)}),p.jsx("div",{className:"cuadra-absolute cuadra-right-0 cuadra-top-8 cuadra-z-50 cuadra-bg-background cuadra-border cuadra-border-border cuadra-rounded-lg cuadra-shadow-lg cuadra-min-w-[120px] cuadra-overflow-hidden",children:o?p.jsx("button",{type:"button",className:"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:_=>{_.stopPropagation(),S()},disabled:h,children:"Save"}):p.jsxs(p.Fragment,{children:[p.jsx("button",{type:"button",className:"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:_=>{_.stopPropagation(),l(!0),d(t.title||""),f(!1)},children:"Rename"}),p.jsx("div",{className:"cuadra-border-t cuadra-border-border"}),p.jsx(Qf,{asChild:!0,children:p.jsx("button",{type:"button",className:"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left cuadra-text-destructive hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:_=>{_.stopPropagation(),f(!1)},children:"Delete"})})]})})]})]})})]}):null}function mu({onThreadSelect:e,showThemeToggle:t,theme:r,onLogout:n}){return p.jsxs(io,{className:"!cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-full cuadra-w-80",style:{borderRightWidth:"1px"},children:[p.jsx("div",{className:"cuadra-border-b cuadra-border-border cuadra-flex cuadra-items-center cuadra-justify-end cuadra-transition-all cuadra-duration-300 cuadra-h-16 cuadra-px-4",children:p.jsx("button",{type:"button",onClick:e,className:"cuadra-flex md:cuadra-hidden cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors","aria-label":"Close",children:p.jsx(_n,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})})}),p.jsxs("div",{className:"cuadra-flex-1 cuadra-overflow-y-auto cuadra-p-2 scrollbar-thin",children:[p.jsx(ro,{className:"group cuadra-relative cuadra-flex cuadra-items-center cuadra-gap-3 cuadra-p-3 cuadra-rounded-lg cuadra-cursor-pointer cuadra-transition-colors cuadra-border cuadra-border-transparent hover:cuadra-bg-muted hover:cuadra-border-border",onClick:()=>e==null?void 0:e(),children:p.jsx("div",{className:"cuadra-flex-1 cuadra-min-w-0",children:p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[p.jsx(zu,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),p.jsx("h4",{className:"cuadra-text-sm cuadra-font-normal cuadra-text-foreground font-brand",children:"New Chat"})]})})}),p.jsx("div",{className:"cuadra-my-2 cuadra-border-t cuadra-border-border"}),p.jsx(ao,{components:{ThreadListItem:a=>p.jsx(Xx,E(m({},a),{onThreadSelect:e}))}})]}),(t||n)&&p.jsxs("div",{className:"cuadra-border-t cuadra-border-border cuadra-flex md:cuadra-hidden cuadra-items-center cuadra-justify-between cuadra-px-4 cuadra-py-4",children:[n&&p.jsx("button",{type:"button",onClick:n,className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors","aria-label":"Logout",children:p.jsx(Fu,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})}),t&&p.jsx(pu,{theme:r})]})]})}const Qx=`
33
+ `},i.current()));return/^[\t ]/.test(u)&&(u=Sr(u.charCodeAt(0))+u.slice(1)),u=u?s+" "+u:s,r.options.closeAtx&&(u+=" "+s),l(),o(),u}Wl.peek=Ow;function Wl(e){return e.value||""}function Ow(){return"<"}Jl.peek=Fw;function Jl(e,t,r,n){const a=Ja(r),i=a==='"'?"Quote":"Apostrophe",s=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${i}`),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(")"),s(),u}function Fw(){return"!"}Kl.peek=Bw;function Kl(e,t,r,n){const a=e.referenceType,i=r.enter("imageReference");let s=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+"]["),s();const c=r.stack;r.stack=[],s=r.enter("reference");const d=r.safe(r.associationId(e),m({before:l,after:"]"},o.current()));return s(),r.stack=c,i(),a==="full"||!u||u!==d?l+=o.move(d+"]"):a==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function Bw(){return"!"}Yl.peek=zw;function Yl(e,t,r){let n=e.value||"",a="`",i=-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+" ");++i<r.unsafe.length;){const s=r.unsafe[i],o=r.compilePattern(s);let l;if(s.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 zw(){return"`"}function Gl(e,t){const r=ma(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))}Xl.peek=Rw;function Xl(e,t,r,n){const a=Ja(r),i=a==='"'?"Quote":"Apostrophe",s=r.createTracker(n);let o,l;if(Gl(e,r)){const c=r.stack;r.stack=[],o=r.enter("autolink");let d=s.move("<");return d+=s.move(r.containerPhrasing(e,m({before:d,after:">"},s.current()))),d+=s.move(">"),o(),r.stack=c,d}o=r.enter("link"),l=r.enter("label");let u=s.move("[");return u+=s.move(r.containerPhrasing(e,m({before:u,after:"]("},s.current()))),u+=s.move("]("),l(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(l=r.enter("destinationLiteral"),u+=s.move("<"),u+=s.move(r.safe(e.url,m({before:u,after:">"},s.current()))),u+=s.move(">")):(l=r.enter("destinationRaw"),u+=s.move(r.safe(e.url,m({before:u,after:e.title?" ":")"},s.current())))),l(),e.title&&(l=r.enter(`title${i}`),u+=s.move(" "+a),u+=s.move(r.safe(e.title,m({before:u,after:a},s.current()))),u+=s.move(a),l()),u+=s.move(")"),o(),u}function Rw(e,t,r){return Gl(e,r)?"<":"["}Ql.peek=jw;function Ql(e,t,r,n){const a=e.referenceType,i=r.enter("linkReference");let s=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+"]["),s();const c=r.stack;r.stack=[],s=r.enter("reference");const d=r.safe(r.associationId(e),m({before:l,after:"]"},o.current()));return s(),r.stack=c,i(),a==="full"||!u||u!==d?l+=o.move(d+"]"):a==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function jw(){return"["}function Ka(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 $w(e){const t=Ka(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 Uw(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 Zl(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 Hw(e,t,r,n){const a=r.enter("list"),i=r.bulletCurrent;let s=e.ordered?Uw(r):Ka(r);const o=e.ordered?s==="."?")":".":$w(r);let l=t&&r.bulletLastUsed?s===r.bulletLastUsed:!1;if(!e.ordered){const c=e.children?e.children[0]:void 0;if((s==="*"||s==="-")&&c&&(!c.children||!c.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),Zl(r)===s&&c){let d=-1;for(;++d<e.children.length;){const f=e.children[d];if(f&&f.type==="listItem"&&f.children&&f.children[0]&&f.children[0].type==="thematicBreak"){l=!0;break}}}}l&&(s=o),r.bulletCurrent=s;const u=r.containerFlow(e,n);return r.bulletLastUsed=s,r.bulletCurrent=i,a(),u}function qw(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 Vw(e,t,r,n){const a=qw(r);let i=r.bulletCurrent||Ka(r);t&&t.type==="list"&&t.ordered&&(i=(typeof t.start=="number"&&t.start>-1?t.start:1)+(r.options.incrementListMarker===!1?0:t.children.indexOf(e))+i);let s=i.length+1;(a==="tab"||a==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(s=Math.ceil(s/4)*4);const o=r.createTracker(n);o.move(i+" ".repeat(s-i.length)),o.shift(s);const l=r.enter("listItem"),u=r.indentLines(r.containerFlow(e,o.current()),c);return l(),u;function c(d,f,h){return f?(h?"":" ".repeat(s))+d:(h?i:i+" ".repeat(s-i.length))+d}}function Ww(e,t,r,n){const a=r.enter("paragraph"),i=r.enter("phrasing"),s=r.containerPhrasing(e,n);return i(),a(),s}const Jw=dn(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function Kw(e,t,r,n){return(e.children.some(function(s){return Jw(s)})?r.containerPhrasing:r.containerFlow).call(r,e,n)}function Yw(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}eu.peek=Gw;function eu(e,t,r,n){const a=Yw(r),i=r.enter("strong"),s=r.createTracker(n),o=s.move(a+a);let l=s.move(r.containerPhrasing(e,m({after:a,before:o},s.current())));const u=l.charCodeAt(0),c=pn(n.before.charCodeAt(n.before.length-1),u,a);c.inside&&(l=Sr(u)+l.slice(1));const d=l.charCodeAt(l.length-1),f=pn(n.after.charCodeAt(0),d,a);f.inside&&(l=l.slice(0,-1)+Sr(d));const h=s.move(a+a);return i(),r.attentionEncodeSurroundingInfo={after:f.outside,before:c.outside},o+l+h}function Gw(e,t,r){return r.options.strong||"*"}function Xw(e,t,r,n){return r.safe(e.value,n)}function Qw(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 Zw(e,t,r){const n=(Zl(r)+(r.options.ruleSpaces?" ":"")).repeat(Qw(r));return r.options.ruleSpaces?n.slice(0,-1):n}const tu={blockquote:kw,break:ql,code:Ew,definition:Mw,emphasis:Vl,hardBreak:ql,heading:Dw,html:Wl,image:Jl,imageReference:Kl,inlineCode:Yl,link:Xl,linkReference:Ql,list:Hw,listItem:Vw,paragraph:Ww,root:Kw,strong:eu,text:Xw,thematicBreak:Zw};function ex(){return{enter:{table:tx,tableData:ru,tableHeader:ru,tableRow:nx},exit:{codeText:ax,table:rx,tableData:Ya,tableHeader:Ya,tableRow:Ya}}}function tx(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 rx(e){this.exit(e),this.data.inTable=void 0}function nx(e){this.enter({type:"tableRow",children:[]},e)}function Ya(e){this.exit(e)}function ru(e){this.enter({type:"tableCell",children:[]},e)}function ax(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,ix));const r=this.stack[this.stack.length-1];r.type,r.value=t,this.exit(e)}function ix(e,t){return t==="|"?t:e}function sx(e){const t=e||{},r=t.tableCellPadding,n=t.tablePipeAlign,a=t.stringLength,i=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:s,tableCell:l,tableRow:o}};function s(h,g,k,w){return u(c(h,k,w),h.align)}function o(h,g,k,w){const b=d(h,k,w),I=u([b]);return I.slice(0,I.indexOf(`
35
+ `))}function l(h,g,k,w){const b=k.enter("tableCell"),I=k.enter("phrasing"),T=k.containerPhrasing(h,E(m({},w),{before:i,after:i}));return I(),b(),T}function u(h,g){return xw(h,{align:g,alignDelimiters:n,padding:r,stringLength:a})}function c(h,g,k){const w=h.children;let b=-1;const I=[],T=g.enter("table");for(;++b<w.length;)I[b]=d(w[b],g,k);return T(),I}function d(h,g,k){const w=h.children;let b=-1;const I=[],T=g.enter("tableRow");for(;++b<w.length;)I[b]=l(w[b],h,g,k);return T(),I}function f(h,g,k){let w=tu.inlineCode(h,g,k);return k.stack.includes("tableCell")&&(w=w.replace(/\|/g,"\\$&")),w}}function ox(){return{exit:{taskListCheckValueChecked:nu,taskListCheckValueUnchecked:nu,paragraph:ux}}}function lx(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:cx}}}function nu(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function ux(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 i=-1,s;for(;++i<a.length;){const o=a[i];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 cx(e,t,r,n){const a=e.children[0],i=typeof e.checked=="boolean"&&a&&a.type==="paragraph",s="["+(e.checked?"x":" ")+"] ",o=r.createTracker(n);i&&o.move(s);let l=tu.listItem(e,t,r,m(m({},n),o.current()));return i&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),l;function u(c){return c+s}}function dx(){return[Hb(),cw(),pw(),ex(),ox()]}function hx(e){return{extensions:[qb(),dw(e),mw(),sx(e),lx()]}}const fx={tokenize:wx,partial:!0},au={tokenize:xx,partial:!0},iu={tokenize:vx,partial:!0},su={tokenize:kx,partial:!0},px={tokenize:Sx,partial:!0},ou={name:"wwwAutolink",tokenize:yx,previous:uu},lu={name:"protocolAutolink",tokenize:bx,previous:cu},ct={name:"emailAutolink",tokenize:gx,previous:du},ot={};function mx(){return{text:ot}}let At=48;for(;At<123;)ot[At]=ct,At++,At===58?At=65:At===91&&(At=97);ot[43]=ct,ot[45]=ct,ot[46]=ct,ot[95]=ct,ot[72]=[ct,lu],ot[104]=[ct,lu],ot[87]=[ct,ou],ot[119]=[ct,ou];function gx(e,t,r){const n=this;let a,i;return s;function s(d){return!Ga(d)||!du.call(n,n.previous)||Xa(n.events)?r(d):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),o(d))}function o(d){return Ga(d)?(e.consume(d),o):d===64?(e.consume(d),l):r(d)}function l(d){return d===46?e.check(px,c,u)(d):d===45||d===95||Ae(d)?(i=!0,e.consume(d),l):c(d)}function u(d){return e.consume(d),a=!0,l}function c(d){return i&&a&&Le(n.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(d)):r(d)}}function yx(e,t,r){const n=this;return a;function a(s){return s!==87&&s!==119||!uu.call(n,n.previous)||Xa(n.events)?r(s):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(fx,e.attempt(au,e.attempt(iu,i),r),r)(s))}function i(s){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(s)}}function bx(e,t,r){const n=this;let a="",i=!1;return s;function s(d){return(d===72||d===104)&&cu.call(n,n.previous)&&!Xa(n.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),a+=String.fromCodePoint(d),e.consume(d),o):r(d)}function o(d){if(Le(d)&&a.length<5)return a+=String.fromCodePoint(d),e.consume(d),o;if(d===58){const f=a.toLowerCase();if(f==="http"||f==="https")return e.consume(d),l}return r(d)}function l(d){return d===47?(e.consume(d),i?u:(i=!0,l)):r(d)}function u(d){return d===null||tn(d)||ue(d)||Et(d)||rn(d)?r(d):e.attempt(au,e.attempt(iu,c),r)(d)}function c(d){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(d)}}function wx(e,t,r){let n=0;return a;function a(s){return(s===87||s===119)&&n<3?(n++,e.consume(s),a):s===46&&n===3?(e.consume(s),i):r(s)}function i(s){return s===null?r(s):t(s)}}function xx(e,t,r){let n,a,i;return s;function s(u){return u===46||u===95?e.check(su,l,o)(u):u===null||ue(u)||Et(u)||u!==45&&rn(u)?l(u):(i=!0,e.consume(u),s)}function o(u){return u===95?n=!0:(a=n,n=void 0),e.consume(u),s}function l(u){return a||n||!i?r(u):t(u)}}function vx(e,t){let r=0,n=0;return a;function a(s){return s===40?(r++,e.consume(s),a):s===41&&n<r?i(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(su,t,i)(s):s===null||ue(s)||Et(s)?t(s):(e.consume(s),a)}function i(s){return s===41&&n++,e.consume(s),a}}function kx(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),i):o===93?(e.consume(o),a):o===60||o===null||ue(o)||Et(o)?t(o):r(o)}function a(o){return o===null||o===40||o===91||ue(o)||Et(o)?t(o):n(o)}function i(o){return Le(o)?s(o):r(o)}function s(o){return o===59?(e.consume(o),n):Le(o)?(e.consume(o),s):r(o)}}function Sx(e,t,r){return n;function n(i){return e.consume(i),a}function a(i){return Ae(i)?r(i):t(i)}}function uu(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||ue(e)}function cu(e){return!Le(e)}function du(e){return!(e===47||Ga(e))}function Ga(e){return e===43||e===45||e===46||e===95||Ae(e)}function Xa(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 _x={tokenize:Nx,partial:!0};function Tx(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Ax,continuation:{tokenize:Mx},exit:Px}},text:{91:{name:"gfmFootnoteCall",tokenize:Ex},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Cx,resolveTo:Ix}}}}function Cx(e,t,r){const n=this;let a=n.events.length;const i=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let s;for(;a--;){const l=n.events[a][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=tt(n.sliceSerialize({start:s.end,end:n.now()}));return u.codePointAt(0)!==94||!i.includes(u.slice(1))?r(l):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(l),e.exit("gfmFootnoteCallLabelMarker"),t(l))}}function Ix(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 i={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},e[e.length-1][1].start)},s={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},o=[e[r+1],e[r+2],["enter",n,t],e[r+3],e[r+4],["enter",a,t],["exit",a,t],["enter",i,t],["enter",s,t],["exit",s,t],["exit",i,t],e[e.length-2],e[e.length-1],["exit",n,t]];return e.splice(r,e.length-r+1,...o),e}function Ex(e,t,r){const n=this,a=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let i=0,s;return o;function o(d){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),l}function l(d){return d!==94?r(d):(e.enter("gfmFootnoteCallMarker"),e.consume(d),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(d){if(i>999||d===93&&!s||d===null||d===91||ue(d))return r(d);if(d===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return a.includes(tt(n.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(d)}return ue(d)||(s=!0),i++,e.consume(d),d===92?c:u}function c(d){return d===91||d===92||d===93?(e.consume(d),i++,u):u(d)}}function Ax(e,t,r){const n=this,a=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let i,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",c):r(g)}function c(g){if(s>999||g===93&&!o||g===null||g===91||ue(g))return r(g);if(g===93){e.exit("chunkString");const k=e.exit("gfmFootnoteDefinitionLabelString");return i=tt(n.sliceSerialize(k)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return ue(g)||(o=!0),s++,e.consume(g),g===92?d:c}function d(g){return g===91||g===92||g===93?(e.consume(g),s++,c):c(g)}function f(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),a.includes(i)||a.push(i),ee(e,h,"gfmFootnoteDefinitionWhitespace")):r(g)}function h(g){return t(g)}}function Mx(e,t,r){return e.check(yr,t,e.attempt(_x,t,r))}function Px(e){e.exit("gfmFootnoteDefinition")}function Nx(e,t,r){const n=this;return ee(e,a,"gfmFootnoteDefinitionIndent",5);function a(i){const s=n.events[n.events.length-1];return s&&s[1].type==="gfmFootnoteDefinitionIndent"&&s[2].sliceSerialize(s[1],!0).length===4?t(i):r(i)}}function Lx(e){let r=(e||{}).singleTilde;const n={name:"strikethrough",tokenize:i,resolveAll:a};return r==null&&(r=!0),{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function a(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 c={type:"strikethrough",start:Object.assign({},s[u][1].start),end:Object.assign({},s[l][1].end)},d={type:"strikethroughText",start:Object.assign({},s[u][1].end),end:Object.assign({},s[l][1].start)},f=[["enter",c,o],["enter",s[u][1],o],["exit",s[u][1],o],["enter",d,o]],h=o.parser.constructs.insideSpan.null;h&&Ue(f,f.length,0,nn(h,s.slice(u+1,l),o)),Ue(f,f.length,0,[["exit",d,o],["enter",s[l][1],o],["exit",s[l][1],o],["exit",c,o]]),Ue(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 i(s,o,l){const u=this.previous,c=this.events;let d=0;return f;function f(g){return u===126&&c[c.length-1][1].type!=="characterEscape"?l(g):(s.enter("strikethroughSequenceTemporary"),h(g))}function h(g){const k=Vt(u);if(g===126)return d>1?l(g):(s.consume(g),d++,h);if(d<2&&!r)return l(g);const w=s.exit("strikethroughSequenceTemporary"),b=Vt(g);return w._open=!b||b===2&&!!k,w._close=!k||k===2&&!!b,o(g)}}}class Dx{constructor(){this.map=[]}add(t,r,n){Ox(this,t,r,n)}consume(t){if(this.map.sort(function(i,s){return i[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 a=n.pop();for(;a;){for(const i of a)t.push(i);a=n.pop()}this.map.length=0}}function Ox(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 Fx(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 i=n.length-1;n[i]=n[i]==="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 Bx(){return{flow:{null:{name:"table",tokenize:zx,resolveAll:Rx}}}}function zx(e,t,r){const n=this;let a=0,i=0,s;return o;function o(S){let N=n.events.length-1;for(;N>-1;){const z=n.events[N][1].type;if(z==="lineEnding"||z==="linePrefix")N--;else break}const M=N>-1?n.events[N][1].type:null,J=M==="tableHead"||M==="tableRow"?_:l;return J===_&&n.parser.lazy[n.now().line]?r(S):J(S)}function l(S){return e.enter("tableHead"),e.enter("tableRow"),u(S)}function u(S){return S===124||(s=!0,i+=1),c(S)}function c(S){return S===null?r(S):W(S)?i>1?(i=0,n.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(S),e.exit("lineEnding"),h):r(S):Q(S)?ee(e,c,"whitespace")(S):(i+=1,s&&(s=!1,a+=1),S===124?(e.enter("tableCellDivider"),e.consume(S),e.exit("tableCellDivider"),s=!0,c):(e.enter("data"),d(S)))}function d(S){return S===null||S===124||ue(S)?(e.exit("data"),c(S)):(e.consume(S),S===92?f:d)}function f(S){return S===92||S===124?(e.consume(S),d):d(S)}function h(S){return n.interrupt=!1,n.parser.lazy[n.now().line]?r(S):(e.enter("tableDelimiterRow"),s=!1,Q(S)?ee(e,g,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(S):g(S))}function g(S){return S===45||S===58?w(S):S===124?(s=!0,e.enter("tableCellDivider"),e.consume(S),e.exit("tableCellDivider"),k):F(S)}function k(S){return Q(S)?ee(e,w,"whitespace")(S):w(S)}function w(S){return S===58?(i+=1,s=!0,e.enter("tableDelimiterMarker"),e.consume(S),e.exit("tableDelimiterMarker"),b):S===45?(i+=1,b(S)):S===null||W(S)?B(S):F(S)}function b(S){return S===45?(e.enter("tableDelimiterFiller"),I(S)):F(S)}function I(S){return S===45?(e.consume(S),I):S===58?(s=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(S),e.exit("tableDelimiterMarker"),T):(e.exit("tableDelimiterFiller"),T(S))}function T(S){return Q(S)?ee(e,B,"whitespace")(S):B(S)}function B(S){return S===124?g(S):S===null||W(S)?!s||a!==i?F(S):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(S)):F(S)}function F(S){return r(S)}function _(S){return e.enter("tableRow"),$(S)}function $(S){return S===124?(e.enter("tableCellDivider"),e.consume(S),e.exit("tableCellDivider"),$):S===null||W(S)?(e.exit("tableRow"),t(S)):Q(S)?ee(e,$,"whitespace")(S):(e.enter("data"),R(S))}function R(S){return S===null||S===124||ue(S)?(e.exit("data"),$(S)):(e.consume(S),S===92?j:R)}function j(S){return S===92||S===124?(e.consume(S),R):R(S)}}function Rx(e,t){let r=-1,n=!0,a=0,i=[0,0,0,0],s=[0,0,0,0],o=!1,l=0,u,c,d;const f=new Dx;for(;++r<e.length;){const h=e[r],g=h[1];h[0]==="enter"?g.type==="tableHead"?(o=!1,l!==0&&(hu(f,t,l,u,c),c=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,d=void 0,i=[0,0,0,0],s=[0,r+1,0,0],o&&(o=!1,c={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(r,0,[["enter",c,t]])),a=g.type==="tableDelimiterRow"?2:c?3:1):a&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(n=!1,s[2]===0&&(i[1]!==0&&(s[0]=s[1],d=mn(f,t,i,a,void 0,d),i=[0,0,0,0]),s[2]=r)):g.type==="tableCellDivider"&&(n?n=!1:(i[1]!==0&&(s[0]=s[1],d=mn(f,t,i,a,void 0,d)),i=s,s=[i[1],r,0,0])):g.type==="tableHead"?(o=!0,l=r):g.type==="tableRow"||g.type==="tableDelimiterRow"?(l=r,i[1]!==0?(s[0]=s[1],d=mn(f,t,i,a,r,d)):s[1]!==0&&(d=mn(f,t,s,a,r,d)),a=0):a&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(s[3]=r)}for(l!==0&&hu(f,t,l,u,c),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=Fx(t.events,r))}return e}function mn(e,t,r,n,a,i){const s=n===1?"tableHeader":n===2?"tableDelimiter":"tableData",o="tableContent";r[0]!==0&&(i.end=Object.assign({},Jt(t.events,r[0])),e.add(r[0],0,[["exit",i,t]]));const l=Jt(t.events,r[1]);if(i={type:s,start:Object.assign({},l),end:Object.assign({},l)},e.add(r[1],0,[["enter",i,t]]),r[2]!==0){const u=Jt(t.events,r[2]),c=Jt(t.events,r[3]),d={type:o,start:Object.assign({},u),end:Object.assign({},c)};if(e.add(r[2],0,[["enter",d,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,k=r[3]-r[2]-1;e.add(g,k,[])}}e.add(r[3]+1,0,[["exit",d,t]])}return a!==void 0&&(i.end=Object.assign({},Jt(t.events,a)),e.add(a,0,[["exit",i,t]]),i=void 0),i}function hu(e,t,r,n,a){const i=[],s=Jt(t.events,r);a&&(a.end=Object.assign({},s),i.push(["exit",a,t])),n.end=Object.assign({},s),i.push(["exit",n,t]),e.add(r+1,0,i)}function Jt(e,t){const r=e[t],n=r[0]==="enter"?"start":"end";return r[1][n]}const jx={name:"tasklistCheck",tokenize:Ux};function $x(){return{text:{91:jx}}}function Ux(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"),i)}function i(l){return ue(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):Q(l)?e.check({tokenize:Hx},t,r)(l):r(l)}}function Hx(e,t,r){return ee(e,n,"whitespace");function n(a){return a===null?r(a):t(a)}}function qx(e){return Uo([mx(),Tx(),Lx(e),Bx(),$x()])}const Vx={};function Wx(e){const t=this,r=e||Vx,n=t.data(),a=n.micromarkExtensions||(n.micromarkExtensions=[]),i=n.fromMarkdownExtensions||(n.fromMarkdownExtensions=[]),s=n.toMarkdownExtensions||(n.toMarkdownExtensions=[]);a.push(qx(r)),i.push(dx()),s.push(hx(r))}function xe(...e){return e.filter(Boolean).join(" ")}const Jx=({content:e})=>p.jsx(Bb,{remarkPlugins:[Wx],className:"cuadra-aui-md",components:Gx,children:e}),Qa=y.memo(Jx),Kx=({language:e,code:t})=>{const{isCopied:r,copyToClipboard:n}=Yx(),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(Fu,{className:"cuadra-h-4 cuadra-w-4"}),r&&p.jsx(Du,{className:"cuadra-h-4 cuadra-w-4"})]})]})},Yx=({copiedDuration:e=3e3}={})=>{const[t,r]=y.useState(!1);return{isCopied:t,copyToClipboard:a=>{a&&navigator.clipboard.writeText(a).then(()=>{r(!0),setTimeout(()=>r(!1),e)})}}},Gx=vb({h1:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("h1",m({className:xe("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=V(n,["className"]);return p.jsx("h2",m({className:xe("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=V(n,["className"]);return p.jsx("h3",m({className:xe("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=V(n,["className"]);return p.jsx("h4",m({className:xe("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=V(n,["className"]);return p.jsx("h5",m({className:xe("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=V(n,["className"]);return p.jsx("h6",m({className:xe("cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand",e)},t))},p:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("p",m({className:xe("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=V(n,["className"]);return p.jsx("a",m({className:xe("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=V(n,["className"]);return p.jsx("blockquote",m({className:xe("cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand",e)},t))},ul:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("ul",m({className:xe("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=V(n,["className"]);return p.jsx("ol",m({className:xe("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=V(n,["className"]);return p.jsx("hr",m({className:xe("cuadra-my-5 cuadra-border-b",e)},t))},table:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("table",m({className:xe("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=V(n,["className"]);return p.jsx("th",m({className:xe("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=V(n,["className"]);return p.jsx("td",m({className:xe("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=V(n,["className"]);return p.jsx("tr",m({className:xe("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=V(n,["className"]);return p.jsx("sup",m({className:xe("[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand",e)},t))},pre:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("pre",m({className:xe("cuadra-overflow-x-auto 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=V(a,["className"]);const i=Nl();return p.jsx("code",m({className:xe(!i&&"cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand",t)},r))},CodeHeader:Kx});function fu(n){var a=n,{className:e="",variant:t="default"}=a,r=V(a,["className","variant"]);const i="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:`${i} ${s[t]||s.default} ${e}`},r))}function Xx(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 Qx({sources:e,maxVisible:t=3}){if(!e||e.length===0)return null;const r=Xx(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(si,{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((i,s)=>p.jsx(ev,{source:i},i.sourceId||s)),a>0&&p.jsxs(fu,{variant:"subtle",children:["+",a," more"]})]})]})}function Zx(e){var r;switch((r=e.split(".").pop())==null?void 0:r.toLowerCase()){case"csv":case"xlsx":case"xls":return zu;case"md":case"txt":return Ru;default:return si}}function ev({source:e}){const{filename:t,score:r}=e,n=Zx(t);return p.jsxs(fu,{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 pu=y.forwardRef(function({welcomeTitle:t="Hi, how can I help you today?",welcomeSubtitle:r="Start exploring our platform and discover what you can build.",extraTopPadding:n,suggestions:a,inputPlaceholder:i="Type your message...",enableAttachments:s=!1,preMadeResponseDelay:o=1e3,streamingSpeed:l=50},u){const c=ss(),d=he(),[f,h]=y.useState(!1),[g,k]=y.useState(null),[w,b]=y.useState(!1),I=y.useCallback((_,$,R)=>{var j,S;if(!w)try{const N=(j=R==null?void 0:R.streamingSpeed)!=null?j:l,M=(S=R==null?void 0:R.delay)!=null?S:o;up(_,$,N,M),d.composer().setText(_),setTimeout(()=>{d.composer().send()},10)}catch(N){}},[w,l,o,d]),T=y.useCallback(_=>{try{d.composer().setText(_),setTimeout(()=>{d.composer().send()},10)}catch($){}},[d]),B=y.useCallback(_=>P(null,null,function*(){var $;if(!(w||!c))try{if(_.response){const R=($=_.responseDelay)!=null?$:o;yield I(_.prompt,_.response,{delay:R,streamingSpeed:l})}else T(_.prompt)}catch(R){}}),[c,w,o,l,I,T]),F=y.useCallback(()=>{try{const _=window.__cuadraThreadListRuntime;_!=null&&_.switchToNewThread&&_.switchToNewThread()}catch(_){}},[]);return y.useImperativeHandle(u,()=>({sendMessage:T,sendPreMadeQA:I,clearChat:F}),[T,I,F]),y.useEffect(()=>{var _,$;if(!c){h(!1);return}try{const R=c==null?void 0:c.store;if(!R){h(!1);return}const j=(_=R.subscribe)==null?void 0:_.call(R,N=>{const M=N==null?void 0:N.threadId,J=(N==null?void 0:N.messages)||[],z=(N==null?void 0:N.isLoadingHistory)||!1,D=J.length;M&&M!==g&&k(M),h(z&&D===0)}),S=($=R.getState)==null?void 0:$.call(R);if(S){const N=S==null?void 0:S.threadId,M=(S==null?void 0:S.messages)||[],J=(S==null?void 0:S.isLoadingHistory)||!1,z=M.length;N&&N!==g&&k(N),h(J&&z===0)}return()=>{j&&j()}}catch(R){h(!1)}},[c,g]),p.jsxs(Xs,{className:"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full",children:[p.jsx(eo,{className:"cuadra-w-full cuadra-bg-inherit cuadra-px-4 cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto cuadra-relative scrollbar-thin cuadra-pt-4",style:n?{paddingTop:n}:void 0,children:f?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-2",children:[p.jsx(oi,{className:"cuadra-h-6 cuadra-w-6 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(p.Fragment,{children:[p.jsx(Qs,{children:p.jsx(tv,{title:t,subtitle:r,suggestions:a,onSuggestionClick:B,isProcessing:w})}),p.jsx(Zf,{components:{UserMessage:rv,AssistantMessage:iv}})]})}),p.jsxs("div",{className:"cuadra-w-full cuadra-mt-3 cuadra-border-t cuadra-border-border cuadra-pt-4",children:[s&&p.jsx(Gs,{components:{Attachment:()=>{const _=re(({attachment:$})=>$);return _?p.jsxs("div",{className:"cuadra-relative cuadra-inline-flex cuadra-items-center cuadra-gap-2 cuadra-mb-2 cuadra-px-2 cuadra-py-1 cuadra-rounded-md cuadra-bg-muted cuadra-border cuadra-border-border",children:[p.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground font-brand",children:_.name||"Attachment"}),p.jsx(lf,{asChild:!0,children:p.jsx("button",{type:"button",className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-4 cuadra-rounded hover:cuadra-bg-background cuadra-transition-colors","aria-label":"Remove attachment",children:p.jsx(Tn,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})})]}):null}}}),p.jsxs($s,{className:"cuadra-relative !cuadra-relative cuadra-flex-1 cuadra-w-full",children:[p.jsx(Ks,{asChild:!0,children:p.jsx("textarea",{rows:3,placeholder:i,className:"cuadra-flex cuadra-min-h-[80px] cuadra-w-full cuadra-rounded-md cuadra-border cuadra-border-border cuadra-bg-background cuadra-px-3 cuadra-py-2 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:{paddingRight:s?"5rem":"3rem",fontSize:"1rem",borderWidth:"1px"}})}),s&&p.jsx(qf,{multiple:!0,asChild:!0,children:p.jsx("button",{type:"button",className:"!cuadra-absolute !cuadra-bottom-2 !cuadra-right-12 cuadra-size-8 cuadra-rounded-md hover:cuadra-bg-muted cuadra-transition-colors cuadra-flex cuadra-items-center cuadra-justify-center cuadra-border cuadra-border-border",style:{position:"absolute",bottom:"0.5rem",right:"3rem"},"aria-label":"Attach file",children:p.jsx(li,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground",strokeWidth:1.5})})}),p.jsx(Tf,{asChild:!0,children:p.jsx("button",{className:"!cuadra-absolute !cuadra-bottom-2 !cuadra-right-2 cuadra-size-8 cuadra-rounded-md cuadra-shadow-sm hover:cuadra-opacity-90 disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed cuadra-flex cuadra-items-center cuadra-justify-center",style:{position:"absolute",bottom:"0.5rem",right:"0.5rem",backgroundColor:"var(--cuadra-primary)",color:"hsl(var(--cuadra-primary-foreground))"},"aria-label":"Send message",type:"button",children:p.jsx(Nu,{className:"cuadra-h-4 cuadra-w-4"})})})]})]})]})});function tv({title:e,subtitle:t,suggestions:r,onSuggestionClick:n,isProcessing:a}){return p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-h-full cuadra-py-12 cuadra-px-4 cuadra-overflow-y-auto scrollbar-hide",children:p.jsxs("div",{className:"cuadra-text-center cuadra-max-w-3xl cuadra-w-full cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-min-h-full",children:[p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-mb-8",children:[p.jsx("h2",{className:"cuadra-text-lg cuadra-font-normal cuadra-text-foreground cuadra-mb-2 font-brand",children:e}),p.jsx("p",{className:"cuadra-text-muted-foreground font-brand",children:t})]}),r&&r.length>0&&p.jsx("div",{className:"cuadra-grid cuadra-grid-cols-2 cuadra-gap-2 cuadra-pb-4 cuadra-w-full cuadra-max-w-2xl",children:r.map((i,s)=>p.jsx("button",{type:"button",onClick:()=>n(i),disabled:a,className:"cuadra-w-full cuadra-text-center cuadra-px-4 cuadra-py-3 cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-bg-background cuadra-text-sm cuadra-text-foreground font-brand cuadra-cursor-pointer focus:cuadra-outline-none focus:cuadra-ring-0 disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed",style:{borderWidth:"1px"},children:i.prompt},`suggestion-${s}`))})]})})}function rv(){return p.jsxs(Qn,{className:"cuadra-grid cuadra-w-full cuadra-auto-rows-auto cuadra-grid-cols-[minmax(72px,1fr)_auto] cuadra-gap-y-2 cuadra-py-3 [&:where(>*)]:cuadra-col-start-2",children:[p.jsx(Rs,{components:{Attachment:()=>{var i;const e=re(({attachment:s})=>s);if(!e)return null;const t=e.type==="image",r=e.file,n=(i=e.content)==null?void 0:i.find(s=>s.type==="image"),a=r?URL.createObjectURL(r):n==null?void 0:n.image;return p.jsx("div",{className:"cuadra-col-start-2 cuadra-row-start-1 cuadra-mb-2 cuadra-max-w-[calc(42rem*0.8)]",children:t&&a?p.jsx("img",{src:a,alt:e.name||"Attachment",className:"cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-max-h-64 cuadra-max-w-full cuadra-object-contain",style:{borderWidth:"1px"}}):p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-bg-muted cuadra-px-3 cuadra-py-2",children:[p.jsx(li,{className:"cuadra-h-4 cuadra-w-4 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-bg-muted cuadra-text-foreground cuadra-col-start-2 cuadra-row-start-2 cuadra-max-w-[calc(42rem*0.8)] cuadra-break-words cuadra-rounded-3xl cuadra-border cuadra-border-border cuadra-px-5 cuadra-py-2.5 font-brand",style:{maxWidth:"calc(42rem * 0.8)",borderRadius:"1.5rem",backgroundColor:"var(--cuadra-muted)",color:"hsl(var(--cuadra-foreground))",paddingLeft:"1.25rem",paddingRight:"1.25rem",paddingTop:"0.625rem",paddingBottom:"0.625rem",wordBreak:"break-word",borderWidth:"1px"},children:p.jsx(Zn,{components:{Text:({text:e})=>p.jsx(Qa,{content:e||""})}})})]})}function nv({text:e}){const[t,r]=y.useState(!0);return e?p.jsxs("div",{className:"cuadra-mb-3 cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-bg-muted/50 cuadra-overflow-hidden",children:[p.jsxs("button",{type:"button",onClick:()=>r(!t),className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-px-3 cuadra-py-2 cuadra-text-left cuadra-text-sm cuadra-text-muted-foreground hover:cuadra-bg-muted/80 cuadra-transition-colors font-brand",children:[p.jsx(_n,{className:`cuadra-h-4 cuadra-w-4 cuadra-shrink-0 cuadra-transition-transform ${t?"":"cuadra--rotate-90"}`}),p.jsx(Lu,{className:"cuadra-h-4 cuadra-w-4 cuadra-shrink-0"}),p.jsx("span",{children:"Reasoning"})]}),t&&p.jsx("div",{className:"cuadra-px-3 cuadra-pb-3 cuadra-pt-1 cuadra-border-t cuadra-border-border",children:p.jsx("div",{className:"cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand",children:p.jsx(Qa,{content:e})})})]}):null}function av(){return p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-text-muted-foreground cuadra-text-sm font-brand cuadra-py-2",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-bg-current cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"0ms"}}),p.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-bg-current cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"150ms"}}),p.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-bg-current cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"300ms"}})]}),p.jsx("span",{children:"Thinking..."})]})}function iv(){const[e]=y.useState(()=>Ct.getCurrentMessageId()),t=re(({message:a})=>{var i;return((i=a==null?void 0:a.status)==null?void 0:i.type)==="running"}),r=re(({message:a})=>{const i=a==null?void 0:a.content;return!i||!Array.isArray(i)?!1:i.some(s=>!!(s.type==="text"&&s.text&&s.text.length>0||s.type==="reasoning"&&s.text&&s.text.length>0))}),n=y.useSyncExternalStore(a=>Ct.subscribe(a),()=>{var a;if(e){const i=Ct.getForMessage(e);if((a=i.sources)!=null&&a.length)return i.sources}return Ct.get().sources||null},()=>null);return p.jsx(Qn,{className:"cuadra-relative cuadra-grid cuadra-w-full cuadra-grid-cols-[auto_auto_1fr] cuadra-grid-rows-[auto_1fr] cuadra-py-3",children:p.jsxs("div",{className:"cuadra-text-foreground cuadra-col-span-2 cuadra-col-start-2 cuadra-row-start-1 cuadra-my-1.5 cuadra-max-w-[90%] cuadra-break-words cuadra-leading-7 font-brand",style:{maxWidth:"90%",marginTop:"0.375rem",marginBottom:"0.375rem"},children:[p.jsx(Zn,{components:{Text:({text:a})=>p.jsx(Qa,{content:a||""}),Reasoning:({text:a})=>p.jsx(nv,{text:a||""})}}),t&&!r&&p.jsx(av,{}),n&&n.length>0&&p.jsx(Qx,{sources:n})]})})}const mu=({className:e="",theme:t="system"})=>{const r=()=>{if(typeof window=="undefined")return"light";if(t==="system"){const s=localStorage.getItem("theme");return s||(window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light")}return t},[n,a]=y.useState(r);y.useEffect(()=>{t!=="system"&&a(t)},[t]),y.useEffect(()=>{const s=document.documentElement;s.classList.remove("light","dark"),s.classList.add(n),t==="system"&&localStorage.setItem("theme",n)},[n,t]);const i=()=>{t==="system"&&a(s=>s==="light"?"dark":"light")};return p.jsx("button",{type:"button","aria-label":"Toggle theme",onClick:i,disabled:t!=="system",className:`cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed ${e}`,children:p.jsx(Ou,{className:`cuadra-h-4 cuadra-w-4 cuadra-transition-colors ${n==="dark"?"cuadra-text-primary":"cuadra-text-gray-400"}`})})};function sv({onThreadSelect:e}){var w,b;const t=os(),r=Vd(I=>I.threadId),[n,a]=y.useState(null),i=(t==null?void 0:t.id)===r,s=n===(t==null?void 0:t.id),[o,l]=y.useState(!1),[u,c]=y.useState((t==null?void 0:t.title)||""),[d,f]=y.useState(!1),[h,g]=y.useState(!1),k=()=>P(null,null,function*(){if(!(t!=null&&t.remoteId)||!u||u===t.title){l(!1);return}try{g(!0);const I=window.__cuadraThreadListAdapter;I&&typeof I.rename=="function"&&(yield I.rename(t.remoteId,u)),l(!1),f(!1)}catch(I){l(!1),f(!1)}finally{g(!1)}});return y.useEffect(()=>{t!=null&&t.title&&!o&&c(t.title)},[t==null?void 0:t.title,o]),t?p.jsxs(lo,{className:`group cuadra-relative cuadra-flex cuadra-items-center cuadra-rounded-lg cuadra-transition-colors cuadra-cursor-pointer cuadra-border cuadra-mb-2 ${i?"cuadra-bg-muted cuadra-border-border":"cuadra-border-transparent hover:cuadra-bg-muted hover:cuadra-border-border"}`,style:{marginBottom:"0.5rem"},onMouseEnter:()=>a(t.id),onMouseLeave:()=>a(null),children:[p.jsx(np,{className:"cuadra-p-3 cuadra-flex-1 cuadra-flex cuadra-items-center cuadra-min-w-0 cuadra-cursor-pointer",onClick:()=>e==null?void 0:e(),children:p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-min-w-0 cuadra-flex-1 cuadra-items-start cuadra-text-left",children:o?p.jsx("input",{className:"cuadra-flex cuadra-w-full cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus-visible:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 font-brand",value:u,onChange:I=>c(I.target.value),onKeyDown:I=>{I.key==="Enter"&&k(),I.key==="Escape"&&(l(!1),c(t.title||""))},disabled:h,autoFocus:!0,onClick:I=>I.stopPropagation()}):p.jsxs(p.Fragment,{children:[p.jsx("span",{className:"cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-truncate font-brand",children:(((w=t.title)==null?void 0:w.length)||0)>60?`${(b=t.title)==null?void 0:b.slice(0,60)}…`:t.title||"Chat"}),t.updatedAt&&p.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground cuadra-mt-1 font-brand",children:new Date(t.updatedAt).toLocaleDateString()})]})})}),p.jsx("div",{className:"cuadra-mr-2 cuadra-flex-shrink-0 cuadra-w-6 cuadra-h-6 cuadra-flex cuadra-items-center cuadra-justify-center",children:(s||i||d)&&p.jsxs("div",{className:"cuadra-relative",children:[p.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-background/50 cuadra-transition-colors",onClick:I=>{I.stopPropagation(),f(!d)},"aria-label":"Thread options",children:p.jsx(Bu,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"})}),d&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:()=>f(!1)}),p.jsx("div",{className:"cuadra-absolute cuadra-right-0 cuadra-top-8 cuadra-z-50 cuadra-bg-background cuadra-border cuadra-border-border cuadra-rounded-lg cuadra-shadow-lg cuadra-min-w-[120px] cuadra-overflow-hidden",children:o?p.jsx("button",{type:"button",className:"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:I=>{I.stopPropagation(),k()},disabled:h,children:"Save"}):p.jsxs(p.Fragment,{children:[p.jsx("button",{type:"button",className:"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:I=>{I.stopPropagation(),l(!0),c(t.title||""),f(!1)},children:"Rename"}),p.jsx("div",{className:"cuadra-border-t cuadra-border-border"}),p.jsx(tp,{asChild:!0,children:p.jsx("button",{type:"button",className:"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left cuadra-text-destructive hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:I=>{I.stopPropagation(),f(!1)},children:"Delete"})})]})})]})]})})]}):null}function gu({onThreadSelect:e,showThemeToggle:t,theme:r,onLogout:n}){return p.jsxs(oo,{className:"!cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-full cuadra-w-80",style:{borderRightWidth:"1px"},children:[p.jsx("div",{className:"cuadra-border-b cuadra-border-border cuadra-flex cuadra-items-center cuadra-justify-end cuadra-transition-all cuadra-duration-300 cuadra-h-16 cuadra-px-4",children:p.jsx("button",{type:"button",onClick:e,className:"cuadra-flex md:cuadra-hidden cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors","aria-label":"Close",children:p.jsx(Tn,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})})}),p.jsxs("div",{className:"cuadra-flex-1 cuadra-overflow-y-auto cuadra-p-2 scrollbar-thin",children:[p.jsx(ao,{className:"group cuadra-relative cuadra-flex cuadra-items-center cuadra-gap-3 cuadra-p-3 cuadra-rounded-lg cuadra-cursor-pointer cuadra-transition-colors cuadra-border cuadra-border-transparent hover:cuadra-bg-muted hover:cuadra-border-border",onClick:()=>e==null?void 0:e(),children:p.jsx("div",{className:"cuadra-flex-1 cuadra-min-w-0",children:p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[p.jsx(Uu,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),p.jsx("h4",{className:"cuadra-text-sm cuadra-font-normal cuadra-text-foreground font-brand",children:"New Chat"})]})})}),p.jsx("div",{className:"cuadra-my-2 cuadra-border-t cuadra-border-border"}),p.jsx(so,{components:{ThreadListItem:a=>p.jsx(sv,E(m({},a),{onThreadSelect:e}))}})]}),(t||n)&&p.jsxs("div",{className:"cuadra-border-t cuadra-border-border cuadra-flex md:cuadra-hidden cuadra-items-center cuadra-justify-between cuadra-px-4 cuadra-py-4",children:[n&&p.jsx("button",{type:"button",onClick:n,className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors","aria-label":"Logout",children:p.jsx(ju,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})}),t&&p.jsx(mu,{theme:r})]})]})}const ov=`
36
36
  @keyframes rotate {
37
37
  100% { transform: rotate(1turn); }
38
38
  }
39
- `,Xa=({children:e,className:t="",paddingX:r="px-0",paddingY:n="py-0",borderSizePx:a=4,style:i,contentStyle:s,rotating:o=!1})=>p.jsxs(p.Fragment,{children:[p.jsx("style",{children:Qx}),p.jsxs("div",{className:`cuadra-relative cuadra-bg-background md:cuadra-rounded-xl cuadra-overflow-hidden ${t}`,style:m({padding:a},i),children:[p.jsx("div",{className:`cuadra-absolute md:cuadra-rounded-xl cuadra-textured-card-border ${o?"cuadra-textured-card-border-rotating":""}`,style:o?{left:"-100%",top:"-100%",width:"300%",height:"300%",backgroundRepeat:"no-repeat",backgroundSize:"cover",backgroundPosition:"center",animation:"rotate 4s linear infinite"}:{backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",top:"0",left:"0",width:"100%",height:"100%"}}),p.jsx("div",{className:`cuadra-relative cuadra-bg-background cuadra-h-full cuadra-z-10 cuadra-flex cuadra-flex-col cuadra-overflow-hidden ${r} ${n}`,style:m({borderRadius:"calc(0.75rem - 4px)"},s),children:e})]})]}),gu=({currentModel:e,models:t,modelsLoading:r,modelsError:n,onModelChange:a,hideModelSelector:i=!1,showThemeToggle:s=!0,theme:o="system",onMobileMenuClick:l,showMobileMenuButton:u=!1})=>{const[d,c]=g.useState(!1),[f,h]=g.useState(!1),y=g.useRef(null);g.useEffect(()=>{const b=_=>{y.current&&!y.current.contains(_.target)&&c(!1)};return d&&document.addEventListener("mousedown",b),()=>{document.removeEventListener("mousedown",b)}},[d]);const S=t.find(b=>b.id===e),x=b=>{a(b),c(!1),h(!1)};return p.jsxs("div",{className:"cuadra-h-16 cuadra-px-4 cuadra-border-b cuadra-border-border cuadra-flex cuadra-items-center cuadra-justify-between cuadra-bg-background",children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[u&&p.jsx("button",{type:"button",onClick:l,className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed md:cuadra-hidden","aria-label":"Toggle thread list",children:p.jsx(Bu,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})}),s&&p.jsx("div",{className:"cuadra-hidden md:cuadra-flex cuadra-items-center cuadra-gap-2",children:p.jsx(pu,{theme:o})})]}),p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 md:cuadra-ml-0 cuadra-ml-auto",children:[!i&&p.jsx("label",{className:"cuadra-hidden md:cuadra-inline cuadra-text-sm cuadra-text-muted-foreground cuadra-font-brand",children:"Model"}),i?null:r?p.jsx("div",{className:"cuadra-w-48 cuadra-rounded-md cuadra-border cuadra-border-border cuadra-px-3 cuadra-py-2 cuadra-bg-muted",children:p.jsx("span",{className:"cuadra-text-muted-foreground cuadra-text-sm cuadra-font-brand",children:"Loading..."})}):n?p.jsx("div",{className:"cuadra-w-48 cuadra-rounded-md cuadra-border cuadra-border-destructive cuadra-px-3 cuadra-py-2 cuadra-bg-destructive/10",children:p.jsx("span",{className:"cuadra-text-destructive cuadra-text-sm cuadra-font-brand",children:"Failed to load models"})}):p.jsxs(p.Fragment,{children:[p.jsxs("div",{ref:y,className:"cuadra-hidden md:cuadra-block cuadra-relative cuadra-w-48",children:[p.jsxs("button",{type:"button",onClick:()=>c(!d),disabled:r||t.length===0||!!n,className:"cuadra-flex cuadra-h-10 cuadra-w-full cuadra-items-center cuadra-justify-between cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-font-brand",children:[p.jsx("span",{className:S?"cuadra-text-foreground":"cuadra-text-muted-foreground",children:(S==null?void 0:S.name)||"Select model"}),p.jsx(ni,{className:"cuadra-ml-2 cuadra-h-4 cuadra-w-4 cuadra-opacity-50"})]}),d&&t.length>0&&p.jsx("div",{className:"cuadra-absolute cuadra-z-50 cuadra-mt-1 cuadra-w-full cuadra-min-w-[8rem] cuadra-overflow-hidden cuadra-rounded-md glass-popover cuadra-text-popover-foreground cuadra-animate-in fade-in-80 cuadra-border cuadra-border-border cuadra-bg-popover cuadra-shadow-md",children:p.jsx("div",{className:"cuadra-p-1",children:t.map(b=>p.jsxs("button",{type:"button",onClick:()=>x(b.id),className:`cuadra-relative cuadra-flex cuadra-w-full cuadra-cursor-pointer cuadra-select-none cuadra-items-center cuadra-rounded-sm cuadra-py-1.5 cuadra-pl-8 cuadra-pr-2 cuadra-text-sm cuadra-outline-none focus:cuadra-bg-secondary focus:cuadra-text-secondary-foreground font-brand cuadra-transition-colors ${e===b.id?"cuadra-bg-secondary cuadra-text-secondary-foreground":"hover:cuadra-bg-secondary/50"}`,children:[e===b.id&&p.jsx("span",{className:"cuadra-absolute cuadra-left-2 cuadra-flex cuadra-h-3.5 cuadra-w-3.5 cuadra-items-center cuadra-justify-center",children:p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",fill:"none",viewBox:"0 0 16 16",children:p.jsx("path",{fill:"currentColor",fillRule:"evenodd",d:"M6.47 10.03a.75.75 0 0 1-1.06-1.06l2-2a.75.75 0 0 1 1.06 0l2 2a.75.75 0 1 1-1.06 1.06L8 9.06l-1.53 1.53Z",clipRule:"evenodd"})})}),p.jsx("span",{children:b.name})]},b.id))})})]}),p.jsxs("button",{type:"button",onClick:()=>h(!0),disabled:r||t.length===0||!!n,className:"cuadra-flex md:cuadra-hidden cuadra-h-10 cuadra-w-full cuadra-items-center cuadra-justify-between cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-font-brand",children:[p.jsx("span",{className:S?"cuadra-text-foreground":"cuadra-text-muted-foreground",children:(S==null?void 0:S.name)||"Select model"}),p.jsx(ni,{className:"cuadra-ml-2 cuadra-h-4 cuadra-w-4 cuadra-opacity-50"})]}),f&&typeof document!="undefined"&&Le.createPortal(p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-bg-black/50 cuadra-z-50 md:cuadra-hidden",onClick:()=>h(!1)}),p.jsxs("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-50 cuadra-flex cuadra-flex-col cuadra-bg-background md:cuadra-hidden",children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-border-b cuadra-border-border cuadra-px-4 cuadra-py-4",children:[p.jsx("h2",{className:"cuadra-text-lg cuadra-font-normal cuadra-text-foreground font-brand",children:"Select Model"}),p.jsx("button",{type:"button",onClick:()=>h(!1),className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors","aria-label":"Close",children:p.jsx(_n,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})})]}),p.jsx("div",{className:"cuadra-flex-1 cuadra-overflow-y-auto cuadra-p-4",children:r?p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-py-8",children:p.jsx("span",{className:"cuadra-text-muted-foreground cuadra-text-sm cuadra-font-brand",children:"Loading models..."})}):n?p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-py-8",children:p.jsx("span",{className:"cuadra-text-destructive cuadra-text-sm cuadra-font-brand",children:"Failed to load models"})}):t.length===0?p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-py-8",children:p.jsx("span",{className:"cuadra-text-muted-foreground cuadra-text-sm cuadra-font-brand",children:"No models available"})}):p.jsx("div",{className:"cuadra-space-y-2",children:t.map(b=>p.jsxs("button",{type:"button",onClick:()=>x(b.id),className:`cuadra-w-full cuadra-flex cuadra-items-center cuadra-justify-between cuadra-rounded-lg cuadra-border cuadra-px-4 cuadra-py-4 cuadra-text-left cuadra-transition-colors font-brand cuadra-bg-background cuadra-text-foreground cuadra-border-border hover:cuadra-bg-muted ${e===b.id?"cuadra-border-primary":""}`,children:[p.jsx("span",{className:"cuadra-text-base cuadra-font-normal",children:b.name}),e===b.id&&p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",fill:"none",viewBox:"0 0 20 20",className:"cuadra-text-primary",children:p.jsx("path",{fill:"currentColor",fillRule:"evenodd",d:"M16.707 5.293a1 1 0 0 1 0 1.414l-8 8a1 1 0 0 1-1.414 0l-4-4a1 1 0 0 1 1.414-1.414L8 12.586l7.293-7.293a1 1 0 0 1 1.414 0Z",clipRule:"evenodd"})})]},b.id))})})]})]}),document.body)]})]})]})},Zx=g.createContext(void 0),Qa=({children:e,value:t})=>p.jsx(Zx.Provider,{value:t,children:e});function ev(){g.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:Te&&Te.tagName.toUpperCase()==="SCRIPT"&&Te.src||new URL("cuadra-uikit.umd.js",document.baseURI).href).href];let i=!1;for(const s of a)if(n.href=s,n.onload=()=>{i=!0},n.onerror=()=>{},document.head.appendChild(n),i)break},[])}const yu=g.forwardRef(function({config:t},r){ev();const n=g.useRef(null),a=g.useRef(!1),{baseUrl:i,proxyUrl:s,sessionToken:o,mode:l="multiChat",modelMode:u="fixed",modelId:d,onModelChange:c,ephemeral:f=!1,systemPrompt:h,initialThreadId:y,welcomeTitle:S,welcomeSubtitle:x,extraTopPadding:b,suggestions:_,inputPlaceholder:T,preMadeResponseDelay:L=1e3,streamingSpeed:z=50,showThemeToggle:I=!0,initialMessage:q,initialPreMadeQA:B,theme:U="system",onError:k,onChatCreated:D,onUserMessage:M,onThreadIdUpdate:H,onLogout:R,enableAttachments:F=!1,onBeforeRequest:j}=t;g.useImperativeHandle(r,()=>({sendMessage:V=>{var te;(te=n.current)==null||te.sendMessage(V)},sendPreMadeQA:(V,te,ie)=>{var He;(He=n.current)==null||He.sendPreMadeQA(V,te,ie)},clearChat:()=>{var V;(V=n.current)==null||V.clearChat()}}),[]),g.useEffect(()=>{if(a.current)return;const V=setTimeout(()=>{var te,ie;B?(a.current=!0,(te=n.current)==null||te.sendPreMadeQA(B.question,B.answer,{delay:L,streamingSpeed:z})):q&&(a.current=!0,(ie=n.current)==null||ie.sendMessage(q))},500);return()=>clearTimeout(V)},[q,B,L,z]);const[J,re]=g.useState(!1),[Z,w]=g.useState(null),[ae,xe]=g.useState(null),[v,ve]=g.useState(!1),Xe=g.useRef(null),pe=V=>{if(V<30)return!0;if(Xe.current){const te=Xe.current.getBoundingClientRect();if(V-te.left<30)return!0}return!1},gt=V=>{const ie=V.touches[0].clientX;(pe(ie)||J)&&(w(ie),xe(ie),ve(!0))},Qe=V=>{if(Z===null||!v)return;const te=V.touches[0];xe(te.clientX)},ot=()=>{if(Z===null||ae===null){ve(!1);return}const V=ae-Z,te=50,ie=.3,be=Math.abs(V)/300;V>te&&!J&&Z!==null?pe(Z)&&re(!0):((V<-te||V<0&&be>ie)&&J||J&&V<-20&&be>ie)&&re(!1),w(null),xe(null),ve(!1)},yt=()=>{if(v&&Z!==null&&ae!==null){const V=ae-Z;if(J)return`translateX(${Math.min(0,V)}px)`;if(Z!==null&&pe(Z))return`translateX(${Math.min(0,-320+V)}px)`}return J?"translateX(0)":"translateX(-100%)"},Jt=()=>{if(!v||Z===null||ae===null)return J?.5:0;const te=ae-Z;return J?Math.max(0,Math.min(1,(320+te)/320))*.5:Z!==null&&pe(Z)?Math.max(0,Math.min(1,(te+320)/320))*.5:0},Kt=s||i||"",Gt=!!s,mn=g.useMemo(()=>new oo(Kt,o||void 0,Gt),[Kt,o,Gt]),[Pe,gn]=g.useState(null),[bt,yn]=g.useState(!1),[wt,Ir]=g.useState(null),[Za,bn]=g.useState(!1);g.useEffect(()=>{l==="multiChat"&&bn(!0)},[l]);const xt=g.useCallback(()=>P(null,null,function*(){if(u==="selector"){yn(!0),Ir(null);try{const V=yield mn.listModels();gn(V)}catch(V){Ir(V instanceof Error?V:new Error("Failed to load models"))}finally{yn(!1)}}}),[mn,u]);g.useEffect(()=>{u==="selector"&&xt()},[u,xt]),g.useEffect(()=>(typeof window!="undefined"&&(window.__cuadraUIKitRefetchModels=xt),()=>{typeof window!="undefined"&&delete window.__cuadraUIKitRefetchModels}),[xt]);const[Ze,wn]=g.useState(u==="fixed"&&d||null),A=g.useRef(Ze),O=g.useCallback(V=>{const te=A.current;wn(V),A.current=V,c==null||c(V),te!==null&&te!==V&&l==="multiChat"&&setTimeout(()=>{var He,be;const ie=window.__cuadraThreadListRuntime;if((He=ie==null?void 0:ie.threads)!=null&&He.switchToNewThread)try{ie.threads.switchToNewThread()}catch(lt){}else if((be=ie==null?void 0:ie.threads)!=null&&be.createThread)try{ie.threads.createThread()}catch(lt){}else if(ie!=null&&ie.switchToNewThread)try{ie.switchToNewThread()}catch(lt){}},100)},[c,l]);g.useEffect(()=>{if(u==="selector"&&(Pe!=null&&Pe.items)&&Pe.items.length>0&&!Ze){const V=Pe.items[0];if(V!=null&&V.id){const te=V.id;wn(te),c==null||c(te)}}},[u,Pe==null?void 0:Pe.items,Ze,c]);const G=u==="fixed"?!!d:!!Ze,Q=g.useMemo(()=>((Pe==null?void 0:Pe.items)||[]).filter(V=>(V==null?void 0:V.id)&&(V==null?void 0:V.displayName)).map(V=>({id:V.id,name:V.displayName})),[Pe]),oe=g.useMemo(()=>({currentModelId:Ze||"",models:Q,modelsLoading:bt,modelsError:wt,onModelChange:O,refetchModels:xt}),[Ze,Q,bt,wt,O,xt]);return u==="selector"&&bt||l==="multiChat"&&Za?p.jsx(Qa,{value:oe,children:p.jsx(Xa,{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(ai,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"})})})}):u==="selector"&&!G&&wt?p.jsx(Qa,{value:oe,children:p.jsx(Xa,{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(Qa,{value:oe,children:p.jsx(sp,{baseUrl:Gt?Kt:i||Kt,sessionToken:o,isProxyMode:Gt,mode:l,modelMode:u,modelId:Ze||d||void 0,onModelChange:O,ephemeral:f,systemPrompt:h,initialThreadId:y,enableAttachments:F,onError:k,onChatCreated:D,onUserMessage:M,onThreadIdUpdate:H,onBeforeRequest:j,onChatsLoaded:()=>{l==="multiChat"&&bn(!1)},children:p.jsx(Xa,{paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",className:`cuadra-h-full ${t.containerClass||""}`,borderSizePx:4,style:{height:"100%"},children:p.jsx("div",{className:"cuadra-h-full cuadra-flex cuadra-relative",style:{height:"100%"},onTouchStart:gt,onTouchMove:Qe,onTouchEnd:ot,children:l==="multiChat"?p.jsxs(p.Fragment,{children:[typeof document!="undefined"&&Le.createPortal(p.jsx("div",{className:`cuadra-fixed cuadra-inset-0 cuadra-bg-black cuadra-z-40 md:cuadra-hidden cuadra-transition-opacity cuadra-duration-300 ${J||v?"":"cuadra-pointer-events-none"}`,style:{opacity:Jt()},onClick:()=>re(!1)}),document.body),typeof document!="undefined"&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-hidden md:cuadra-block !cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-full cuadra-w-80 cuadra-relative",style:{borderRightWidth:"1px",height:"100%"},children:p.jsx(mu,{onThreadSelect:()=>re(!1),showThemeToggle:I,theme:U,onLogout:R})}),typeof document!="undefined"&&Le.createPortal(p.jsx("div",{className:`cuadra-block md:cuadra-hidden !cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-h-screen cuadra-w-80 cuadra-fixed cuadra-z-50 cuadra-top-0 cuadra-left-0 ${J||v?"":"cuadra-pointer-events-none"}`,style:{borderRightWidth:"1px",transform:yt(),transition:v?"none":"transform 0.3s ease-in-out"},onTouchStart:gt,onTouchMove:Qe,onTouchEnd:ot,children:p.jsx(mu,{onThreadSelect:()=>re(!1),showThemeToggle:I,theme:U,onLogout:R})}),document.body)]}),p.jsxs("div",{ref:Xe,className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:[u==="selector"&&p.jsx(gu,{currentModel:Ze||"",models:Q,modelsLoading:bt,modelsError:wt,onModelChange:O,showThemeToggle:I,theme:U,onMobileMenuClick:()=>re(!J),showMobileMenuButton:l==="multiChat"}),p.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0 cuadra-space-y-4 cuadra-p-4",children:p.jsx(fu,{ref:n,welcomeTitle:S,welcomeSubtitle:x,extraTopPadding:b,suggestions:_,inputPlaceholder:T,enableAttachments:F,preMadeResponseDelay:L,streamingSpeed:z})})]})]}):p.jsxs("div",{className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:[u==="selector"&&p.jsx(gu,{currentModel:Ze||"",models:Q,modelsLoading:bt,modelsError:wt,onModelChange:O,showThemeToggle:I,theme:U}),p.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0 cuadra-space-y-4 cuadra-p-4",children:p.jsx(fu,{ref:n,welcomeTitle:S,welcomeSubtitle:x,extraTopPadding:b,suggestions:_,inputPlaceholder:T,preMadeResponseDelay:L,streamingSpeed:z})})]})})})})})})});class pn{constructor(){C(this,"config",null);C(this,"root",null);C(this,"container",null);C(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=E(m({},t),{containerId:r}),this.container=n,this.root=he.createRoot(n),this.root.render(g.createElement(bu,{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 s;const n=r||((s=this.config)==null?void 0:s.containerId);if(!n)return;const a=this.instances.get(n);if(!(a!=null&&a.config))return;const i=m(m({},a.config),t);a.config=i,a.root&&a.container&&a.root.render(g.createElement(bu,{config:i}))}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 bu=({config:e})=>p.jsx(yu,{config:e});let Ae=null;typeof window!="undefined"&&(Ae=new pn);const wu={init:e=>(Ae||(Ae=new pn),Ae.init(e)),destroy:e=>Ae==null?void 0:Ae.destroy(e),updateConfig:(e,t)=>Ae==null?void 0:Ae.updateConfig(e,t),getInstance:e=>Ae==null?void 0:Ae.getInstance(e),refetchModels:()=>{if(typeof window!="undefined"){const e=window.__cuadraUIKitRefetchModels;e&&e()}},version:"0.1.0"};if(typeof window!="undefined"){window.CuadraUIKit=wu;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"&&tv(r)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):setTimeout(e,0)}function tv(e){if(!e||!Ae)return;const t=pn.parseConfigFromAttributes(e),r=t.containerId||"cuadra-chat",n=document.getElementById(r);if(n){const a=pn.parseConfigFromAttributes(e,n);Object.assign(t,a)}(t.baseUrl||t.proxyUrl)&&Ae.init(t)}$.WidgetContent=yu,$.default=wu,Object.defineProperties($,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
39
+ `,Za=({children:e,className:t="",paddingX:r="px-0",paddingY:n="py-0",borderSizePx:a=4,style:i,contentStyle:s,rotating:o=!1})=>p.jsxs(p.Fragment,{children:[p.jsx("style",{children:ov}),p.jsxs("div",{className:`cuadra-relative cuadra-bg-background md:cuadra-rounded-xl cuadra-overflow-hidden ${t}`,style:m({padding:a},i),children:[p.jsx("div",{className:`cuadra-absolute md:cuadra-rounded-xl cuadra-textured-card-border ${o?"cuadra-textured-card-border-rotating":""}`,style:o?{left:"-100%",top:"-100%",width:"300%",height:"300%",backgroundRepeat:"no-repeat",backgroundSize:"cover",backgroundPosition:"center",animation:"rotate 4s linear infinite"}:{backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",top:"0",left:"0",width:"100%",height:"100%"}}),p.jsx("div",{className:`cuadra-relative cuadra-bg-background cuadra-h-full cuadra-z-10 cuadra-flex cuadra-flex-col cuadra-overflow-hidden ${r} ${n}`,style:m({borderRadius:"calc(0.75rem - 4px)"},s),children:e})]})]}),yu=({currentModel:e,models:t,modelsLoading:r,modelsError:n,onModelChange:a,hideModelSelector:i=!1,showThemeToggle:s=!0,theme:o="system",onMobileMenuClick:l,showMobileMenuButton:u=!1})=>{const[c,d]=y.useState(!1),[f,h]=y.useState(!1),g=y.useRef(null);y.useEffect(()=>{const b=I=>{g.current&&!g.current.contains(I.target)&&d(!1)};return c&&document.addEventListener("mousedown",b),()=>{document.removeEventListener("mousedown",b)}},[c]);const k=t.find(b=>b.id===e),w=b=>{a(b),d(!1),h(!1)};return p.jsxs("div",{className:"cuadra-h-16 cuadra-px-4 cuadra-border-b cuadra-border-border cuadra-flex cuadra-items-center cuadra-justify-between cuadra-bg-background",children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[u&&p.jsx("button",{type:"button",onClick:l,className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed md:cuadra-hidden","aria-label":"Toggle thread list",children:p.jsx($u,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})}),s&&p.jsx("div",{className:"cuadra-hidden md:cuadra-flex cuadra-items-center cuadra-gap-2",children:p.jsx(mu,{theme:o})})]}),p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 md:cuadra-ml-0 cuadra-ml-auto",children:[!i&&p.jsx("label",{className:"cuadra-hidden md:cuadra-inline cuadra-text-sm cuadra-text-muted-foreground cuadra-font-brand",children:"Model"}),i?null:r?p.jsx("div",{className:"cuadra-w-48 cuadra-rounded-md cuadra-border cuadra-border-border cuadra-px-3 cuadra-py-2 cuadra-bg-muted",children:p.jsx("span",{className:"cuadra-text-muted-foreground cuadra-text-sm cuadra-font-brand",children:"Loading..."})}):n?p.jsx("div",{className:"cuadra-w-48 cuadra-rounded-md cuadra-border cuadra-border-destructive cuadra-px-3 cuadra-py-2 cuadra-bg-destructive/10",children:p.jsx("span",{className:"cuadra-text-destructive cuadra-text-sm cuadra-font-brand",children:"Failed to load models"})}):p.jsxs(p.Fragment,{children:[p.jsxs("div",{ref:g,className:"cuadra-hidden md:cuadra-block cuadra-relative cuadra-w-48",children:[p.jsxs("button",{type:"button",onClick:()=>d(!c),disabled:r||t.length===0||!!n,className:"cuadra-flex cuadra-h-10 cuadra-w-full cuadra-items-center cuadra-justify-between cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-font-brand",children:[p.jsx("span",{className:k?"cuadra-text-foreground":"cuadra-text-muted-foreground",children:(k==null?void 0:k.name)||"Select model"}),p.jsx(_n,{className:"cuadra-ml-2 cuadra-h-4 cuadra-w-4 cuadra-opacity-50"})]}),c&&t.length>0&&p.jsx("div",{className:"cuadra-absolute cuadra-z-50 cuadra-mt-1 cuadra-w-full cuadra-min-w-[8rem] cuadra-overflow-hidden cuadra-rounded-md glass-popover cuadra-text-popover-foreground cuadra-animate-in fade-in-80 cuadra-border cuadra-border-border cuadra-bg-popover cuadra-shadow-md",children:p.jsx("div",{className:"cuadra-p-1",children:t.map(b=>p.jsxs("button",{type:"button",onClick:()=>w(b.id),className:`cuadra-relative cuadra-flex cuadra-w-full cuadra-cursor-pointer cuadra-select-none cuadra-items-center cuadra-rounded-sm cuadra-py-1.5 cuadra-pl-8 cuadra-pr-2 cuadra-text-sm cuadra-outline-none focus:cuadra-bg-secondary focus:cuadra-text-secondary-foreground font-brand cuadra-transition-colors ${e===b.id?"cuadra-bg-secondary cuadra-text-secondary-foreground":"hover:cuadra-bg-secondary/50"}`,children:[e===b.id&&p.jsx("span",{className:"cuadra-absolute cuadra-left-2 cuadra-flex cuadra-h-3.5 cuadra-w-3.5 cuadra-items-center cuadra-justify-center",children:p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",fill:"none",viewBox:"0 0 16 16",children:p.jsx("path",{fill:"currentColor",fillRule:"evenodd",d:"M6.47 10.03a.75.75 0 0 1-1.06-1.06l2-2a.75.75 0 0 1 1.06 0l2 2a.75.75 0 1 1-1.06 1.06L8 9.06l-1.53 1.53Z",clipRule:"evenodd"})})}),p.jsx("span",{children:b.name})]},b.id))})})]}),p.jsxs("button",{type:"button",onClick:()=>h(!0),disabled:r||t.length===0||!!n,className:"cuadra-flex md:cuadra-hidden cuadra-h-10 cuadra-w-full cuadra-items-center cuadra-justify-between cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-font-brand",children:[p.jsx("span",{className:k?"cuadra-text-foreground":"cuadra-text-muted-foreground",children:(k==null?void 0:k.name)||"Select model"}),p.jsx(_n,{className:"cuadra-ml-2 cuadra-h-4 cuadra-w-4 cuadra-opacity-50"})]}),f&&typeof document!="undefined"&&Re.createPortal(p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-bg-black/50 cuadra-z-50 md:cuadra-hidden",onClick:()=>h(!1)}),p.jsxs("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-50 cuadra-flex cuadra-flex-col cuadra-bg-background md:cuadra-hidden",children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-border-b cuadra-border-border cuadra-px-4 cuadra-py-4",children:[p.jsx("h2",{className:"cuadra-text-lg cuadra-font-normal cuadra-text-foreground font-brand",children:"Select Model"}),p.jsx("button",{type:"button",onClick:()=>h(!1),className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors","aria-label":"Close",children:p.jsx(Tn,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})})]}),p.jsx("div",{className:"cuadra-flex-1 cuadra-overflow-y-auto cuadra-p-4",children:r?p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-py-8",children:p.jsx("span",{className:"cuadra-text-muted-foreground cuadra-text-sm cuadra-font-brand",children:"Loading models..."})}):n?p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-py-8",children:p.jsx("span",{className:"cuadra-text-destructive cuadra-text-sm cuadra-font-brand",children:"Failed to load models"})}):t.length===0?p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-py-8",children:p.jsx("span",{className:"cuadra-text-muted-foreground cuadra-text-sm cuadra-font-brand",children:"No models available"})}):p.jsx("div",{className:"cuadra-space-y-2",children:t.map(b=>p.jsxs("button",{type:"button",onClick:()=>w(b.id),className:`cuadra-w-full cuadra-flex cuadra-items-center cuadra-justify-between cuadra-rounded-lg cuadra-border cuadra-px-4 cuadra-py-4 cuadra-text-left cuadra-transition-colors font-brand cuadra-bg-background cuadra-text-foreground cuadra-border-border hover:cuadra-bg-muted ${e===b.id?"cuadra-border-primary":""}`,children:[p.jsx("span",{className:"cuadra-text-base cuadra-font-normal",children:b.name}),e===b.id&&p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",fill:"none",viewBox:"0 0 20 20",className:"cuadra-text-primary",children:p.jsx("path",{fill:"currentColor",fillRule:"evenodd",d:"M16.707 5.293a1 1 0 0 1 0 1.414l-8 8a1 1 0 0 1-1.414 0l-4-4a1 1 0 0 1 1.414-1.414L8 12.586l7.293-7.293a1 1 0 0 1 1.414 0Z",clipRule:"evenodd"})})]},b.id))})})]})]}),document.body)]})]})]})},lv=y.createContext(void 0),ei=({children:e,value:t})=>p.jsx(lv.Provider,{value:t,children:e});function uv(){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 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:Me&&Me.tagName.toUpperCase()==="SCRIPT"&&Me.src||new URL("cuadra-uikit.umd.js",document.baseURI).href).href];let i=!1;for(const s of a)if(n.href=s,n.onload=()=>{i=!0},n.onerror=()=>{},document.head.appendChild(n),i)break},[])}const bu=y.forwardRef(function({config:t},r){uv();const n=y.useRef(null),a=y.useRef(!1),{baseUrl:i,proxyUrl:s,sessionToken:o,mode:l="multiChat",modelMode:u="fixed",modelId:c,onModelChange:d,ephemeral:f=!1,systemPrompt:h,enableReasoning:g=!1,initialThreadId:k,welcomeTitle:w,welcomeSubtitle:b,extraTopPadding:I,suggestions:T,inputPlaceholder:B,preMadeResponseDelay:F=1e3,streamingSpeed:_=50,showThemeToggle:$=!0,initialMessage:R,initialPreMadeQA:j,theme:S="system",onError:N,onChatCreated:M,onUserMessage:J,onThreadIdUpdate:z,onLogout:D,enableAttachments:Y=!1,onBeforeRequest:ce}=t;y.useImperativeHandle(r,()=>({sendMessage:q=>{var ie;(ie=n.current)==null||ie.sendMessage(q)},sendPreMadeQA:(q,ie,te)=>{var we;(we=n.current)==null||we.sendPreMadeQA(q,ie,te)},clearChat:()=>{var q;(q=n.current)==null||q.clearChat()}}),[]),y.useEffect(()=>{if(a.current)return;const q=setTimeout(()=>{var ie,te;j?(a.current=!0,(ie=n.current)==null||ie.sendPreMadeQA(j.question,j.answer,{delay:F,streamingSpeed:_})):R&&(a.current=!0,(te=n.current)==null||te.sendMessage(R))},500);return()=>clearTimeout(q)},[R,j,F,_]);const[se,me]=y.useState(!1),[x,Se]=y.useState(null),[ve,v]=y.useState(null),[U,oe]=y.useState(!1),ne=y.useRef(null),_e=q=>{if(q<30)return!0;if(ne.current){const ie=ne.current.getBoundingClientRect();if(q-ie.left<30)return!0}return!1},Te=q=>{const te=q.touches[0].clientX;(_e(te)||se)&&(Se(te),v(te),oe(!0))},ge=q=>{if(x===null||!U)return;const ie=q.touches[0];v(ie.clientX)},He=()=>{if(x===null||ve===null){oe(!1);return}const q=ve-x,ie=50,te=.3,Ke=Math.abs(q)/300;q>ie&&!se&&x!==null?_e(x)&&me(!0):((q<-ie||q<0&&Ke>te)&&se||se&&q<-20&&Ke>te)&&me(!1),Se(null),v(null),oe(!1)},Kt=()=>{if(U&&x!==null&&ve!==null){const q=ve-x;if(se)return`translateX(${Math.min(0,q)}px)`;if(x!==null&&_e(x))return`translateX(${Math.min(0,-320+q)}px)`}return se?"translateX(0)":"translateX(-100%)"},ti=()=>{if(!U||x===null||ve===null)return se?.5:0;const ie=ve-x;return se?Math.max(0,Math.min(1,(320+ie)/320))*.5:x!==null&&_e(x)?Math.max(0,Math.min(1,(ie+320)/320))*.5:0},Yt=s||i||"",Gt=!!s,Er=y.useMemo(()=>new uo(Yt,o||void 0,Gt),[Yt,o,Gt]),[Oe,yn]=y.useState(null),[Pt,Ar]=y.useState(!1),[yt,bn]=y.useState(null),[ri,wn]=y.useState(!1);y.useEffect(()=>{l==="multiChat"&&wn(!0)},[l]);const bt=y.useCallback(()=>P(null,null,function*(){if(u==="selector"){Ar(!0),bn(null);try{const q=yield Er.listModels();yn(q)}catch(q){bn(q instanceof Error?q:new Error("Failed to load models"))}finally{Ar(!1)}}}),[Er,u]);y.useEffect(()=>{u==="selector"&&bt()},[u,bt]),y.useEffect(()=>(typeof window!="undefined"&&(window.__cuadraUIKitRefetchModels=bt),()=>{typeof window!="undefined"&&delete window.__cuadraUIKitRefetchModels}),[bt]);const[nt,A]=y.useState(u==="fixed"&&c||null),O=y.useRef(nt),K=y.useCallback(q=>{const ie=O.current;A(q),O.current=q,d==null||d(q),ie!==null&&ie!==q&&l==="multiChat"&&setTimeout(()=>{var we,Ke;const te=window.__cuadraThreadListRuntime;if((we=te==null?void 0:te.threads)!=null&&we.switchToNewThread)try{te.threads.switchToNewThread()}catch(Ye){}else if((Ke=te==null?void 0:te.threads)!=null&&Ke.createThread)try{te.threads.createThread()}catch(Ye){}else if(te!=null&&te.switchToNewThread)try{te.switchToNewThread()}catch(Ye){}},100)},[d,l]);y.useEffect(()=>{if(u==="selector"&&(Oe!=null&&Oe.items)&&Oe.items.length>0&&!nt){const q=Oe.items[0];if(q!=null&&q.id){const ie=q.id;A(ie),d==null||d(ie)}}},[u,Oe==null?void 0:Oe.items,nt,d]);const Z=u==="fixed"?!!c:!!nt,ae=y.useMemo(()=>((Oe==null?void 0:Oe.items)||[]).filter(q=>(q==null?void 0:q.id)&&(q==null?void 0:q.displayName)).map(q=>({id:q.id,name:q.displayName})),[Oe]),Fe=y.useMemo(()=>({currentModelId:nt||"",models:ae,modelsLoading:Pt,modelsError:yt,onModelChange:K,refetchModels:bt}),[nt,ae,Pt,yt,K,bt]);return u==="selector"&&Pt||l==="multiChat"&&ri?p.jsx(ei,{value:Fe,children:p.jsx(Za,{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(oi,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"})})})}):u==="selector"&&!Z&&yt?p.jsx(ei,{value:Fe,children:p.jsx(Za,{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(ei,{value:Fe,children:p.jsx(cp,{baseUrl:Gt?Yt:i||Yt,sessionToken:o,isProxyMode:Gt,mode:l,modelMode:u,modelId:nt||c||void 0,onModelChange:K,ephemeral:f,systemPrompt:h,enableReasoning:g,initialThreadId:k,enableAttachments:Y,onError:N,onChatCreated:M,onUserMessage:J,onThreadIdUpdate:z,onBeforeRequest:ce,onChatsLoaded:()=>{l==="multiChat"&&wn(!1)},children:p.jsx(Za,{paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",className:`cuadra-h-full ${t.containerClass||""}`,borderSizePx:4,style:{height:"100%"},children:p.jsx("div",{className:"cuadra-h-full cuadra-flex cuadra-relative",style:{height:"100%"},onTouchStart:Te,onTouchMove:ge,onTouchEnd:He,children:l==="multiChat"?p.jsxs(p.Fragment,{children:[typeof document!="undefined"&&Re.createPortal(p.jsx("div",{className:`cuadra-fixed cuadra-inset-0 cuadra-bg-black cuadra-z-40 md:cuadra-hidden cuadra-transition-opacity cuadra-duration-300 ${se||U?"":"cuadra-pointer-events-none"}`,style:{opacity:ti()},onClick:()=>me(!1)}),document.body),typeof document!="undefined"&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-hidden md:cuadra-block !cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-full cuadra-w-80 cuadra-relative",style:{borderRightWidth:"1px",height:"100%"},children:p.jsx(gu,{onThreadSelect:()=>me(!1),showThemeToggle:$,theme:S,onLogout:D})}),typeof document!="undefined"&&Re.createPortal(p.jsx("div",{className:`cuadra-block md:cuadra-hidden !cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-h-screen cuadra-w-80 cuadra-fixed cuadra-z-50 cuadra-top-0 cuadra-left-0 ${se||U?"":"cuadra-pointer-events-none"}`,style:{borderRightWidth:"1px",transform:Kt(),transition:U?"none":"transform 0.3s ease-in-out"},onTouchStart:Te,onTouchMove:ge,onTouchEnd:He,children:p.jsx(gu,{onThreadSelect:()=>me(!1),showThemeToggle:$,theme:S,onLogout:D})}),document.body)]}),p.jsxs("div",{ref:ne,className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:[u==="selector"&&p.jsx(yu,{currentModel:nt||"",models:ae,modelsLoading:Pt,modelsError:yt,onModelChange:K,showThemeToggle:$,theme:S,onMobileMenuClick:()=>me(!se),showMobileMenuButton:l==="multiChat"}),p.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0 cuadra-space-y-4 cuadra-p-4",children:p.jsx(pu,{ref:n,welcomeTitle:w,welcomeSubtitle:b,extraTopPadding:I,suggestions:T,inputPlaceholder:B,enableAttachments:Y,preMadeResponseDelay:F,streamingSpeed:_})})]})]}):p.jsxs("div",{className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:[u==="selector"&&p.jsx(yu,{currentModel:nt||"",models:ae,modelsLoading:Pt,modelsError:yt,onModelChange:K,showThemeToggle:$,theme:S}),p.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0 cuadra-space-y-4 cuadra-p-4",children:p.jsx(pu,{ref:n,welcomeTitle:w,welcomeSubtitle:b,extraTopPadding:I,suggestions:T,inputPlaceholder:B,preMadeResponseDelay:F,streamingSpeed:_})})]})})})})})})});class gn{constructor(){C(this,"config",null);C(this,"root",null);C(this,"container",null);C(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=E(m({},t),{containerId:r}),this.container=n,this.root=fe.createRoot(n),this.root.render(y.createElement(wu,{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 s;const n=r||((s=this.config)==null?void 0:s.containerId);if(!n)return;const a=this.instances.get(n);if(!(a!=null&&a.config))return;const i=m(m({},a.config),t);a.config=i,a.root&&a.container&&a.root.render(y.createElement(wu,{config:i}))}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 wu=({config:e})=>p.jsx(bu,{config:e});let De=null;typeof window!="undefined"&&(De=new gn);const xu={init:e=>(De||(De=new gn),De.init(e)),destroy:e=>De==null?void 0:De.destroy(e),updateConfig:(e,t)=>De==null?void 0:De.updateConfig(e,t),getInstance:e=>De==null?void 0:De.getInstance(e),refetchModels:()=>{if(typeof window!="undefined"){const e=window.__cuadraUIKitRefetchModels;e&&e()}},version:"0.1.0"};if(typeof window!="undefined"){window.CuadraUIKit=xu;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"&&cv(r)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):setTimeout(e,0)}function cv(e){if(!e||!De)return;const t=gn.parseConfigFromAttributes(e),r=t.containerId||"cuadra-chat",n=document.getElementById(r);if(n){const a=gn.parseConfigFromAttributes(e,n);Object.assign(t,a)}(t.baseUrl||t.proxyUrl)&&De.init(t)}H.WidgetContent=bu,H.default=xu,Object.defineProperties(H,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
40
40
  //# sourceMappingURL=cuadra-uikit.umd.js.map