@useago/sdk 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -46,6 +46,11 @@ Start your dev server. A chat panel renders on the page; type a message and
46
46
  watch the reply stream in. That's a complete integration. (`generic-guide` is a
47
47
  public demo agent; swap `baseUrl` and `agent` for your own once you have a tenant.)
48
48
 
49
+ `ChatWidget` is the high-level component to get started in minutes. Everything it
50
+ does is also exposed through hooks and APIs (`useChat`, `useMessages`, the raw
51
+ client, events), so when you outgrow the default panel you can drop down and build
52
+ the exact experience you want. The example below renders one piece of that.
53
+
49
54
  ## Let the agent drive your existing routes
50
55
 
51
56
  This is the part existing apps care about. You already have a router and pages;
@@ -76,6 +81,49 @@ guards, auth and layouts keep working exactly as they do today.
76
81
  `react-router-dom` here is *your* router, not an SDK dependency:
77
82
  `useAgoNavigation` accepts any `(path: string) => void` function.
78
83
 
84
+ ## Show the source docs the agent retrieved
85
+
86
+ Each assistant message carries the knowledge sources it used in `m.sources`
87
+ (each one is `{ id, title, url? }`). Build your own chat with `useChat` and
88
+ render them as links to show the URL of every retrieved doc:
89
+
90
+ ```tsx
91
+ import { useChat } from "@useago/sdk/react";
92
+
93
+ function Chat() {
94
+ const { messages, sendMessage, isLoading } = useChat();
95
+
96
+ return (
97
+ <div>
98
+ {messages.map((m) => (
99
+ <div key={m.id}>
100
+ <p><b>{m.role}:</b> {m.content}</p>
101
+
102
+ {m.sources?.length ? (
103
+ <ul>
104
+ {m.sources.map((s) => (
105
+ <li key={s.id}>
106
+ {s.url ? (
107
+ <a href={s.url} target="_blank" rel="noreferrer">
108
+ {s.title || s.url}
109
+ </a>
110
+ ) : (
111
+ s.title
112
+ )}
113
+ </li>
114
+ ))}
115
+ </ul>
116
+ ) : null}
117
+ </div>
118
+ ))}
119
+ <button onClick={() => sendMessage("Hello!")} disabled={isLoading}>
120
+ Send
121
+ </button>
122
+ </div>
123
+ );
124
+ }
125
+ ```
126
+
79
127
  **Next: the [Getting started guide](docs/general/getting-started.md)** has both
80
128
  examples assembled into a running app, plus everything else the SDK can do, in
81
129
  about 5 minutes.
@@ -0,0 +1,6 @@
1
+ var h=class extends Error{constructor(e,t,s){super(e),this.code=t,this.statusCode=s,this.name="AgoError"}},u=class b extends h{constructor(t,s,n,r,i,a){super(t,s,n),this.type=r,this.param=i,this.docUrl=a,this.name="AgoApiError"}static fromResponse(t,s){const n=t.error;return new b(n.doc_url?`${n.message} See ${n.doc_url}`:n.message,n.code,s,n.type,n.param,n.doc_url)}},d=class extends h{constructor(e,t){super(e,"network_error"),this.originalError=t,this.name="AgoNetworkError"}},g=class extends h{constructor(e,t="stream_error"){super(e,t),this.name="AgoStreamError"}},m=class extends h{constructor(e,t,s){super(e,"function_error"),this.functionName=t,this.originalError=s,this.name="AgoFunctionError"}},$=class{constructor(e=!1){this.enabled=e}enable(){this.enabled=!0}disable(){this.enabled=!1}log(...e){this.enabled&&console.log("[AGO SDK]",...e)}warn(...e){this.enabled&&console.warn("[AGO SDK]",...e)}error(...e){console.error("[AGO SDK]",...e)}debug(...e){this.enabled&&console.debug("[AGO SDK]",...e)}},o=new $,y="ago_widget_id";function x(){if(typeof localStorage<"u"){const t=localStorage.getItem(y);if(t)return t}const e=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`ago-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`;if(typeof localStorage<"u")try{localStorage.setItem(y,e)}catch{}return e}var R=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.headers={"X-User-Anon-Id":e.widgetId||x()},e.userEmail&&(this.headers["X-User-Email"]=e.userEmail),e.userJwt&&(this.headers.Authorization=`Bearer ${e.userJwt}`),e.permission&&(this.headers["X-Widget-Permission"]=e.permission)}updateConfig(e){e.baseUrl&&(this.baseUrl=e.baseUrl.replace(/\/$/,"")),e.widgetId&&(this.headers["X-User-Anon-Id"]=e.widgetId),e.userEmail&&(this.headers["X-User-Email"]=e.userEmail),e.userJwt&&(this.headers.Authorization=`Bearer ${e.userJwt}`),e.permission!==void 0&&(e.permission?this.headers["X-Widget-Permission"]=e.permission:delete this.headers["X-Widget-Permission"])}async get(e){return this.request("GET",e)}async post(e,t){return this.request("POST",e,t)}async postStream(e,t){const s=`${this.baseUrl}${e}`;o.debug("POST (stream)",s,t);try{const n=await fetch(s,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0});return n.ok||await this.handleErrorResponse(n),n}catch(n){throw n instanceof u?n:new d(`Network error: ${n instanceof Error?n.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,n instanceof Error?n:void 0)}}async postFormData(e,t){const s=`${this.baseUrl}${e}`;o.debug("POST (formData)",s);const n={...this.headers};try{const r=await fetch(s,{method:"POST",headers:n,body:t});return r.ok||await this.handleErrorResponse(r),r}catch(r){throw r instanceof u?r:new d(`Network error: ${r instanceof Error?r.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,r instanceof Error?r:void 0)}}async request(e,t,s){const n=`${this.baseUrl}${t}`;o.debug(e,n,s);try{const r=await fetch(n,{method:e,headers:{...this.headers,"Content-Type":"application/json"},body:s?JSON.stringify(s):void 0});return r.ok||await this.handleErrorResponse(r),r.status===204?void 0:r.json()}catch(r){throw r instanceof u?r:new d(`Network error: ${r instanceof Error?r.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,r instanceof Error?r:void 0)}}async handleErrorResponse(e){let t;try{t=await e.json()}catch{}if(t?.error)throw u.fromResponse(t,e.status);let s="";throw e.status===401||e.status===403?s=" Check `userJwt` (and that it has not expired).":e.status===404&&(s=" Check that `baseUrl` points at your AGO API root."),new u(`HTTP ${e.status}: ${e.statusText}.${s}`,"http_error",e.status,"api_error")}},C=class{constructor(){this.functions=new Map}register(e,t,s){if(typeof e=="object"){const{name:r,handler:i,description:a,parameters:l}=e;return this.register(r,i,{description:a,parameters:l})}const n=e;if(!t||!s)throw new h(`registerFunction("${n}"): both a handler and a schema are required. Pass them as arguments or use the single-object form: registerFunction({ name, parameters, handler }).`,"function_invalid_registration");this.functions.has(n)&&o.warn(`Function "${n}" is being overwritten`),this.functions.set(n,{schema:{...s,name:n},handler:t}),o.log(`Registered function: ${n}`)}unregister(e){const t=this.functions.delete(e);return t&&o.log(`Unregistered function: ${e}`),t}get(e){return this.functions.get(e)}has(e){return this.functions.has(e)}getSchemas(){return Array.from(this.functions.values()).map(e=>e.schema)}async execute(e,t){const s=this.functions.get(e);if(!s)throw new m(`Function "${e}" is not registered`,e);o.log(`Executing function: ${e}`,t);try{const n=await s.handler(t);return o.log(`Function ${e} completed:`,n),n}catch(n){throw o.error(`Function ${e} failed:`,n),new m(`Function "${e}" execution failed: ${n instanceof Error?n.message:"Unknown error"}`,e,n instanceof Error?n:void 0)}}clear(){this.functions.clear(),o.log("Cleared all registered functions")}get size(){return this.functions.size}},E=class{constructor(){this.entries=new Map,this.dynamicProviders=new Map}set(e,t){this.entries.set(e,t),o.log(`ClientContext set: ${e}`)}remove(e){const t=this.entries.delete(e);return t&&o.log(`ClientContext removed: ${e}`),t}addDynamicProvider(e,t){this.dynamicProviders.set(e,t),o.log(`DynamicContext provider added: ${e}`)}removeDynamicProvider(e){const t=this.dynamicProviders.delete(e);return t&&o.log(`DynamicContext provider removed: ${e}`),t}getSnapshot(){if(this.entries.size===0&&this.dynamicProviders.size===0)return null;const e={};for(const[t,s]of this.entries)e[t]=s;for(const[t,s]of this.dynamicProviders)try{const n=s();n&&(e[t]=n)}catch(n){o.error(`DynamicContext provider "${t}" threw:`,n)}return Object.keys(e).length===0?null:{entries:e}}clear(){this.entries.clear(),this.dynamicProviders.clear(),o.log("ClientContext cleared")}};function f(e){return e===null||typeof e!="object"?JSON.stringify(e)??"null":Array.isArray(e)?`[${e.map(f).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${f(e[t])}`).join(",")}}`}var _=class{constructor(e){this.callbacks=e,this.buffer="",this.message={},this.toolCalls=[],this.sources=[],this.followUpReplies=[],this.isFirstChunk=!0,this.answerCompleteEmitted=!1,this.firedClientFunctions=new Set}async processStream(e){if(!e.body)throw new g("Response has no body. The endpoint did not return a stream: check that `baseUrl` points at an AGO API and nothing (proxy, mock) strips the SSE body.","stream_no_body");const t=e.body.getReader(),s=new TextDecoder;try{for(;;){const{done:n,value:r}=await t.read();if(n)break;const i=s.decode(r,{stream:!0});this.buffer+=i,this.processBuffer()}return this.buffer.trim()&&this.processBuffer(),this.buildFinalMessage()}catch(n){const r=n instanceof Error?n:new g("Stream processing failed mid-flight. The connection may have dropped; retry the message.");throw this.callbacks.onError?.(r),r}finally{t.releaseLock()}}processBuffer(){const e=this.buffer.split(`
2
+
3
+ `);this.buffer=e.pop()||"";for(const t of e){if(!t.trim())continue;const s=t.split(`
4
+ `);for(const n of s)if(!n.startsWith(": ")&&n.startsWith("data: ")){const r=n.slice(6);try{const i=JSON.parse(r);this.handleChunk(i)}catch(i){o.warn("Failed to parse SSE data:",r,i)}}}}handleChunk(e){if(e.message_id&&!this.message.id&&(this.message.id=e.message_id),e.thread?.id&&(this.message.conversationId=e.thread.id,this.isFirstChunk&&this.message.id&&(this.isFirstChunk=!1,this.callbacks.onStart?.({conversationId:this.message.conversationId,messageId:this.message.id}))),e.content!==void 0&&(this.message.content=(this.message.content||"")+e.content,this.message.conversationId&&this.message.id&&this.callbacks.onChunk?.({content:e.content,conversationId:this.message.conversationId,messageId:this.message.id})),e.full_content!==void 0&&(this.message.content=e.full_content),e.status&&(this.message.status=e.status),e.agent&&(this.message.agent={id:e.agent.id,name:e.agent.name,displayName:e.agent.display_name}),e.knowledge_sources&&(this.sources=e.knowledge_sources.map(t=>{const s=t.knowledge_document;return{id:s.id,title:s.title,url:s.use_external_link?s.external_link_url:s.internal_link_url}})),e.type==="client_function"&&e.function_name){const t=`${e.function_name}::${f(e.arguments??{})}`;this.firedClientFunctions.has(t)||(this.firedClientFunctions.add(t),this.callbacks.onClientFunction?.({invocationId:e.id||"",functionName:e.function_name,arguments:e.arguments||{},conversationId:this.message.conversationId||""}))}if(e.tool_call_data&&e.type&&e.type!=="client_function"){const t=this.parseToolCall(e);this.callbacks.onToolCall?.(t);const s=this.toolCalls.findIndex(n=>n.id===t.id);s>=0?this.toolCalls[s]=t:this.toolCalls.push(t)}e.follow_up_replies&&(this.followUpReplies=e.follow_up_replies),this.message.status==="DONE"&&!this.answerCompleteEmitted&&this.message.id&&(this.answerCompleteEmitted=!0,this.callbacks.onAnswerComplete?.(this.buildMessage()))}parseToolCall(e){return{id:e.id||"",type:e.type||"status_message",status:e.status||"unknown",toolName:e.tool_name||"",toolDisplayName:e.tool_display_name,message:e.message,formSchema:e.form_schema,data:e.data,functionName:e.function_name,arguments:e.arguments}}buildMessage(){return{id:this.message.id||"",conversationId:this.message.conversationId||"",content:this.message.content||"",role:"assistant",status:this.message.status||"DONE",agent:this.message.agent,sources:this.sources.length>0?this.sources:void 0,toolCalls:this.toolCalls.length>0?this.toolCalls:void 0,followUpReplies:this.followUpReplies.length>0?this.followUpReplies:void 0,createdAt:new Date}}buildFinalMessage(){const e=this.buildMessage();return this.callbacks.onComplete?.(e),e}};function I(e){const t=e.message.toLowerCase();return t.includes("load failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("abort")}var S=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){const s=this.handlers.get(e);s&&s.delete(t)}emit(e,t){const s=this.handlers.get(e);s&&s.forEach(n=>{try{n(t)}catch(r){console.error(`Error in event handler for ${String(e)}:`,r)}})}once(e,t){const s=(n=>{this.off(e,s),t(n)});this.on(e,s)}waitFor(e,t){return new Promise((s,n)=>{let r;const i=(a=>{r&&clearTimeout(r),s(a)});this.once(e,i),t?.timeout&&(r=setTimeout(()=>{this.off(e,i),n(new Error(`waitFor("${String(e)}") timed out after ${t.timeout}ms`))},t.timeout))})}removeAllListeners(e){e?this.handlers.delete(e):this.handlers.clear()}},w='`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the live demo endpoint https://playground.api.useago.com. See docs/general/configuration.md#error-codes (config_missing_base_url).',U=/^[a-z][a-z0-9+.-]*:\/\//i,v=!1;function p(e,t="AgoClient"){if(typeof e!="object"||e===null)throw new h(`${t}: ${w}`,"config_missing_base_url");const s=e.baseUrl;if(typeof s!="string"||s.trim()==="")throw new h(`${t}: ${w}`,"config_missing_base_url");!s.startsWith("/")&&!U.test(s)&&(v||(v=!0,console.warn(`[AGO] ${t}: \`baseUrl\` has no protocol and is not a relative path (config_suspect_base_url). Requests will fail: Node throws a URL parse error, browsers fetch it as a relative path. Use "https://..." (or a "/path" for a same-origin proxy).`)))}var F=class k{constructor(t){this.warnedEmptyConversations=new Set,p(t,"AgoClient"),this.config=t,this.httpClient=new R(t),this.functionRegistry=new C,this.contextRegistry=new E,this.eventEmitter=new S,t.debug&&o.enable(),o.log("AgoClient initialized")}async sendMessage(t,s){const n=this.functionRegistry.getSchemas(),r=this.contextRegistry.getSnapshot(),i=this.config.agent||this.config.defaultAgentId,a={content:t,conversation_id:s?.conversationId,agent_id:s?.agentId||i};n.length>0&&(a.client_functions=n),r&&(a.client_context=r);let l;if(s?.files&&s.files.length>0){const c=new FormData;c.append("content",t),s.conversationId&&c.append("conversation_id",s.conversationId),(s.agentId||i)&&c.append("agent_id",s.agentId||i||""),n.length>0&&c.append("client_functions",JSON.stringify(n)),r&&c.append("client_context",JSON.stringify(r));for(const A of s.files)c.append("files",A);l=await this.httpClient.postFormData("/api/sdk/v1/messages",c)}else l=await this.httpClient.postStream("/api/sdk/v1/messages",a);return this.processSSEResponse(l)}async processSSEResponse(t){let s=!1;const n=await new _({onStart:r=>{this.eventEmitter.emit("message:start",r)},onChunk:r=>{this.eventEmitter.emit("message:chunk",r)},onToolCall:r=>{this.eventEmitter.emit("toolCall:received",r),r.type==="form"&&this.eventEmitter.emit("toolCall:form",r)},onClientFunction:async r=>{s=!0,this.eventEmitter.emit("function:invoke",r),await this.handleClientFunctionInvocation(r)},onAnswerComplete:r=>{this.eventEmitter.emit("message:answer-complete",r)},onComplete:r=>{this.eventEmitter.emit("message:complete",r)},onError:r=>{this.eventEmitter.emit("message:error",{error:r.message,code:r instanceof h?r.code:void 0})}}).processStream(t);return this.maybeFlagEmptyReply(n,s),n}maybeFlagEmptyReply(t,s){t.status==="DONE"&&(t.content??"").trim()===""&&!s&&!(t.toolCalls&&t.toolCalls.length>0)&&!(t.followUpReplies&&t.followUpReplies.length>0)&&setTimeout(()=>{if(this.eventEmitter.emit("message:empty",{conversationId:t.conversationId??"",messageId:t.id??""}),this.config.warnOnEmptyReply===!1)return;const n=t.conversationId||"(no conversation)";if(this.warnedEmptyConversations.has(n))return;this.warnedEmptyConversations.add(n);const r=this.config.agent||this.config.defaultAgentId;t.id?console.warn("[AGO] Reply completed with empty content. Possible causes: "+(r?`the agent "${r}" may not exist for this tenant, `:"an unknown `agent` slug, ")+"or the agent replied with no text. Listen for the `message:empty` event to handle this in your app; silence this warning with `warnOnEmptyReply: false`."):console.warn("[AGO] The stream completed without any message data. Possible causes: "+(r?`the agent "${r}" may not exist for this tenant, or `:"")+"`baseUrl` does not point at an AGO endpoint that returns server-sent events. Listen for the `message:empty` event to handle this in your app; silence this warning with `warnOnEmptyReply: false`.")},0)}async handleClientFunctionInvocation(t){let s,n;try{s=await this.functionRegistry.execute(t.functionName,t.arguments)}catch(r){n=r instanceof Error?r.message:"Unknown error",o.error("Client function execution failed:",r)}if(t.invocationId)try{await this.submitToolCallForm(t.invocationId,{result:s,error:n,_type:"client_function_result"})}catch(r){o.error("Failed to submit function result:",r)}this.eventEmitter.emit("function:result",{invocationId:t.invocationId,result:s,error:n})}async getConversations(){return(await this.httpClient.get("/api/sdk/v1/conversations")).items.map(t=>({id:t.id,title:t.title,lastMessageDate:new Date(t.last_message_date)}))}async getConversation(t){const s=await this.httpClient.get(`/api/sdk/v1/conversations/${t}`),n={id:s.id,title:s.title,lastMessageDate:new Date(s.last_message_date),messages:s.messages.map(r=>({id:r.id,conversationId:s.id,content:r.content,role:r.role,status:r.status,createdAt:new Date(r.created_at),toolCalls:k.mapPersistedToolCalls(r.tool_call_data)}))};return this.eventEmitter.emit("conversation:loaded",n),n}static mapPersistedToolCalls(t){if(!(!t||t.length===0))return t.map(s=>({id:String(s.id??""),type:s.type??"status_message",status:String(s.status??"unknown"),toolName:s.tool_name??"",toolDisplayName:s.tool_display_name,message:s.message,formSchema:s.form_schema,data:s.data,functionName:s.function_name,arguments:s.arguments}))}async getMessages(t){return(await this.getConversation(t)).messages||[]}async submitToolCallForm(t,s){await this.httpClient.post(`/api/sdk/v1/tool-calls/${t}/submit`,{formData:s})}async confirmToolCall(t){await this.httpClient.post(`/api/tool-calls/${t}/confirm/`)}async rejectToolCall(t){await this.httpClient.post(`/api/tool-calls/${t}/reject/`)}async getFormCollector(t){const s=await this.httpClient.get(`/api/sdk/v1/forms/${encodeURIComponent(t)}`);return{name:s.name,description:s.description,schema:s.schema,submit:s.submit??void 0}}async submitFormCollector(t,s){return this.httpClient.post("/api/sdk/v1/forms/submit",{name:t,values:s})}async submitFeedback(t,s){await this.httpClient.post(`/api/sdk/v1/messages/${t}/feedback`,{rating:s})}registerFunction(t,s,n){typeof t=="object"?this.functionRegistry.register(t):this.functionRegistry.register(t,s,n)}register(t){if(Array.isArray(t))for(const s of t)this.functionRegistry.register(s);else this.functionRegistry.register(t)}unregisterFunction(t){return this.functionRegistry.unregister(t)}getRegisteredFunctions(){return this.functionRegistry.getSchemas()}registerNavigationFunction(t,s){const n=s.map(i=>i.name),r=s.map(i=>`- "${i.name}": ${i.description}`).join(`
5
+ `);this.registerFunction("navigateToPage",async i=>{const a=i.page,l=s.find(c=>c.name===a);return l?(t(l.path),{success:!0,navigatedTo:l.path}):{success:!1,error:`Unknown page: ${a}`}},{description:`Navigate the user to a page in the application. Available pages:
6
+ ${r}`,parameters:{type:"object",properties:{page:{type:"string",description:"The page to navigate to",enum:n}},required:["page"]}})}setContext(t,s){this.contextRegistry.set(t,s),this.notifyContextChanged()}removeContext(t){const s=this.contextRegistry.remove(t);return s&&this.notifyContextChanged(),s}addDynamicContext(t,s){this.contextRegistry.addDynamicProvider(t,s),this.notifyContextChanged()}removeDynamicContext(t){const s=this.contextRegistry.removeDynamicProvider(t);return s&&this.notifyContextChanged(),s}notifyContextChanged(){this.eventEmitter.emit("context:changed",this.contextRegistry.getSnapshot())}enableAutoPageContext(){this.addDynamicContext("browser-page",()=>{const t=typeof window<"u"?window.location.href:void 0,s=typeof document<"u"?document.title:void 0;return!t&&!s?null:{name:"Browser page",description:"Current page the user is viewing",data:{url:t,title:s}}})}getContextSnapshot(){return this.contextRegistry.getSnapshot()}on(t,s){this.eventEmitter.on(t,s)}off(t,s){this.eventEmitter.off(t,s)}once(t,s){this.eventEmitter.once(t,s)}waitFor(t,s){return this.eventEmitter.waitFor(t,s)}updateConfig(t){const s={};for(const[r,i]of Object.entries(t))i!==void 0&&(s[r]=i);const n={...this.config,...s};p(n,"AgoClient.updateConfig"),this.config=n,this.httpClient.updateConfig(s),s.debug!==void 0&&(s.debug?o.enable():o.disable())}destroy(){this.eventEmitter.removeAllListeners(),this.functionRegistry.clear(),this.contextRegistry.clear(),o.log("AgoClient destroyed")}};Object.defineProperty(exports,"AgoApiError",{enumerable:!0,get:function(){return u}});Object.defineProperty(exports,"AgoClient",{enumerable:!0,get:function(){return F}});Object.defineProperty(exports,"AgoError",{enumerable:!0,get:function(){return h}});Object.defineProperty(exports,"AgoFunctionError",{enumerable:!0,get:function(){return m}});Object.defineProperty(exports,"AgoNetworkError",{enumerable:!0,get:function(){return d}});Object.defineProperty(exports,"AgoStreamError",{enumerable:!0,get:function(){return g}});Object.defineProperty(exports,"ClientContextRegistry",{enumerable:!0,get:function(){return E}});Object.defineProperty(exports,"EventEmitter",{enumerable:!0,get:function(){return S}});Object.defineProperty(exports,"FunctionRegistry",{enumerable:!0,get:function(){return C}});Object.defineProperty(exports,"SSEHandler",{enumerable:!0,get:function(){return _}});Object.defineProperty(exports,"isStreamNetworkError",{enumerable:!0,get:function(){return I}});Object.defineProperty(exports,"logger",{enumerable:!0,get:function(){return o}});Object.defineProperty(exports,"validateConfig",{enumerable:!0,get:function(){return p}});
@@ -2,27 +2,27 @@ var h = class extends Error {
2
2
  constructor(e, t, s) {
3
3
  super(e), this.code = t, this.statusCode = s, this.name = "AgoError";
4
4
  }
5
- }, d = class v extends h {
5
+ }, d = class C extends h {
6
6
  constructor(t, s, n, i, r, a) {
7
7
  super(t, s, n), this.type = i, this.param = r, this.docUrl = a, this.name = "AgoApiError";
8
8
  }
9
9
  static fromResponse(t, s) {
10
10
  const n = t.error;
11
- return new v(n.doc_url ? `${n.message} See ${n.doc_url}` : n.message, n.code, s, n.type, n.param, n.doc_url);
11
+ return new C(n.doc_url ? `${n.message} See ${n.doc_url}` : n.message, n.code, s, n.type, n.param, n.doc_url);
12
12
  }
13
13
  }, u = class extends h {
14
14
  constructor(e, t) {
15
15
  super(e, "network_error"), this.originalError = t, this.name = "AgoNetworkError";
16
16
  }
17
- }, m = class extends h {
17
+ }, g = class extends h {
18
18
  constructor(e, t = "stream_error") {
19
19
  super(e, t), this.name = "AgoStreamError";
20
20
  }
21
- }, g = class extends h {
21
+ }, f = class extends h {
22
22
  constructor(e, t, s) {
23
23
  super(e, "function_error"), this.functionName = t, this.originalError = s, this.name = "AgoFunctionError";
24
24
  }
25
- }, E = class {
25
+ }, _ = class {
26
26
  constructor(e = !1) {
27
27
  this.enabled = e;
28
28
  }
@@ -44,22 +44,22 @@ var h = class extends Error {
44
44
  debug(...e) {
45
45
  this.enabled && console.debug("[AGO SDK]", ...e);
46
46
  }
47
- }, o = new E(), f = "ago_widget_id";
48
- function _() {
47
+ }, o = new _(), p = "ago_widget_id";
48
+ function S() {
49
49
  if (typeof localStorage < "u") {
50
- const t = localStorage.getItem(f);
50
+ const t = localStorage.getItem(p);
51
51
  if (t) return t;
52
52
  }
53
53
  const e = typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `ago-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
54
54
  if (typeof localStorage < "u") try {
55
- localStorage.setItem(f, e);
55
+ localStorage.setItem(p, e);
56
56
  } catch {
57
57
  }
58
58
  return e;
59
59
  }
60
- var S = class {
60
+ var k = class {
61
61
  constructor(e) {
62
- this.baseUrl = e.baseUrl.replace(/\/$/, ""), this.headers = { "X-User-Anon-Id": e.widgetId || _() }, e.userEmail && (this.headers["X-User-Email"] = e.userEmail), e.userJwt && (this.headers.Authorization = `Bearer ${e.userJwt}`), e.permission && (this.headers["X-Widget-Permission"] = e.permission);
62
+ this.baseUrl = e.baseUrl.replace(/\/$/, ""), this.headers = { "X-User-Anon-Id": e.widgetId || S() }, e.userEmail && (this.headers["X-User-Email"] = e.userEmail), e.userJwt && (this.headers.Authorization = `Bearer ${e.userJwt}`), e.permission && (this.headers["X-Widget-Permission"] = e.permission);
63
63
  }
64
64
  updateConfig(e) {
65
65
  e.baseUrl && (this.baseUrl = e.baseUrl.replace(/\/$/, "")), e.widgetId && (this.headers["X-User-Anon-Id"] = e.widgetId), e.userEmail && (this.headers["X-User-Email"] = e.userEmail), e.userJwt && (this.headers.Authorization = `Bearer ${e.userJwt}`), e.permission !== void 0 && (e.permission ? this.headers["X-Widget-Permission"] = e.permission : delete this.headers["X-Widget-Permission"]);
@@ -129,7 +129,7 @@ var S = class {
129
129
  let s = "";
130
130
  throw e.status === 401 || e.status === 403 ? s = " Check `userJwt` (and that it has not expired)." : e.status === 404 && (s = " Check that `baseUrl` points at your AGO API root."), new d(`HTTP ${e.status}: ${e.statusText}.${s}`, "http_error", e.status, "api_error");
131
131
  }
132
- }, k = class {
132
+ }, $ = class {
133
133
  constructor() {
134
134
  this.functions = /* @__PURE__ */ new Map();
135
135
  }
@@ -166,13 +166,13 @@ var S = class {
166
166
  }
167
167
  async execute(e, t) {
168
168
  const s = this.functions.get(e);
169
- if (!s) throw new g(`Function "${e}" is not registered`, e);
169
+ if (!s) throw new f(`Function "${e}" is not registered`, e);
170
170
  o.log(`Executing function: ${e}`, t);
171
171
  try {
172
172
  const n = await s.handler(t);
173
173
  return o.log(`Function ${e} completed:`, n), n;
174
174
  } catch (n) {
175
- throw o.error(`Function ${e} failed:`, n), new g(`Function "${e}" execution failed: ${n instanceof Error ? n.message : "Unknown error"}`, e, n instanceof Error ? n : void 0);
175
+ throw o.error(`Function ${e} failed:`, n), new f(`Function "${e}" execution failed: ${n instanceof Error ? n.message : "Unknown error"}`, e, n instanceof Error ? n : void 0);
176
176
  }
177
177
  }
178
178
  clear() {
@@ -214,12 +214,16 @@ var S = class {
214
214
  clear() {
215
215
  this.entries.clear(), this.dynamicProviders.clear(), o.log("ClientContext cleared");
216
216
  }
217
- }, x = class {
217
+ };
218
+ function m(e) {
219
+ return e === null || typeof e != "object" ? JSON.stringify(e) ?? "null" : Array.isArray(e) ? `[${e.map(m).join(",")}]` : `{${Object.keys(e).sort().map((t) => `${JSON.stringify(t)}:${m(e[t])}`).join(",")}}`;
220
+ }
221
+ var x = class {
218
222
  constructor(e) {
219
- this.callbacks = e, this.buffer = "", this.message = {}, this.toolCalls = [], this.sources = [], this.followUpReplies = [], this.isFirstChunk = !0, this.answerCompleteEmitted = !1;
223
+ this.callbacks = e, this.buffer = "", this.message = {}, this.toolCalls = [], this.sources = [], this.followUpReplies = [], this.isFirstChunk = !0, this.answerCompleteEmitted = !1, this.firedClientFunctions = /* @__PURE__ */ new Set();
220
224
  }
221
225
  async processStream(e) {
222
- if (!e.body) throw new m("Response has no body. The endpoint did not return a stream: check that `baseUrl` points at an AGO API and nothing (proxy, mock) strips the SSE body.", "stream_no_body");
226
+ if (!e.body) throw new g("Response has no body. The endpoint did not return a stream: check that `baseUrl` points at an AGO API and nothing (proxy, mock) strips the SSE body.", "stream_no_body");
223
227
  const t = e.body.getReader(), s = new TextDecoder();
224
228
  try {
225
229
  for (; ; ) {
@@ -230,7 +234,7 @@ var S = class {
230
234
  }
231
235
  return this.buffer.trim() && this.processBuffer(), this.buildFinalMessage();
232
236
  } catch (n) {
233
- const i = n instanceof Error ? n : new m("Stream processing failed mid-flight. The connection may have dropped; retry the message.");
237
+ const i = n instanceof Error ? n : new g("Stream processing failed mid-flight. The connection may have dropped; retry the message.");
234
238
  throw this.callbacks.onError?.(i), i;
235
239
  } finally {
236
240
  t.releaseLock();
@@ -276,12 +280,16 @@ var S = class {
276
280
  title: s.title,
277
281
  url: s.use_external_link ? s.external_link_url : s.internal_link_url
278
282
  };
279
- })), e.type === "client_function" && e.function_name && this.callbacks.onClientFunction?.({
280
- invocationId: e.id || "",
281
- functionName: e.function_name,
282
- arguments: e.arguments || {},
283
- conversationId: this.message.conversationId || ""
284
- }), e.tool_call_data && e.type && e.type !== "client_function") {
283
+ })), e.type === "client_function" && e.function_name) {
284
+ const t = `${e.function_name}::${m(e.arguments ?? {})}`;
285
+ this.firedClientFunctions.has(t) || (this.firedClientFunctions.add(t), this.callbacks.onClientFunction?.({
286
+ invocationId: e.id || "",
287
+ functionName: e.function_name,
288
+ arguments: e.arguments || {},
289
+ conversationId: this.message.conversationId || ""
290
+ }));
291
+ }
292
+ if (e.tool_call_data && e.type && e.type !== "client_function") {
285
293
  const t = this.parseToolCall(e);
286
294
  this.callbacks.onToolCall?.(t);
287
295
  const s = this.toolCalls.findIndex((n) => n.id === t.id);
@@ -322,11 +330,11 @@ var S = class {
322
330
  return this.callbacks.onComplete?.(e), e;
323
331
  }
324
332
  };
325
- function R(e) {
333
+ function U(e) {
326
334
  const t = e.message.toLowerCase();
327
335
  return t.includes("load failed") || t.includes("failed to fetch") || t.includes("network") || t.includes("abort");
328
336
  }
329
- var $ = class {
337
+ var I = class {
330
338
  constructor() {
331
339
  this.handlers = /* @__PURE__ */ new Map();
332
340
  }
@@ -367,16 +375,16 @@ var $ = class {
367
375
  removeAllListeners(e) {
368
376
  e ? this.handlers.delete(e) : this.handlers.clear();
369
377
  }
370
- }, p = '`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the live demo endpoint https://playground.api.useago.com. See docs/general/configuration.md#error-codes (config_missing_base_url).', I = /^[a-z][a-z0-9+.-]*:\/\//i, y = !1;
371
- function w(e, t = "AgoClient") {
372
- if (typeof e != "object" || e === null) throw new h(`${t}: ${p}`, "config_missing_base_url");
378
+ }, y = '`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the live demo endpoint https://playground.api.useago.com. See docs/general/configuration.md#error-codes (config_missing_base_url).', R = /^[a-z][a-z0-9+.-]*:\/\//i, w = !1;
379
+ function v(e, t = "AgoClient") {
380
+ if (typeof e != "object" || e === null) throw new h(`${t}: ${y}`, "config_missing_base_url");
373
381
  const s = e.baseUrl;
374
- if (typeof s != "string" || s.trim() === "") throw new h(`${t}: ${p}`, "config_missing_base_url");
375
- !s.startsWith("/") && !I.test(s) && (y || (y = !0, console.warn(`[AGO] ${t}: \`baseUrl\` has no protocol and is not a relative path (config_suspect_base_url). Requests will fail: Node throws a URL parse error, browsers fetch it as a relative path. Use "https://..." (or a "/path" for a same-origin proxy).`)));
382
+ if (typeof s != "string" || s.trim() === "") throw new h(`${t}: ${y}`, "config_missing_base_url");
383
+ !s.startsWith("/") && !R.test(s) && (w || (w = !0, console.warn(`[AGO] ${t}: \`baseUrl\` has no protocol and is not a relative path (config_suspect_base_url). Requests will fail: Node throws a URL parse error, browsers fetch it as a relative path. Use "https://..." (or a "/path" for a same-origin proxy).`)));
376
384
  }
377
- var U = class C {
385
+ var F = class b {
378
386
  constructor(t) {
379
- this.warnedEmptyConversations = /* @__PURE__ */ new Set(), w(t, "AgoClient"), this.config = t, this.httpClient = new S(t), this.functionRegistry = new k(), this.contextRegistry = new A(), this.eventEmitter = new $(), t.debug && o.enable(), o.log("AgoClient initialized");
387
+ this.warnedEmptyConversations = /* @__PURE__ */ new Set(), v(t, "AgoClient"), this.config = t, this.httpClient = new k(t), this.functionRegistry = new $(), this.contextRegistry = new A(), this.eventEmitter = new I(), t.debug && o.enable(), o.log("AgoClient initialized");
380
388
  }
381
389
  async sendMessage(t, s) {
382
390
  const n = this.functionRegistry.getSchemas(), i = this.contextRegistry.getSnapshot(), r = this.config.agent || this.config.defaultAgentId, a = {
@@ -389,7 +397,7 @@ var U = class C {
389
397
  if (s?.files && s.files.length > 0) {
390
398
  const c = new FormData();
391
399
  c.append("content", t), s.conversationId && c.append("conversation_id", s.conversationId), (s.agentId || r) && c.append("agent_id", s.agentId || r || ""), n.length > 0 && c.append("client_functions", JSON.stringify(n)), i && c.append("client_context", JSON.stringify(i));
392
- for (const b of s.files) c.append("files", b);
400
+ for (const E of s.files) c.append("files", E);
393
401
  l = await this.httpClient.postFormData("/api/sdk/v1/messages", c);
394
402
  } else l = await this.httpClient.postStream("/api/sdk/v1/messages", a);
395
403
  return this.processSSEResponse(l);
@@ -478,7 +486,7 @@ var U = class C {
478
486
  role: i.role,
479
487
  status: i.status,
480
488
  createdAt: new Date(i.created_at),
481
- toolCalls: C.mapPersistedToolCalls(i.tool_call_data)
489
+ toolCalls: b.mapPersistedToolCalls(i.tool_call_data)
482
490
  }))
483
491
  };
484
492
  return this.eventEmitter.emit("conversation:loaded", n), n;
@@ -619,24 +627,24 @@ ${i}`,
619
627
  ...this.config,
620
628
  ...s
621
629
  };
622
- w(n, "AgoClient.updateConfig"), this.config = n, this.httpClient.updateConfig(s), s.debug !== void 0 && (s.debug ? o.enable() : o.disable());
630
+ v(n, "AgoClient.updateConfig"), this.config = n, this.httpClient.updateConfig(s), s.debug !== void 0 && (s.debug ? o.enable() : o.disable());
623
631
  }
624
632
  destroy() {
625
633
  this.eventEmitter.removeAllListeners(), this.functionRegistry.clear(), this.contextRegistry.clear(), o.log("AgoClient destroyed");
626
634
  }
627
635
  };
628
636
  export {
629
- R as a,
637
+ U as a,
630
638
  o as c,
631
- g as d,
639
+ f as d,
632
640
  u as f,
633
641
  x as i,
634
642
  d as l,
635
- w as n,
643
+ v as n,
636
644
  A as o,
637
- m as p,
638
- $ as r,
639
- k as s,
640
- U as t,
645
+ g as p,
646
+ I as r,
647
+ $ as s,
648
+ F as t,
641
649
  h as u
642
650
  };
package/dist/angular.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./AgoClient-nYVPdI5x.cjs");var n=class{constructor(e){this.client=new o.AgoClient(e),this.messages$=this.fromEvent("message:complete"),this.chunks$=this.fromEvent("message:chunk"),this.errors$=this.fromEvent("message:error"),this.messageStart$=this.fromEvent("message:start")}fromEvent(e){const t=this.client;return{subscribe(i){const s=r=>{i.next?.(r)};return t.on(e,s),{unsubscribe:()=>t.off(e,s)}}}}sendMessage(e,t){return this.client.sendMessage(e,t)}getConversations(){return this.client.getConversations()}getConversation(e){return this.client.getConversation(e)}getMessages(e){return this.client.getMessages(e)}submitToolCallForm(e,t){return this.client.submitToolCallForm(e,t)}confirmToolCall(e){return this.client.confirmToolCall(e)}rejectToolCall(e){return this.client.rejectToolCall(e)}submitFeedback(e,t){return this.client.submitFeedback(e,t)}registerFunction(e,t,i){typeof e=="object"?this.client.registerFunction(e):this.client.registerFunction(e,t,i)}unregisterFunction(e){return this.client.unregisterFunction(e)}registerNavigationFunction(e,t){this.client.registerNavigationFunction(e,t)}on(e,t){this.client.on(e,t)}off(e,t){this.client.off(e,t)}updateConfig(e){this.client.updateConfig(e)}getClient(){return this.client}destroy(){this.client.destroy()}};function c(e){return{provide:n,useValue:new n(e)}}exports.AgoService=n;exports.provideAgo=c;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./AgoClient-1jgDndKs.cjs");var n=class{constructor(e){this.client=new o.AgoClient(e),this.messages$=this.fromEvent("message:complete"),this.chunks$=this.fromEvent("message:chunk"),this.errors$=this.fromEvent("message:error"),this.messageStart$=this.fromEvent("message:start")}fromEvent(e){const t=this.client;return{subscribe(i){const s=r=>{i.next?.(r)};return t.on(e,s),{unsubscribe:()=>t.off(e,s)}}}}sendMessage(e,t){return this.client.sendMessage(e,t)}getConversations(){return this.client.getConversations()}getConversation(e){return this.client.getConversation(e)}getMessages(e){return this.client.getMessages(e)}submitToolCallForm(e,t){return this.client.submitToolCallForm(e,t)}confirmToolCall(e){return this.client.confirmToolCall(e)}rejectToolCall(e){return this.client.rejectToolCall(e)}submitFeedback(e,t){return this.client.submitFeedback(e,t)}registerFunction(e,t,i){typeof e=="object"?this.client.registerFunction(e):this.client.registerFunction(e,t,i)}unregisterFunction(e){return this.client.unregisterFunction(e)}registerNavigationFunction(e,t){this.client.registerNavigationFunction(e,t)}on(e,t){this.client.on(e,t)}off(e,t){this.client.off(e,t)}updateConfig(e){this.client.updateConfig(e)}getClient(){return this.client}destroy(){this.client.destroy()}};function c(e){return{provide:n,useValue:new n(e)}}exports.AgoService=n;exports.provideAgo=c;
package/dist/angular.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as o } from "./AgoClient-CBLJfu90.js";
1
+ import { t as o } from "./AgoClient-j1sk1hK5.js";
2
2
  var n = class {
3
3
  constructor(t) {
4
4
  this.client = new o(t), this.messages$ = this.fromEvent("message:complete"), this.chunks$ = this.fromEvent("message:chunk"), this.errors$ = this.fromEvent("message:error"), this.messageStart$ = this.fromEvent("message:start");
@@ -1 +1 @@
1
- const d=require("./createFormCollector-CQKfRjfj.cjs");var f="ago_widget_id",g="ago_last_thread",y=7200*1e3;function v(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=Math.floor(Math.random()*16);return(e==="x"?r:r&3|8).toString(16)})}function _(e={}){const r=e.key??f,i=e.threadKey??g,u=e.ttlMs??y,l=e.storage??(typeof localStorage<"u"?localStorage:void 0);let n=e.widgetId??"";if(!n&&l)try{n=l.getItem(r)??""}catch{}if(n||(n=v()),l)try{l.setItem(r,n)}catch{}const o=d.createStore({value:null,lastMessageAt:null},{key:i,storage:l}),c=o.get();c.value!==null&&s(c.lastMessageAt)&&o.set({value:null,lastMessageAt:null});function s(t){return t===null?!0:Number.isFinite(u)?Date.now()-t>u:!1}return{widgetId:n,key:r,getLastActiveThread(){const{value:t,lastMessageAt:a}=o.get();return t===null||s(a)?null:t},setActiveThread(t,a){const x=a==null?null:a instanceof Date?a.getTime():a;o.set({value:t,lastMessageAt:x})},clear(){o.set({value:null,lastMessageAt:null})}}}Object.defineProperty(exports,"createConversationSession",{enumerable:!0,get:function(){return _}});
1
+ const d=require("./createFormCollector-B8V9YSGe.cjs");var f="ago_widget_id",g="ago_last_thread",y=7200*1e3;function v(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=Math.floor(Math.random()*16);return(e==="x"?r:r&3|8).toString(16)})}function _(e={}){const r=e.key??f,i=e.threadKey??g,u=e.ttlMs??y,l=e.storage??(typeof localStorage<"u"?localStorage:void 0);let n=e.widgetId??"";if(!n&&l)try{n=l.getItem(r)??""}catch{}if(n||(n=v()),l)try{l.setItem(r,n)}catch{}const o=d.createStore({value:null,lastMessageAt:null},{key:i,storage:l}),c=o.get();c.value!==null&&s(c.lastMessageAt)&&o.set({value:null,lastMessageAt:null});function s(t){return t===null?!0:Number.isFinite(u)?Date.now()-t>u:!1}return{widgetId:n,key:r,getLastActiveThread(){const{value:t,lastMessageAt:a}=o.get();return t===null||s(a)?null:t},setActiveThread(t,a){const x=a==null?null:a instanceof Date?a.getTime():a;o.set({value:t,lastMessageAt:x})},clear(){o.set({value:null,lastMessageAt:null})}}}Object.defineProperty(exports,"createConversationSession",{enumerable:!0,get:function(){return _}});
@@ -1,4 +1,4 @@
1
- import { i as d } from "./createFormCollector-CyD7KnjG.js";
1
+ import { i as d } from "./createFormCollector-BPKzKDeX.js";
2
2
  var f = "ago_widget_id", g = "ago_last_thread", y = 7200 * 1e3;
3
3
  function v() {
4
4
  return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (e) => {
@@ -1 +1 @@
1
- const O=require("./AgoClient-nYVPdI5x.cjs");function _(o,e){const i=e?e.storage??(typeof localStorage<"u"?localStorage:void 0):void 0;let t=o;if(e&&i)try{const c=i.getItem(e.key);c!=null&&(t=JSON.parse(c))}catch{}const a=new Set,f=()=>a.forEach(c=>c(t));function d(){if(e&&i)try{i.setItem(e.key,JSON.stringify(t))}catch{}}return{get:()=>t,set:c=>{t=c,d(),f()},subscribe:c=>(a.add(c),()=>{a.delete(c)})}}var k=/^[a-zA-Z0-9_-]{1,40}$/,P=o=>o==null||o==="";function q(o,e){const i=e[o.property];if(P(i))return!1;if(Array.isArray(o.value))return o.value.some(f=>String(i)===String(f));if(!o.op)return String(i)===String(o.value);const t=Number(i),a=Number(o.value);if(Number.isNaN(t)||Number.isNaN(a))return!1;switch(o.op){case">=":return t>=a;case"<=":return t<=a;case">":return t>a;case"<":return t<a;default:return O.logger.warn(`Unknown requiredWhen op "${o.op}"; treating as not required.`),!1}}function p(o,e){const i=o.properties??{},t=new Set;for(const f of o.required??[]){const d=i[f]?.requiredWhen;(!d||q(d,e))&&t.add(f)}for(const[f,d]of Object.entries(i))d.requiredWhen&&q(d.requiredWhen,e)&&t.add(f);const a=[...t].filter(f=>P(e[f]));return{missing:a,complete:a.length===0}}function W(o){const e={};for(const[i,t]of Object.entries(o.properties??{}))e[i]={type:t.type,...t.description!=null&&{description:t.description},...t.enum&&{enum:t.enum},...t.default!==void 0&&{default:t.default}};return{type:"object",properties:e,required:[]}}function j(o){const{name:e,description:i,schema:t}=o;if(!k.test(e))throw new Error(`Invalid form collector name "${e}": must match ${k} (it becomes the update_/submit_ function names).`);const a=typeof o.submit=="string"?o.submit?{via:"client",url:o.submit}:!1:o.submit??!1,f=t.properties??{},d=r=>{const n={};for(const[u,s]of Object.entries(r)){const l=f[u];if(l)if(s==null)n[u]=s;else if(l.type==="number"||l.type==="integer"){const b=typeof s=="number"?s:Number(s);n[u]=Number.isNaN(b)?s:b}else l.type==="boolean"?n[u]=typeof s=="boolean"?s:s==="true"?!0:s==="false"?!1:!!s:n[u]=s}return n},c=o.initialValues??{},m=_({values:c,submitted:!1}),v=r=>{const n=m.get(),u={...n,values:{...n.values,...r}};return m.set(u),u};let h=null;const N=async()=>{const{values:r}=m.get(),{complete:n,missing:u}=p(t,r);if(!n)return{ok:!1,missing:u};if(!a)return{ok:!1,error:"No submit target configured for this form collector."};const s=r;try{let l;if(a.via==="client")if("handler"in a)l=await a.handler(s);else{const b=await fetch(a.url,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(s)});if(!b.ok)return{ok:!1,error:`Submit failed: HTTP ${b.status}`};l=await b.json().catch(()=>{})}else{if(!h)return{ok:!1,error:"Backend submit requires install(client) (or useFormCollector) first."};l=await h.submitFormCollector(e,s)}return m.set({...m.get(),submitted:!0}),{ok:!0,result:l}}catch(l){const b=l instanceof Error?l.message:"Submit failed";return O.logger.error(`FormCollector "${e}" submit failed:`,l),{ok:!1,error:b}}},S={name:`update_${e}`,description:`Fill or update fields of the "${e}" form. ${i} Pass any subset of fields; call it repeatedly to fill the form as the user provides information. Returns the current values and which required fields are still missing.`,parameters:W(t),handler:r=>{const n=v(d(r)),{missing:u}=p(t,n.values);return{ok:!0,values:n.values,missing:u}}},g=[S];a&&g.push({name:`submit_${e}`,description:`Submit the completed "${e}" form. Only call this once every required field is collected and the user has confirmed. If fields are missing it returns them instead of submitting.`,parameters:{type:"object",properties:{}},handler:()=>N()});const T="client__",C=a?`submit_${e}`:null,E=r=>{const n=r.functionName??r.toolName;if(n)return n.startsWith(T)?n.slice(8):n},$=r=>{let n={...c},u=!1;for(const s of r){const l=E(s);l===S.name?s.arguments&&(n={...n,...d(s.arguments)}):C&&l===C&&s.status?.toLowerCase()==="done"&&(u=!0)}m.set({values:n,submitted:u})},y=`form:${e}`,w=()=>{const{values:r,submitted:n}=m.get(),{missing:u,complete:s}=p(t,r),l=a?` When nothing is missing and the user confirms, call submit_${e}.`:"",b=n?`The "${e}" form has been submitted.`:`You are currently collecting information from the user to fill the "${e}" form.`;return{name:`Form: ${e}`,description:`${b} ${i} There are conditionnals questions/values to collected, you can find this information with the requiredWhen field in the form. The form schema is the following: ${JSON.stringify(t)}. Data collected so far: ${JSON.stringify(r)}. Call update_${e} with any fields the user provides; ask only for what is still missing.${l}`,data:{values:r,missing:u,complete:s,submitted:n}}},F=r=>{$((r.messages??[]).flatMap(n=>n.toolCalls??[]))};return{name:e,store:m,functions:g,contextKey:y,contextProvider:w,install:r=>{h=r;for(const u of g)r.register(u);r.addDynamicContext(y,w);const n=m.subscribe(()=>r.notifyContextChanged());return r.on("conversation:loaded",F),()=>{n();for(const u of g)r.unregisterFunction(u.name);r.removeDynamicContext(y),r.off("conversation:loaded",F),h===r&&(h=null)}},hydrate:$,submit:N,getValues:()=>m.get().values,setValues:r=>{v(d(r))},reset:()=>{m.set({values:c,submitted:!1})},getStatus:()=>p(t,m.get().values)}}async function x(o,e){const i=await o.getFormCollector(e.name);return j({name:i.name,description:e.description??i.description,schema:e.schema??i.schema,submit:e.submit??i.submit,initialValues:e.initialValues})}Object.defineProperty(exports,"createFormCollector",{enumerable:!0,get:function(){return j}});Object.defineProperty(exports,"createStore",{enumerable:!0,get:function(){return _}});Object.defineProperty(exports,"deriveFormStatus",{enumerable:!0,get:function(){return p}});Object.defineProperty(exports,"loadFormCollector",{enumerable:!0,get:function(){return x}});
1
+ const O=require("./AgoClient-1jgDndKs.cjs");function _(o,e){const i=e?e.storage??(typeof localStorage<"u"?localStorage:void 0):void 0;let t=o;if(e&&i)try{const c=i.getItem(e.key);c!=null&&(t=JSON.parse(c))}catch{}const a=new Set,f=()=>a.forEach(c=>c(t));function d(){if(e&&i)try{i.setItem(e.key,JSON.stringify(t))}catch{}}return{get:()=>t,set:c=>{t=c,d(),f()},subscribe:c=>(a.add(c),()=>{a.delete(c)})}}var k=/^[a-zA-Z0-9_-]{1,40}$/,P=o=>o==null||o==="";function q(o,e){const i=e[o.property];if(P(i))return!1;if(Array.isArray(o.value))return o.value.some(f=>String(i)===String(f));if(!o.op)return String(i)===String(o.value);const t=Number(i),a=Number(o.value);if(Number.isNaN(t)||Number.isNaN(a))return!1;switch(o.op){case">=":return t>=a;case"<=":return t<=a;case">":return t>a;case"<":return t<a;default:return O.logger.warn(`Unknown requiredWhen op "${o.op}"; treating as not required.`),!1}}function p(o,e){const i=o.properties??{},t=new Set;for(const f of o.required??[]){const d=i[f]?.requiredWhen;(!d||q(d,e))&&t.add(f)}for(const[f,d]of Object.entries(i))d.requiredWhen&&q(d.requiredWhen,e)&&t.add(f);const a=[...t].filter(f=>P(e[f]));return{missing:a,complete:a.length===0}}function W(o){const e={};for(const[i,t]of Object.entries(o.properties??{}))e[i]={type:t.type,...t.description!=null&&{description:t.description},...t.enum&&{enum:t.enum},...t.default!==void 0&&{default:t.default}};return{type:"object",properties:e,required:[]}}function j(o){const{name:e,description:i,schema:t}=o;if(!k.test(e))throw new Error(`Invalid form collector name "${e}": must match ${k} (it becomes the update_/submit_ function names).`);const a=typeof o.submit=="string"?o.submit?{via:"client",url:o.submit}:!1:o.submit??!1,f=t.properties??{},d=r=>{const n={};for(const[u,s]of Object.entries(r)){const l=f[u];if(l)if(s==null)n[u]=s;else if(l.type==="number"||l.type==="integer"){const b=typeof s=="number"?s:Number(s);n[u]=Number.isNaN(b)?s:b}else l.type==="boolean"?n[u]=typeof s=="boolean"?s:s==="true"?!0:s==="false"?!1:!!s:n[u]=s}return n},c=o.initialValues??{},m=_({values:c,submitted:!1}),v=r=>{const n=m.get(),u={...n,values:{...n.values,...r}};return m.set(u),u};let h=null;const N=async()=>{const{values:r}=m.get(),{complete:n,missing:u}=p(t,r);if(!n)return{ok:!1,missing:u};if(!a)return{ok:!1,error:"No submit target configured for this form collector."};const s=r;try{let l;if(a.via==="client")if("handler"in a)l=await a.handler(s);else{const b=await fetch(a.url,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(s)});if(!b.ok)return{ok:!1,error:`Submit failed: HTTP ${b.status}`};l=await b.json().catch(()=>{})}else{if(!h)return{ok:!1,error:"Backend submit requires install(client) (or useFormCollector) first."};l=await h.submitFormCollector(e,s)}return m.set({...m.get(),submitted:!0}),{ok:!0,result:l}}catch(l){const b=l instanceof Error?l.message:"Submit failed";return O.logger.error(`FormCollector "${e}" submit failed:`,l),{ok:!1,error:b}}},S={name:`update_${e}`,description:`Fill or update fields of the "${e}" form. ${i} Pass any subset of fields; call it repeatedly to fill the form as the user provides information. Returns the current values and which required fields are still missing.`,parameters:W(t),handler:r=>{const n=v(d(r)),{missing:u}=p(t,n.values);return{ok:!0,values:n.values,missing:u}}},g=[S];a&&g.push({name:`submit_${e}`,description:`Submit the completed "${e}" form. Only call this once every required field is collected and the user has confirmed. If fields are missing it returns them instead of submitting.`,parameters:{type:"object",properties:{}},handler:()=>N()});const T="client__",C=a?`submit_${e}`:null,E=r=>{const n=r.functionName??r.toolName;if(n)return n.startsWith(T)?n.slice(8):n},$=r=>{let n={...c},u=!1;for(const s of r){const l=E(s);l===S.name?s.arguments&&(n={...n,...d(s.arguments)}):C&&l===C&&s.status?.toLowerCase()==="done"&&(u=!0)}m.set({values:n,submitted:u})},y=`form:${e}`,w=()=>{const{values:r,submitted:n}=m.get(),{missing:u,complete:s}=p(t,r),l=a?` When nothing is missing and the user confirms, call submit_${e}.`:"",b=n?`The "${e}" form has been submitted.`:`You are currently collecting information from the user to fill the "${e}" form.`;return{name:`Form: ${e}`,description:`${b} ${i} There are conditionnals questions/values to collected, you can find this information with the requiredWhen field in the form. The form schema is the following: ${JSON.stringify(t)}. Data collected so far: ${JSON.stringify(r)}. Call update_${e} with any fields the user provides; ask only for what is still missing.${l}`,data:{values:r,missing:u,complete:s,submitted:n}}},F=r=>{$((r.messages??[]).flatMap(n=>n.toolCalls??[]))};return{name:e,store:m,functions:g,contextKey:y,contextProvider:w,install:r=>{h=r;for(const u of g)r.register(u);r.addDynamicContext(y,w);const n=m.subscribe(()=>r.notifyContextChanged());return r.on("conversation:loaded",F),()=>{n();for(const u of g)r.unregisterFunction(u.name);r.removeDynamicContext(y),r.off("conversation:loaded",F),h===r&&(h=null)}},hydrate:$,submit:N,getValues:()=>m.get().values,setValues:r=>{v(d(r))},reset:()=>{m.set({values:c,submitted:!1})},getStatus:()=>p(t,m.get().values)}}async function x(o,e){const i=await o.getFormCollector(e.name);return j({name:i.name,description:e.description??i.description,schema:e.schema??i.schema,submit:e.submit??i.submit,initialValues:e.initialValues})}Object.defineProperty(exports,"createFormCollector",{enumerable:!0,get:function(){return j}});Object.defineProperty(exports,"createStore",{enumerable:!0,get:function(){return _}});Object.defineProperty(exports,"deriveFormStatus",{enumerable:!0,get:function(){return p}});Object.defineProperty(exports,"loadFormCollector",{enumerable:!0,get:function(){return x}});
@@ -1,4 +1,4 @@
1
- import { c as _ } from "./AgoClient-CBLJfu90.js";
1
+ import { c as _ } from "./AgoClient-j1sk1hK5.js";
2
2
  function E(n, e) {
3
3
  const i = e ? e.storage ?? (typeof localStorage < "u" ? localStorage : void 0) : void 0;
4
4
  let t = n;
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./AgoClient-nYVPdI5x.cjs"),m=require("./createFormCollector-CQKfRjfj.cjs"),p=require("./createConversationSession-CnIchjFa.cjs"),w=require("./createMockClient-zHQ0cjUH.cjs");require("./testing.cjs");const g=require("./functions-DsmzgHjC.cjs");function h(e){return e}function E(e,o){return e.on("message:complete",o),()=>e.off("message:complete",o)}function S(e,o){return e.on("message:chunk",o),()=>e.off("message:chunk",o)}function y(e,o){return e.on("message:start",o),()=>e.off("message:start",o)}function v(e,o){return e.on("message:error",o),()=>e.off("message:error",o)}function b(e,o){return e.on("toolCall:received",o),()=>e.off("toolCall:received",o)}function F(e,o){return e.on("function:invoke",o),()=>e.off("function:invoke",o)}async function*M(e,o,l){const a=[];let r=null,s=!1;const c=i=>{a.push(i),r?.()},f=i=>c({type:"start",data:i}),t=i=>c({type:"chunk",data:i}),u=i=>{c({type:"complete",data:i}),s=!0,r?.()},d=i=>{c({type:"error",data:i}),s=!0,r?.()},C=i=>c({type:"toolCall",data:i});e.on("message:start",f),e.on("message:chunk",t),e.on("message:complete",u),e.on("message:error",d),e.on("toolCall:received",C),e.sendMessage(o,l).catch(()=>{s=!0,r?.()});try{for(;!s||a.length>0;)a.length>0?yield a.shift():(await new Promise(i=>{r=i}),r=null)}finally{e.off("message:start",f),e.off("message:chunk",t),e.off("message:complete",u),e.off("message:error",d),e.off("toolCall:received",C)}}function A(e){let o,l,a,r,s,c;if(typeof window<"u"&&window.AGO){const t=window.AGO;o=t.basepath,l=t.widgetId,a=t.agent||t.defaultAgent,r=t.permission,s=t.email,c=t.jwt}if(typeof document<"u"){const t=u=>document.querySelector(`meta[name="${u}"]`)?.getAttribute("content")||void 0;o=o||t("ago-base-url"),l=l||t("ago-widget-id"),a=a||t("ago-agent")||t("ago-agent-id"),r=r||t("ago-permission"),s=s||t("ago-user-email")}if(typeof document<"u"){const t=[document.body,...Array.from(document.querySelectorAll("script[data-ago-base-url]"))].filter(Boolean);for(const u of t)u&&(o=o||u.getAttribute("data-ago-base-url")||void 0,l=l||u.getAttribute("data-ago-widget-id")||void 0,a=a||u.getAttribute("data-ago-agent")||u.getAttribute("data-ago-agent-id")||void 0,r=r||u.getAttribute("data-ago-permission")||void 0,s=s||u.getAttribute("data-ago-user-email")||void 0)}o=e?.baseUrl||o,l=e?.widgetId||l,a=e?.agent||e?.defaultAgentId||a,r=e?.permission||r,s=e?.userEmail||s,c=e?.userJwt||c;const f=e?.debug;return o?{baseUrl:o,widgetId:l,agent:a,permission:r,userEmail:s,userJwt:c,debug:f}:null}function k(e){const o=A(e);if(!o)throw new n.AgoError('createAgo(): could not detect AGO configuration. Set window.AGO, add <meta name="ago-base-url">, or pass { baseUrl } explicitly.',"config_missing_base_url");return new n.AgoClient(o)}function q(e,o){return{...e,handler:o}}exports.AgoApiError=n.AgoApiError;exports.AgoClient=n.AgoClient;exports.AgoError=n.AgoError;exports.AgoFunctionError=n.AgoFunctionError;exports.AgoNetworkError=n.AgoNetworkError;exports.AgoStreamError=n.AgoStreamError;exports.ClientContextRegistry=n.ClientContextRegistry;exports.EventEmitter=n.EventEmitter;exports.FunctionRegistry=n.FunctionRegistry;exports.SSEHandler=n.SSEHandler;exports.autoDetectConfig=A;exports.copyToClipboard=g.copyToClipboard;exports.createAgo=k;exports.createConversationSession=p.createConversationSession;exports.createFormCollector=m.createFormCollector;exports.createMessageStream=M;exports.createMockClient=w.createMockClient;exports.createStore=m.createStore;exports.defineFunction=h;exports.deriveFormStatus=m.deriveFormStatus;exports.getLocalStorage=g.getLocalStorage;exports.getUserLocation=g.getUserLocation;exports.highlightElement=g.highlightElement;exports.isStreamNetworkError=n.isStreamNetworkError;exports.loadFormCollector=m.loadFormCollector;exports.logger=n.logger;exports.onFunctionInvoke=F;exports.onMessage=E;exports.onMessageChunk=S;exports.onMessageError=v;exports.onMessageStart=y;exports.onToolCall=b;exports.openUrl=g.openUrl;exports.scrollToElement=g.scrollToElement;exports.setLocalStorage=g.setLocalStorage;exports.setTheme=g.setTheme;exports.showConfirmDialog=g.showConfirmDialog;exports.showNotification=g.showNotification;exports.showToast=g.showToast;exports.submitForm=g.submitForm;exports.trackEvent=g.trackEvent;exports.validateConfig=n.validateConfig;exports.withHandler=q;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./AgoClient-1jgDndKs.cjs"),m=require("./createFormCollector-B8V9YSGe.cjs"),p=require("./createConversationSession-BYNhYbkY.cjs"),w=require("./createMockClient-zHQ0cjUH.cjs");require("./testing.cjs");const g=require("./functions-DsmzgHjC.cjs");function h(e){return e}function E(e,o){return e.on("message:complete",o),()=>e.off("message:complete",o)}function S(e,o){return e.on("message:chunk",o),()=>e.off("message:chunk",o)}function y(e,o){return e.on("message:start",o),()=>e.off("message:start",o)}function v(e,o){return e.on("message:error",o),()=>e.off("message:error",o)}function b(e,o){return e.on("toolCall:received",o),()=>e.off("toolCall:received",o)}function F(e,o){return e.on("function:invoke",o),()=>e.off("function:invoke",o)}async function*M(e,o,l){const a=[];let r=null,s=!1;const c=i=>{a.push(i),r?.()},f=i=>c({type:"start",data:i}),t=i=>c({type:"chunk",data:i}),u=i=>{c({type:"complete",data:i}),s=!0,r?.()},d=i=>{c({type:"error",data:i}),s=!0,r?.()},C=i=>c({type:"toolCall",data:i});e.on("message:start",f),e.on("message:chunk",t),e.on("message:complete",u),e.on("message:error",d),e.on("toolCall:received",C),e.sendMessage(o,l).catch(()=>{s=!0,r?.()});try{for(;!s||a.length>0;)a.length>0?yield a.shift():(await new Promise(i=>{r=i}),r=null)}finally{e.off("message:start",f),e.off("message:chunk",t),e.off("message:complete",u),e.off("message:error",d),e.off("toolCall:received",C)}}function A(e){let o,l,a,r,s,c;if(typeof window<"u"&&window.AGO){const t=window.AGO;o=t.basepath,l=t.widgetId,a=t.agent||t.defaultAgent,r=t.permission,s=t.email,c=t.jwt}if(typeof document<"u"){const t=u=>document.querySelector(`meta[name="${u}"]`)?.getAttribute("content")||void 0;o=o||t("ago-base-url"),l=l||t("ago-widget-id"),a=a||t("ago-agent")||t("ago-agent-id"),r=r||t("ago-permission"),s=s||t("ago-user-email")}if(typeof document<"u"){const t=[document.body,...Array.from(document.querySelectorAll("script[data-ago-base-url]"))].filter(Boolean);for(const u of t)u&&(o=o||u.getAttribute("data-ago-base-url")||void 0,l=l||u.getAttribute("data-ago-widget-id")||void 0,a=a||u.getAttribute("data-ago-agent")||u.getAttribute("data-ago-agent-id")||void 0,r=r||u.getAttribute("data-ago-permission")||void 0,s=s||u.getAttribute("data-ago-user-email")||void 0)}o=e?.baseUrl||o,l=e?.widgetId||l,a=e?.agent||e?.defaultAgentId||a,r=e?.permission||r,s=e?.userEmail||s,c=e?.userJwt||c;const f=e?.debug;return o?{baseUrl:o,widgetId:l,agent:a,permission:r,userEmail:s,userJwt:c,debug:f}:null}function k(e){const o=A(e);if(!o)throw new n.AgoError('createAgo(): could not detect AGO configuration. Set window.AGO, add <meta name="ago-base-url">, or pass { baseUrl } explicitly.',"config_missing_base_url");return new n.AgoClient(o)}function q(e,o){return{...e,handler:o}}exports.AgoApiError=n.AgoApiError;exports.AgoClient=n.AgoClient;exports.AgoError=n.AgoError;exports.AgoFunctionError=n.AgoFunctionError;exports.AgoNetworkError=n.AgoNetworkError;exports.AgoStreamError=n.AgoStreamError;exports.ClientContextRegistry=n.ClientContextRegistry;exports.EventEmitter=n.EventEmitter;exports.FunctionRegistry=n.FunctionRegistry;exports.SSEHandler=n.SSEHandler;exports.autoDetectConfig=A;exports.copyToClipboard=g.copyToClipboard;exports.createAgo=k;exports.createConversationSession=p.createConversationSession;exports.createFormCollector=m.createFormCollector;exports.createMessageStream=M;exports.createMockClient=w.createMockClient;exports.createStore=m.createStore;exports.defineFunction=h;exports.deriveFormStatus=m.deriveFormStatus;exports.getLocalStorage=g.getLocalStorage;exports.getUserLocation=g.getUserLocation;exports.highlightElement=g.highlightElement;exports.isStreamNetworkError=n.isStreamNetworkError;exports.loadFormCollector=m.loadFormCollector;exports.logger=n.logger;exports.onFunctionInvoke=F;exports.onMessage=E;exports.onMessageChunk=S;exports.onMessageError=v;exports.onMessageStart=y;exports.onToolCall=b;exports.openUrl=g.openUrl;exports.scrollToElement=g.scrollToElement;exports.setLocalStorage=g.setLocalStorage;exports.setTheme=g.setTheme;exports.showConfirmDialog=g.showConfirmDialog;exports.showNotification=g.showNotification;exports.showToast=g.showToast;exports.submitForm=g.submitForm;exports.trackEvent=g.trackEvent;exports.validateConfig=n.validateConfig;exports.withHandler=q;
package/dist/index.d.cts CHANGED
@@ -1300,6 +1300,7 @@ export declare class SSEHandler {
1300
1300
  private followUpReplies;
1301
1301
  private isFirstChunk;
1302
1302
  private answerCompleteEmitted;
1303
+ private firedClientFunctions;
1303
1304
  constructor(callbacks: SSEHandlerCallbacks);
1304
1305
  /**
1305
1306
  * Process a streaming response
package/dist/index.d.ts CHANGED
@@ -1300,6 +1300,7 @@ export declare class SSEHandler {
1300
1300
  private followUpReplies;
1301
1301
  private isFirstChunk;
1302
1302
  private answerCompleteEmitted;
1303
+ private firedClientFunctions;
1303
1304
  constructor(callbacks: SSEHandlerCallbacks);
1304
1305
  /**
1305
1306
  * Process a streaming response
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { a as h, c as A, d as y, f as C, i as E, l as b, n as S, o as v, p as k, r as F, s as M, t as d, u as c } from "./AgoClient-CBLJfu90.js";
2
- import { i as I, n as U, r as G, t as O } from "./createFormCollector-CyD7KnjG.js";
3
- import { t as x } from "./createConversationSession-D3aHSSir.js";
1
+ import { a as h, c as A, d as y, f as C, i as E, l as b, n as S, o as v, p as k, r as F, s as M, t as d, u as c } from "./AgoClient-j1sk1hK5.js";
2
+ import { i as I, n as U, r as G, t as O } from "./createFormCollector-BPKzKDeX.js";
3
+ import { t as x } from "./createConversationSession-CZhoTCtD.js";
4
4
  import { t as N } from "./createMockClient-DwdxNwEn.js";
5
5
  import "./testing.js";
6
6
  import { a as H, c as J, d as R, f as j, i as B, l as P, m as $, o as z, p as K, r as Q, s as V, t as W, u as X } from "./functions-C1-5vadY.js";
package/dist/react.cjs CHANGED
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const fe=require("./rolldown-runtime-CaekUdDJ.cjs"),oi=require("./AgoClient-nYVPdI5x.cjs"),ve=require("./createFormCollector-CQKfRjfj.cjs"),ai=require("./createMockClient-zHQ0cjUH.cjs");let D=require("react");D=fe.__toESM(D,1);let z=require("react/jsx-runtime");function Un(e){const[n,t]=(0,D.useState)(!1),r=(0,D.useRef)(null),i=(0,D.useMemo)(()=>{if(r.current&&(r.current.destroy(),r.current=null),!e)return null;const l=new oi.AgoClient(e);return r.current=l,l},[e?.baseUrl,e?.widgetId]);return(0,D.useEffect)(()=>(t(!0),()=>{r.current?.destroy(),r.current=null}),[i]),(0,D.useEffect)(()=>{r.current&&e&&r.current.updateConfig({agent:e.agent,defaultAgentId:e.defaultAgentId,permission:e.permission,userEmail:e.userEmail,userJwt:e.userJwt,debug:e.debug,warnOnEmptyReply:e.warnOnEmptyReply})},[e?.agent,e?.defaultAgentId,e?.permission,e?.userEmail,e?.userJwt,e?.debug,e?.warnOnEmptyReply]),{client:i,isReady:n}}var _t=(0,D.createContext)(null),ui=({children:e,client:n,tools:t,helpers:r,pageContext:i,...l})=>{const{client:o}=Un(n?null:l),a=n||o;return(0,D.useEffect)(()=>{if(!(!t||t.length===0)){for(const u of t)a.register(u);return()=>{for(const u of t)a.unregisterFunction(u.name)}}},[a,t]),(0,D.useEffect)(()=>{if(!r)return;const u=[];return Promise.resolve().then(()=>require("./functions-DsmzgHjC.cjs")).then(s=>s.functions_exports).then(s=>{for(const[f,c]of Object.entries(r)){const h=s[f];if(!h){console.warn(`[AGO] Unknown helper: "${f}"`);continue}const p=c===!0?h:{...h,handler:c};a.register(p),u.push(p.name)}}),()=>{for(const s of u)a.unregisterFunction(s)}},[a,r]),(0,D.useEffect)(()=>{i==="auto"&&a.enableAutoPageContext()},[a,i]),(0,z.jsx)(_t.Provider,{value:a,children:e})};function Ye(){const e=(0,D.useContext)(_t);if(!e)throw new Error('useAgoClient must be used within an <AgoProvider>. Wrap your component tree with <AgoProvider baseUrl="...">.');return e}function Je(){return(0,D.useContext)(_t)}function Ot({client:e,conversationId:n}={}){const t=Je(),r=e||t;if(!r)throw new Error("useMessages requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.");const[i,l]=(0,D.useState)([]),[o,a]=(0,D.useState)(n),[u,s]=(0,D.useState)(!1),[f,c]=(0,D.useState)(null);(0,D.useEffect)(()=>{n&&n!==o&&(a(n),h(n))},[n]);const h=async p=>{try{l(await r.getMessages(p))}catch(x){c(x instanceof Error?x:new Error("Failed to load messages"))}};return(0,D.useEffect)(()=>{const p=v=>{o||a(v.conversationId)},x=v=>{l(b=>{const A=b[b.length-1];return A&&A.id===v.messageId?[...b.slice(0,-1),{...A,content:A.content+v.content}]:b})},k=v=>{l(b=>{let A=-1;for(let P=b.length-1;P>=0;P--)if(b[P].role==="assistant"&&b[P].status==="IN_PROGRESS"){A=P;break}return A<0?b:[...b.slice(0,A),{...b[A],...v},...b.slice(A+1)]})},C=v=>{l(b=>{const A=b.findIndex(P=>P.id===v.id);return A>=0?[...b.slice(0,A),v,...b.slice(A+1)]:[...b,v]}),s(!1)},d=v=>{c(new Error(v.error)),s(!1)};return r.on("message:start",p),r.on("message:chunk",x),r.on("message:answer-complete",k),r.on("message:complete",C),r.on("message:error",d),()=>{r.off("message:start",p),r.off("message:chunk",x),r.off("message:answer-complete",k),r.off("message:complete",C),r.off("message:error",d)}},[r,o]),{messages:i,isLoading:u,error:f,sendMessage:(0,D.useCallback)(async(p,x)=>{s(!0),c(null);const k={id:`temp-${Date.now()}`,conversationId:o||"",content:p,role:"user",status:"DONE",createdAt:new Date},C={id:`temp-assistant-${Date.now()}`,conversationId:o||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};l(d=>[...d,k,C]);try{const d=await r.sendMessage(p,{conversationId:o,files:x});return d.conversationId&&!o&&a(d.conversationId),l(v=>{const b=v.filter(P=>!P.id.startsWith("temp-")),A={...k,id:k.id.replace("temp-","user-"),conversationId:d.conversationId};return b.some(P=>P.id===d.id)?[...b,A].sort((P,S)=>new Date(P.createdAt).getTime()-new Date(S.createdAt).getTime()):[...b,A,d]}),d}catch(d){return c(d instanceof Error?d:new Error("Failed to send message")),s(!1),l(v=>v.filter(b=>!b.id.startsWith("temp-"))),null}},[r,o]),clearMessages:(0,D.useCallback)(()=>{l([]),a(void 0),c(null)},[]),conversationId:o}}var $n=({onSend:e,disabled:n=!1,placeholder:t="Type a message...",allowFiles:r=!1,className:i=""})=>{const[l,o]=(0,D.useState)(""),[a,u]=(0,D.useState)([]),s=(0,D.useRef)(null),f=(0,D.useCallback)(k=>{k.preventDefault(),(l.trim()||a.length>0)&&(e(l.trim(),a.length>0?a:void 0),o(""),u([]))},[l,a,e]),c=(0,D.useCallback)(k=>{k.key==="Enter"&&!k.shiftKey&&(k.preventDefault(),f(k))},[f]),h=(0,D.useCallback)(k=>{const C=Array.from(k.target.files||[]);u(d=>[...d,...C])},[]),p=(0,D.useCallback)(k=>{u(C=>C.filter((d,v)=>v!==k))},[]),x=l.trim()||a.length>0;return(0,z.jsxs)("form",{onSubmit:f,className:`ago-chat-input ${i}`,style:{display:"flex",flexDirection:"column",gap:"8px",padding:"12px 16px",borderTop:"1px solid #dee3e8",backgroundColor:"#fff"},children:[a.length>0&&(0,z.jsx)("div",{className:"ago-chat-input__files",style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:a.map((k,C)=>(0,z.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"4px 10px",backgroundColor:"#f0f2f5",borderRadius:"6px",fontSize:"12px",color:"#30373e"},children:[(0,z.jsx)("span",{style:{maxWidth:"120px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k.name}),(0,z.jsx)("button",{type:"button",onClick:()=>p(C),style:{border:"none",background:"none",cursor:"pointer",padding:"0",color:"#6b6d6f",fontSize:"14px",lineHeight:1},children:"×"})]},C))}),(0,z.jsxs)("div",{style:{display:"flex",gap:"8px",alignItems:"flex-end"},children:[r&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("button",{type:"button",onClick:()=>s.current?.click(),disabled:n,style:{padding:"8px",border:"1px solid #dee3e8",borderRadius:"8px",backgroundColor:"#fff",cursor:n?"not-allowed":"pointer",color:"#6b6d6f",fontSize:"16px",lineHeight:1},children:"+"}),(0,z.jsx)("input",{ref:s,type:"file",multiple:!0,onChange:h,style:{display:"none"}})]}),(0,z.jsx)("textarea",{value:l,onChange:k=>o(k.target.value),onKeyDown:c,placeholder:t,disabled:n,rows:1,style:{flex:1,padding:"10px 14px",border:"1px solid #dee3e8",borderRadius:"20px",resize:"none",outline:"none",fontFamily:"inherit",fontSize:"14px",color:"#30373e",backgroundColor:"#f8f8f8",transition:"border-color 0.15s"},onFocus:k=>{k.currentTarget.style.borderColor="#1b5fc4"},onBlur:k=>{k.currentTarget.style.borderColor="#dee3e8"}}),(0,z.jsx)("button",{type:"submit",disabled:n||!x,style:{padding:"10px 18px",border:"none",borderRadius:"20px",backgroundColor:n||!x?"#b5bfc8":"#03182f",color:"#fff",cursor:n||!x?"not-allowed":"pointer",fontWeight:500,fontSize:"14px",transition:"background-color 0.15s"},children:"Send"})]})]})};function si(e,n){const t=n||{};return(e[e.length-1]===""?[...e,""]:e).join((t.padRight?" ":"")+","+(t.padLeft===!1?"":" ")).trim()}var ci=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,fi=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,pi={};function rn(e,n){return((n||pi).jsx?fi:ci).test(e)}var hi=/[ \t\n\f\r]/g;function mi(e){return typeof e=="object"?e.type==="text"?ln(e.value):!1:ln(e)}function ln(e){return e.replace(hi,"")===""}var Ke=class{constructor(e,n,t){this.normal=n,this.property=e,t&&(this.space=t)}};Ke.prototype.normal={};Ke.prototype.property={};Ke.prototype.space=void 0;function Vn(e,n){const t={},r={};for(const i of e)Object.assign(t,i.property),Object.assign(r,i.normal);return new Ke(t,r,n)}function It(e){return e.toLowerCase()}var re=class{constructor(e,n){this.attribute=n,this.property=e}};re.prototype.attribute="";re.prototype.booleanish=!1;re.prototype.boolean=!1;re.prototype.commaOrSpaceSeparated=!1;re.prototype.commaSeparated=!1;re.prototype.defined=!1;re.prototype.mustUseProperty=!1;re.prototype.number=!1;re.prototype.overloadedBoolean=!1;re.prototype.property="";re.prototype.spaceSeparated=!1;re.prototype.space=void 0;var At=fe.__exportAll({boolean:()=>N,booleanish:()=>Q,commaOrSpaceSeparated:()=>le,commaSeparated:()=>Re,number:()=>E,overloadedBoolean:()=>Tt,spaceSeparated:()=>W}),gi=0,N=Ae(),Q=Ae(),Tt=Ae(),E=Ae(),W=Ae(),Re=Ae(),le=Ae();function Ae(){return 2**++gi}var ft=Object.keys(At),Nt=class extends re{constructor(e,n,t,r){let i=-1;if(super(e,n),on(this,"space",r),typeof t=="number")for(;++i<ft.length;){const l=ft[i];on(this,ft[i],(t&At[l])===At[l])}}};Nt.prototype.defined=!0;function on(e,n,t){t&&(e[n]=t)}function Oe(e){const n={},t={};for(const[r,i]of Object.entries(e.properties)){const l=new Nt(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(l.mustUseProperty=!0),n[r]=l,t[It(r)]=r,t[It(l.attribute)]=r}return new Ke(n,t,e.space)}var Wn=Oe({properties:{ariaActiveDescendant:null,ariaAtomic:Q,ariaAutoComplete:null,ariaBusy:Q,ariaChecked:Q,ariaColCount:E,ariaColIndex:E,ariaColSpan:E,ariaControls:W,ariaCurrent:null,ariaDescribedBy:W,ariaDetails:null,ariaDisabled:Q,ariaDropEffect:W,ariaErrorMessage:null,ariaExpanded:Q,ariaFlowTo:W,ariaGrabbed:Q,ariaHasPopup:null,ariaHidden:Q,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:W,ariaLevel:E,ariaLive:null,ariaModal:Q,ariaMultiLine:Q,ariaMultiSelectable:Q,ariaOrientation:null,ariaOwns:W,ariaPlaceholder:null,ariaPosInSet:E,ariaPressed:Q,ariaReadOnly:Q,ariaRelevant:null,ariaRequired:Q,ariaRoleDescription:W,ariaRowCount:E,ariaRowIndex:E,ariaRowSpan:E,ariaSelected:Q,ariaSetSize:E,ariaSort:null,ariaValueMax:E,ariaValueMin:E,ariaValueNow:E,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Xn(e,n){return n in e?e[n]:n}function Yn(e,n){return Xn(e,n.toLowerCase())}var di=Oe({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Re,acceptCharset:W,accessKey:W,action:null,allow:null,allowFullScreen:N,allowPaymentRequest:N,allowUserMedia:N,alt:null,as:null,async:N,autoCapitalize:null,autoComplete:W,autoFocus:N,autoPlay:N,blocking:W,capture:null,charSet:null,checked:N,cite:null,className:W,cols:E,colSpan:null,content:null,contentEditable:Q,controls:N,controlsList:W,coords:E|Re,crossOrigin:null,data:null,dateTime:null,decoding:null,default:N,defer:N,dir:null,dirName:null,disabled:N,download:Tt,draggable:Q,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:N,formTarget:null,headers:W,height:E,hidden:Tt,high:E,href:null,hrefLang:null,htmlFor:W,httpEquiv:W,id:null,imageSizes:null,imageSrcSet:null,inert:N,inputMode:null,integrity:null,is:null,isMap:N,itemId:null,itemProp:W,itemRef:W,itemScope:N,itemType:W,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:N,low:E,manifest:null,max:null,maxLength:E,media:null,method:null,min:null,minLength:E,multiple:N,muted:N,name:null,nonce:null,noModule:N,noValidate:N,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:N,optimum:E,pattern:null,ping:W,placeholder:null,playsInline:N,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:N,referrerPolicy:null,rel:W,required:N,reversed:N,rows:E,rowSpan:E,sandbox:W,scope:null,scoped:N,seamless:N,selected:N,shadowRootClonable:N,shadowRootDelegatesFocus:N,shadowRootMode:null,shape:null,size:E,sizes:null,slot:null,span:E,spellCheck:Q,src:null,srcDoc:null,srcLang:null,srcSet:null,start:E,step:null,style:null,tabIndex:E,target:null,title:null,translate:null,type:null,typeMustMatch:N,useMap:null,value:Q,width:E,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:W,axis:null,background:null,bgColor:null,border:E,borderColor:null,bottomMargin:E,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:N,declare:N,event:null,face:null,frame:null,frameBorder:null,hSpace:E,leftMargin:E,link:null,longDesc:null,lowSrc:null,marginHeight:E,marginWidth:E,noResize:N,noHref:N,noShade:N,noWrap:N,object:null,profile:null,prompt:null,rev:null,rightMargin:E,rules:null,scheme:null,scrolling:Q,standby:null,summary:null,text:null,topMargin:E,valueType:null,version:null,vAlign:null,vLink:null,vSpace:E,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:N,disableRemotePlayback:N,prefix:null,property:null,results:E,security:null,unselectable:null},space:"html",transform:Yn}),xi=Oe({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:le,accentHeight:E,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:E,amplitude:E,arabicForm:null,ascent:E,attributeName:null,attributeType:null,azimuth:E,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:E,by:null,calcMode:null,capHeight:E,className:W,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:E,diffuseConstant:E,direction:null,display:null,dur:null,divisor:E,dominantBaseline:null,download:N,dx:null,dy:null,edgeMode:null,editable:null,elevation:E,enableBackground:null,end:null,event:null,exponent:E,externalResourcesRequired:null,fill:null,fillOpacity:E,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:Re,g2:Re,glyphName:Re,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:E,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:E,horizOriginX:E,horizOriginY:E,id:null,ideographic:E,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:E,k:E,k1:E,k2:E,k3:E,k4:E,kernelMatrix:le,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:E,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:E,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:E,overlineThickness:E,paintOrder:null,panose1:null,path:null,pathLength:E,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:W,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:E,pointsAtY:E,pointsAtZ:E,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:le,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:le,rev:le,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:le,requiredFeatures:le,requiredFonts:le,requiredFormats:le,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:E,specularExponent:E,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:E,strikethroughThickness:E,string:null,stroke:null,strokeDashArray:le,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:E,strokeOpacity:E,strokeWidth:null,style:null,surfaceScale:E,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:le,tabIndex:E,tableValues:null,target:null,targetX:E,targetY:E,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:le,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:E,underlineThickness:E,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:E,values:null,vAlphabetic:E,vMathematical:E,vectorEffect:null,vHanging:E,vIdeographic:E,version:null,vertAdvY:E,vertOriginX:E,vertOriginY:E,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:E,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Xn}),Jn=Oe({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,n){return"xlink:"+n.slice(5).toLowerCase()}}),Kn=Oe({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Yn}),Qn=Oe({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),yi={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"},ki=/[A-Z]/g,an=/-[a-z]/g,bi=/^data[-\w.:]+$/i;function wi(e,n){const t=It(n);let r=n,i=re;if(t in e.normal)return e.property[e.normal[t]];if(t.length>4&&t.slice(0,4)==="data"&&bi.test(n)){if(n.charAt(4)==="-"){const l=n.slice(5).replace(an,Si);r="data"+l.charAt(0).toUpperCase()+l.slice(1)}else{const l=n.slice(4);if(!an.test(l)){let o=l.replace(ki,vi);o.charAt(0)!=="-"&&(o="-"+o),n="data"+o}}i=Nt}return new i(r,n)}function vi(e){return"-"+e.toLowerCase()}function Si(e){return e.charAt(1).toUpperCase()}var Ci=Vn([Wn,di,Jn,Kn,Qn],"html"),Bt=Vn([Wn,xi,Jn,Kn,Qn],"svg");function Ei(e){return e.join(" ").trim()}var Ii=fe.__commonJSMin(((e,n)=>{var t=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,r=/\n/g,i=/^\s*/,l=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,a=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,u=/^[;\s]*/,s=/^\s+|\s+$/g,f=`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const fe=require("./rolldown-runtime-CaekUdDJ.cjs"),oi=require("./AgoClient-1jgDndKs.cjs"),ve=require("./createFormCollector-B8V9YSGe.cjs"),ai=require("./createMockClient-zHQ0cjUH.cjs");let D=require("react");D=fe.__toESM(D,1);let z=require("react/jsx-runtime");function Un(e){const[n,t]=(0,D.useState)(!1),r=(0,D.useRef)(null),i=(0,D.useMemo)(()=>{if(r.current&&(r.current.destroy(),r.current=null),!e)return null;const l=new oi.AgoClient(e);return r.current=l,l},[e?.baseUrl,e?.widgetId]);return(0,D.useEffect)(()=>(t(!0),()=>{r.current?.destroy(),r.current=null}),[i]),(0,D.useEffect)(()=>{r.current&&e&&r.current.updateConfig({agent:e.agent,defaultAgentId:e.defaultAgentId,permission:e.permission,userEmail:e.userEmail,userJwt:e.userJwt,debug:e.debug,warnOnEmptyReply:e.warnOnEmptyReply})},[e?.agent,e?.defaultAgentId,e?.permission,e?.userEmail,e?.userJwt,e?.debug,e?.warnOnEmptyReply]),{client:i,isReady:n}}var _t=(0,D.createContext)(null),ui=({children:e,client:n,tools:t,helpers:r,pageContext:i,...l})=>{const{client:o}=Un(n?null:l),a=n||o;return(0,D.useEffect)(()=>{if(!(!t||t.length===0)){for(const u of t)a.register(u);return()=>{for(const u of t)a.unregisterFunction(u.name)}}},[a,t]),(0,D.useEffect)(()=>{if(!r)return;const u=[];return Promise.resolve().then(()=>require("./functions-DsmzgHjC.cjs")).then(s=>s.functions_exports).then(s=>{for(const[f,c]of Object.entries(r)){const h=s[f];if(!h){console.warn(`[AGO] Unknown helper: "${f}"`);continue}const p=c===!0?h:{...h,handler:c};a.register(p),u.push(p.name)}}),()=>{for(const s of u)a.unregisterFunction(s)}},[a,r]),(0,D.useEffect)(()=>{i==="auto"&&a.enableAutoPageContext()},[a,i]),(0,z.jsx)(_t.Provider,{value:a,children:e})};function Ye(){const e=(0,D.useContext)(_t);if(!e)throw new Error('useAgoClient must be used within an <AgoProvider>. Wrap your component tree with <AgoProvider baseUrl="...">.');return e}function Je(){return(0,D.useContext)(_t)}function Ot({client:e,conversationId:n}={}){const t=Je(),r=e||t;if(!r)throw new Error("useMessages requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.");const[i,l]=(0,D.useState)([]),[o,a]=(0,D.useState)(n),[u,s]=(0,D.useState)(!1),[f,c]=(0,D.useState)(null);(0,D.useEffect)(()=>{n&&n!==o&&(a(n),h(n))},[n]);const h=async p=>{try{l(await r.getMessages(p))}catch(x){c(x instanceof Error?x:new Error("Failed to load messages"))}};return(0,D.useEffect)(()=>{const p=v=>{o||a(v.conversationId)},x=v=>{l(b=>{const A=b[b.length-1];return A&&A.id===v.messageId?[...b.slice(0,-1),{...A,content:A.content+v.content}]:b})},k=v=>{l(b=>{let A=-1;for(let P=b.length-1;P>=0;P--)if(b[P].role==="assistant"&&b[P].status==="IN_PROGRESS"){A=P;break}return A<0?b:[...b.slice(0,A),{...b[A],...v},...b.slice(A+1)]})},C=v=>{l(b=>{const A=b.findIndex(P=>P.id===v.id);return A>=0?[...b.slice(0,A),v,...b.slice(A+1)]:[...b,v]}),s(!1)},d=v=>{c(new Error(v.error)),s(!1)};return r.on("message:start",p),r.on("message:chunk",x),r.on("message:answer-complete",k),r.on("message:complete",C),r.on("message:error",d),()=>{r.off("message:start",p),r.off("message:chunk",x),r.off("message:answer-complete",k),r.off("message:complete",C),r.off("message:error",d)}},[r,o]),{messages:i,isLoading:u,error:f,sendMessage:(0,D.useCallback)(async(p,x)=>{s(!0),c(null);const k={id:`temp-${Date.now()}`,conversationId:o||"",content:p,role:"user",status:"DONE",createdAt:new Date},C={id:`temp-assistant-${Date.now()}`,conversationId:o||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};l(d=>[...d,k,C]);try{const d=await r.sendMessage(p,{conversationId:o,files:x});return d.conversationId&&!o&&a(d.conversationId),l(v=>{const b=v.filter(P=>!P.id.startsWith("temp-")),A={...k,id:k.id.replace("temp-","user-"),conversationId:d.conversationId};return b.some(P=>P.id===d.id)?[...b,A].sort((P,S)=>new Date(P.createdAt).getTime()-new Date(S.createdAt).getTime()):[...b,A,d]}),d}catch(d){return c(d instanceof Error?d:new Error("Failed to send message")),s(!1),l(v=>v.filter(b=>!b.id.startsWith("temp-"))),null}},[r,o]),clearMessages:(0,D.useCallback)(()=>{l([]),a(void 0),c(null)},[]),conversationId:o}}var $n=({onSend:e,disabled:n=!1,placeholder:t="Type a message...",allowFiles:r=!1,className:i=""})=>{const[l,o]=(0,D.useState)(""),[a,u]=(0,D.useState)([]),s=(0,D.useRef)(null),f=(0,D.useCallback)(k=>{k.preventDefault(),(l.trim()||a.length>0)&&(e(l.trim(),a.length>0?a:void 0),o(""),u([]))},[l,a,e]),c=(0,D.useCallback)(k=>{k.key==="Enter"&&!k.shiftKey&&(k.preventDefault(),f(k))},[f]),h=(0,D.useCallback)(k=>{const C=Array.from(k.target.files||[]);u(d=>[...d,...C])},[]),p=(0,D.useCallback)(k=>{u(C=>C.filter((d,v)=>v!==k))},[]),x=l.trim()||a.length>0;return(0,z.jsxs)("form",{onSubmit:f,className:`ago-chat-input ${i}`,style:{display:"flex",flexDirection:"column",gap:"8px",padding:"12px 16px",borderTop:"1px solid #dee3e8",backgroundColor:"#fff"},children:[a.length>0&&(0,z.jsx)("div",{className:"ago-chat-input__files",style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:a.map((k,C)=>(0,z.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"4px 10px",backgroundColor:"#f0f2f5",borderRadius:"6px",fontSize:"12px",color:"#30373e"},children:[(0,z.jsx)("span",{style:{maxWidth:"120px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k.name}),(0,z.jsx)("button",{type:"button",onClick:()=>p(C),style:{border:"none",background:"none",cursor:"pointer",padding:"0",color:"#6b6d6f",fontSize:"14px",lineHeight:1},children:"×"})]},C))}),(0,z.jsxs)("div",{style:{display:"flex",gap:"8px",alignItems:"flex-end"},children:[r&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)("button",{type:"button",onClick:()=>s.current?.click(),disabled:n,style:{padding:"8px",border:"1px solid #dee3e8",borderRadius:"8px",backgroundColor:"#fff",cursor:n?"not-allowed":"pointer",color:"#6b6d6f",fontSize:"16px",lineHeight:1},children:"+"}),(0,z.jsx)("input",{ref:s,type:"file",multiple:!0,onChange:h,style:{display:"none"}})]}),(0,z.jsx)("textarea",{value:l,onChange:k=>o(k.target.value),onKeyDown:c,placeholder:t,disabled:n,rows:1,style:{flex:1,padding:"10px 14px",border:"1px solid #dee3e8",borderRadius:"20px",resize:"none",outline:"none",fontFamily:"inherit",fontSize:"14px",color:"#30373e",backgroundColor:"#f8f8f8",transition:"border-color 0.15s"},onFocus:k=>{k.currentTarget.style.borderColor="#1b5fc4"},onBlur:k=>{k.currentTarget.style.borderColor="#dee3e8"}}),(0,z.jsx)("button",{type:"submit",disabled:n||!x,style:{padding:"10px 18px",border:"none",borderRadius:"20px",backgroundColor:n||!x?"#b5bfc8":"#03182f",color:"#fff",cursor:n||!x?"not-allowed":"pointer",fontWeight:500,fontSize:"14px",transition:"background-color 0.15s"},children:"Send"})]})]})};function si(e,n){const t=n||{};return(e[e.length-1]===""?[...e,""]:e).join((t.padRight?" ":"")+","+(t.padLeft===!1?"":" ")).trim()}var ci=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,fi=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,pi={};function rn(e,n){return((n||pi).jsx?fi:ci).test(e)}var hi=/[ \t\n\f\r]/g;function mi(e){return typeof e=="object"?e.type==="text"?ln(e.value):!1:ln(e)}function ln(e){return e.replace(hi,"")===""}var Ke=class{constructor(e,n,t){this.normal=n,this.property=e,t&&(this.space=t)}};Ke.prototype.normal={};Ke.prototype.property={};Ke.prototype.space=void 0;function Vn(e,n){const t={},r={};for(const i of e)Object.assign(t,i.property),Object.assign(r,i.normal);return new Ke(t,r,n)}function It(e){return e.toLowerCase()}var re=class{constructor(e,n){this.attribute=n,this.property=e}};re.prototype.attribute="";re.prototype.booleanish=!1;re.prototype.boolean=!1;re.prototype.commaOrSpaceSeparated=!1;re.prototype.commaSeparated=!1;re.prototype.defined=!1;re.prototype.mustUseProperty=!1;re.prototype.number=!1;re.prototype.overloadedBoolean=!1;re.prototype.property="";re.prototype.spaceSeparated=!1;re.prototype.space=void 0;var At=fe.__exportAll({boolean:()=>N,booleanish:()=>Q,commaOrSpaceSeparated:()=>le,commaSeparated:()=>Re,number:()=>E,overloadedBoolean:()=>Tt,spaceSeparated:()=>W}),gi=0,N=Ae(),Q=Ae(),Tt=Ae(),E=Ae(),W=Ae(),Re=Ae(),le=Ae();function Ae(){return 2**++gi}var ft=Object.keys(At),Nt=class extends re{constructor(e,n,t,r){let i=-1;if(super(e,n),on(this,"space",r),typeof t=="number")for(;++i<ft.length;){const l=ft[i];on(this,ft[i],(t&At[l])===At[l])}}};Nt.prototype.defined=!0;function on(e,n,t){t&&(e[n]=t)}function Oe(e){const n={},t={};for(const[r,i]of Object.entries(e.properties)){const l=new Nt(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(l.mustUseProperty=!0),n[r]=l,t[It(r)]=r,t[It(l.attribute)]=r}return new Ke(n,t,e.space)}var Wn=Oe({properties:{ariaActiveDescendant:null,ariaAtomic:Q,ariaAutoComplete:null,ariaBusy:Q,ariaChecked:Q,ariaColCount:E,ariaColIndex:E,ariaColSpan:E,ariaControls:W,ariaCurrent:null,ariaDescribedBy:W,ariaDetails:null,ariaDisabled:Q,ariaDropEffect:W,ariaErrorMessage:null,ariaExpanded:Q,ariaFlowTo:W,ariaGrabbed:Q,ariaHasPopup:null,ariaHidden:Q,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:W,ariaLevel:E,ariaLive:null,ariaModal:Q,ariaMultiLine:Q,ariaMultiSelectable:Q,ariaOrientation:null,ariaOwns:W,ariaPlaceholder:null,ariaPosInSet:E,ariaPressed:Q,ariaReadOnly:Q,ariaRelevant:null,ariaRequired:Q,ariaRoleDescription:W,ariaRowCount:E,ariaRowIndex:E,ariaRowSpan:E,ariaSelected:Q,ariaSetSize:E,ariaSort:null,ariaValueMax:E,ariaValueMin:E,ariaValueNow:E,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Xn(e,n){return n in e?e[n]:n}function Yn(e,n){return Xn(e,n.toLowerCase())}var di=Oe({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Re,acceptCharset:W,accessKey:W,action:null,allow:null,allowFullScreen:N,allowPaymentRequest:N,allowUserMedia:N,alt:null,as:null,async:N,autoCapitalize:null,autoComplete:W,autoFocus:N,autoPlay:N,blocking:W,capture:null,charSet:null,checked:N,cite:null,className:W,cols:E,colSpan:null,content:null,contentEditable:Q,controls:N,controlsList:W,coords:E|Re,crossOrigin:null,data:null,dateTime:null,decoding:null,default:N,defer:N,dir:null,dirName:null,disabled:N,download:Tt,draggable:Q,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:N,formTarget:null,headers:W,height:E,hidden:Tt,high:E,href:null,hrefLang:null,htmlFor:W,httpEquiv:W,id:null,imageSizes:null,imageSrcSet:null,inert:N,inputMode:null,integrity:null,is:null,isMap:N,itemId:null,itemProp:W,itemRef:W,itemScope:N,itemType:W,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:N,low:E,manifest:null,max:null,maxLength:E,media:null,method:null,min:null,minLength:E,multiple:N,muted:N,name:null,nonce:null,noModule:N,noValidate:N,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:N,optimum:E,pattern:null,ping:W,placeholder:null,playsInline:N,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:N,referrerPolicy:null,rel:W,required:N,reversed:N,rows:E,rowSpan:E,sandbox:W,scope:null,scoped:N,seamless:N,selected:N,shadowRootClonable:N,shadowRootDelegatesFocus:N,shadowRootMode:null,shape:null,size:E,sizes:null,slot:null,span:E,spellCheck:Q,src:null,srcDoc:null,srcLang:null,srcSet:null,start:E,step:null,style:null,tabIndex:E,target:null,title:null,translate:null,type:null,typeMustMatch:N,useMap:null,value:Q,width:E,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:W,axis:null,background:null,bgColor:null,border:E,borderColor:null,bottomMargin:E,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:N,declare:N,event:null,face:null,frame:null,frameBorder:null,hSpace:E,leftMargin:E,link:null,longDesc:null,lowSrc:null,marginHeight:E,marginWidth:E,noResize:N,noHref:N,noShade:N,noWrap:N,object:null,profile:null,prompt:null,rev:null,rightMargin:E,rules:null,scheme:null,scrolling:Q,standby:null,summary:null,text:null,topMargin:E,valueType:null,version:null,vAlign:null,vLink:null,vSpace:E,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:N,disableRemotePlayback:N,prefix:null,property:null,results:E,security:null,unselectable:null},space:"html",transform:Yn}),xi=Oe({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:le,accentHeight:E,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:E,amplitude:E,arabicForm:null,ascent:E,attributeName:null,attributeType:null,azimuth:E,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:E,by:null,calcMode:null,capHeight:E,className:W,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:E,diffuseConstant:E,direction:null,display:null,dur:null,divisor:E,dominantBaseline:null,download:N,dx:null,dy:null,edgeMode:null,editable:null,elevation:E,enableBackground:null,end:null,event:null,exponent:E,externalResourcesRequired:null,fill:null,fillOpacity:E,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:Re,g2:Re,glyphName:Re,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:E,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:E,horizOriginX:E,horizOriginY:E,id:null,ideographic:E,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:E,k:E,k1:E,k2:E,k3:E,k4:E,kernelMatrix:le,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:E,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:E,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:E,overlineThickness:E,paintOrder:null,panose1:null,path:null,pathLength:E,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:W,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:E,pointsAtY:E,pointsAtZ:E,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:le,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:le,rev:le,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:le,requiredFeatures:le,requiredFonts:le,requiredFormats:le,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:E,specularExponent:E,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:E,strikethroughThickness:E,string:null,stroke:null,strokeDashArray:le,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:E,strokeOpacity:E,strokeWidth:null,style:null,surfaceScale:E,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:le,tabIndex:E,tableValues:null,target:null,targetX:E,targetY:E,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:le,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:E,underlineThickness:E,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:E,values:null,vAlphabetic:E,vMathematical:E,vectorEffect:null,vHanging:E,vIdeographic:E,version:null,vertAdvY:E,vertOriginX:E,vertOriginY:E,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:E,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Xn}),Jn=Oe({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,n){return"xlink:"+n.slice(5).toLowerCase()}}),Kn=Oe({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Yn}),Qn=Oe({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),yi={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"},ki=/[A-Z]/g,an=/-[a-z]/g,bi=/^data[-\w.:]+$/i;function wi(e,n){const t=It(n);let r=n,i=re;if(t in e.normal)return e.property[e.normal[t]];if(t.length>4&&t.slice(0,4)==="data"&&bi.test(n)){if(n.charAt(4)==="-"){const l=n.slice(5).replace(an,Si);r="data"+l.charAt(0).toUpperCase()+l.slice(1)}else{const l=n.slice(4);if(!an.test(l)){let o=l.replace(ki,vi);o.charAt(0)!=="-"&&(o="-"+o),n="data"+o}}i=Nt}return new i(r,n)}function vi(e){return"-"+e.toLowerCase()}function Si(e){return e.charAt(1).toUpperCase()}var Ci=Vn([Wn,di,Jn,Kn,Qn],"html"),Bt=Vn([Wn,xi,Jn,Kn,Qn],"svg");function Ei(e){return e.join(" ").trim()}var Ii=fe.__commonJSMin(((e,n)=>{var t=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,r=/\n/g,i=/^\s*/,l=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,a=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,u=/^[;\s]*/,s=/^\s+|\s+$/g,f=`
2
2
  `,c="/",h="*",p="",x="comment",k="declaration";function C(v,b){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];b=b||{};var A=1,P=1;function S(_){var M=_.match(r);M&&(A+=M.length);var K=_.lastIndexOf(f);P=~K?_.length-K:P+_.length}function B(){var _={line:A,column:P};return function(M){return M.position=new U(_),T(),M}}function U(_){this.start=_,this.end={line:A,column:P},this.source=b.source}U.prototype.content=v;function F(_){var M=new Error(b.source+":"+A+":"+P+": "+_);if(M.reason=_,M.filename=b.source,M.line=A,M.column=P,M.source=v,!b.silent)throw M}function y(_){var M=_.exec(v);if(M){var K=M[0];return S(K),v=v.slice(K.length),M}}function T(){y(i)}function L(_){var M;for(_=_||[];M=$();)M!==!1&&_.push(M);return _}function $(){var _=B();if(!(c!=v.charAt(0)||h!=v.charAt(1))){for(var M=2;p!=v.charAt(M)&&(h!=v.charAt(M)||c!=v.charAt(M+1));)++M;if(M+=2,p===v.charAt(M-1))return F("End of comment missing");var K=v.slice(2,M-2);return P+=2,S(K),v=v.slice(M),P+=2,_({type:x,comment:K})}}function X(){var _=B(),M=y(l);if(M){if($(),!y(o))return F("property missing ':'");var K=y(a),ue=_({type:k,property:d(M[0].replace(t,p)),value:K?d(K[0].replace(t,p)):p});return y(u),ue}}function H(){var _=[];L(_);for(var M;M=X();)M!==!1&&(_.push(M),L(_));return _}return T(),H()}function d(v){return v?v.replace(s,p):p}n.exports=C})),Ai=fe.__commonJSMin((e=>{var n=e&&e.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(e,"__esModule",{value:!0}),e.default=r;var t=n(Ii());function r(i,l){let o=null;if(!i||typeof i!="string")return o;const a=(0,t.default)(i),u=typeof l=="function";return a.forEach(s=>{if(s.type!=="declaration")return;const{property:f,value:c}=s;u?l(f,c,s):c&&(o=o||{},o[f]=c)}),o}})),Ti=fe.__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.camelCase=void 0;var n=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,r=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,l=/^-(ms)-/,o=function(f){return!f||r.test(f)||n.test(f)},a=function(f,c){return c.toUpperCase()},u=function(f,c){return"".concat(c,"-")},s=function(f,c){return c===void 0&&(c={}),o(f)?f:(f=f.toLowerCase(),c.reactCompat?f=f.replace(l,u):f=f.replace(i,u),f.replace(t,a))};e.camelCase=s})),Pi=fe.__commonJSMin(((e,n)=>{var t=(e&&e.__importDefault||function(l){return l&&l.__esModule?l:{default:l}})(Ai()),r=Ti();function i(l,o){var a={};return!l||typeof l!="string"||(0,t.default)(l,function(u,s){u&&s&&(a[(0,r.camelCase)(u,o)]=s)}),a}i.default=i,n.exports=i})),Gn=Zn("end"),jt=Zn("start");function Zn(e){return n;function n(t){const r=t&&t.position&&t.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function Li(e){const n=jt(e),t=Gn(e);if(n&&t)return{start:n,end:t}}function $e(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?un(e.position):"start"in e||"end"in e?un(e):"line"in e||"column"in e?Pt(e):""}function Pt(e){return sn(e&&e.line)+":"+sn(e&&e.column)}function un(e){return Pt(e&&e.start)+"-"+Pt(e&&e.end)}function sn(e){return e&&typeof e=="number"?e:1}var ee=class extends Error{constructor(e,n,t){super(),typeof n=="string"&&(t=n,n=void 0);let r="",i={},l=!1;if(n&&("line"in n&&"column"in n?i={place:n}:"start"in n&&"end"in n?i={place:n}:"type"in n?i={ancestors:[n],place:n.position}:i={...n}),typeof e=="string"?r=e:!i.cause&&e&&(l=!0,r=e.message,i.cause=e),!i.ruleId&&!i.source&&typeof t=="string"){const a=t.indexOf(":");a===-1?i.ruleId=t:(i.source=t.slice(0,a),i.ruleId=t.slice(a+1))}if(!i.place&&i.ancestors&&i.ancestors){const a=i.ancestors[i.ancestors.length-1];a&&(i.place=a.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=r,this.line=o?o.line:void 0,this.name=$e(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=l&&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;var zi=fe.__toESM(Pi(),1),Ht={}.hasOwnProperty,Di=new Map,Fi=/[A-Z]/g,Mi=new Set(["table","tbody","thead","tfoot","tr"]),Ri=new Set(["td","th"]),er="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function _i(e,n){if(!n||n.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const t=n.filePath||void 0;let r;if(n.development){if(typeof n.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=$i(t,n.jsxDEV)}else{if(typeof n.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof n.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=Ui(t,n.jsx,n.jsxs)}const i={Fragment:n.Fragment,ancestors:[],components:n.components||{},create:r,elementAttributeNameCase:n.elementAttributeNameCase||"react",evaluater:n.createEvaluater?n.createEvaluater():void 0,filePath:t,ignoreInvalidStyle:n.ignoreInvalidStyle||!1,passKeys:n.passKeys!==!1,passNode:n.passNode||!1,schema:n.space==="svg"?Bt:Ci,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},l=tr(i,e,void 0);return l&&typeof l!="string"?l:i.create(e,i.Fragment,{children:l||void 0},void 0)}function tr(e,n,t){if(n.type==="element")return Oi(e,n,t);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return Ni(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return ji(e,n,t);if(n.type==="mdxjsEsm")return Bi(e,n);if(n.type==="root")return Hi(e,n,t);if(n.type==="text")return qi(e,n)}function Oi(e,n,t){const r=e.schema;let i=r;n.tagName.toLowerCase()==="svg"&&r.space==="html"&&(i=Bt,e.schema=i),e.ancestors.push(n);const l=rr(e,n.tagName,!1),o=Vi(e,n);let a=Ut(e,n);return Mi.has(n.tagName)&&(a=a.filter(function(u){return typeof u=="string"?!mi(u):!0})),nr(e,o,l,n),qt(o,a),e.ancestors.pop(),e.schema=r,e.create(n,l,o,t)}function Ni(e,n){if(n.data&&n.data.estree&&e.evaluater){const t=n.data.estree.body[0];return t.type,e.evaluater.evaluateExpression(t.expression)}We(e,n.position)}function Bi(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);We(e,n.position)}function ji(e,n,t){const r=e.schema;let i=r;n.name==="svg"&&r.space==="html"&&(i=Bt,e.schema=i),e.ancestors.push(n);const l=n.name===null?e.Fragment:rr(e,n.name,!0),o=Wi(e,n),a=Ut(e,n);return nr(e,o,l,n),qt(o,a),e.ancestors.pop(),e.schema=r,e.create(n,l,o,t)}function Hi(e,n,t){const r={};return qt(r,Ut(e,n)),e.create(n,e.Fragment,r,t)}function qi(e,n){return n.value}function nr(e,n,t,r){typeof t!="string"&&t!==e.Fragment&&e.passNode&&(n.node=r)}function qt(e,n){if(n.length>0){const t=n.length>1?n:n[0];t&&(e.children=t)}}function Ui(e,n,t){return r;function r(i,l,o,a){const u=Array.isArray(o.children)?t:n;return a?u(l,o,a):u(l,o)}}function $i(e,n){return t;function t(r,i,l,o){const a=Array.isArray(l.children),u=jt(r);return n(i,l,o,a,{columnNumber:u?u.column-1:void 0,fileName:e,lineNumber:u?u.line:void 0},void 0)}}function Vi(e,n){const t={};let r,i;for(i in n.properties)if(i!=="children"&&Ht.call(n.properties,i)){const l=Xi(e,i,n.properties[i]);if(l){const[o,a]=l;e.tableCellAlignToStyle&&o==="align"&&typeof a=="string"&&Ri.has(n.tagName)?r=a:t[o]=a}}if(r){const l=t.style||(t.style={});l[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return t}function Wi(e,n){const t={};for(const r of n.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const i=r.data.estree.body[0];i.type;const l=i.expression;l.type;const o=l.properties[0];o.type,Object.assign(t,e.evaluater.evaluateExpression(o.argument))}else We(e,n.position);else{const i=r.name;let l;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const o=r.value.data.estree.body[0];o.type,l=e.evaluater.evaluateExpression(o.expression)}else We(e,n.position);else l=r.value===null?!0:r.value;t[i]=l}return t}function Ut(e,n){const t=[];let r=-1;const i=e.passKeys?new Map:Di;for(;++r<n.children.length;){const l=n.children[r];let o;if(e.passKeys){const u=l.type==="element"?l.tagName:l.type==="mdxJsxFlowElement"||l.type==="mdxJsxTextElement"?l.name:void 0;if(u){const s=i.get(u)||0;o=u+"-"+s,i.set(u,s+1)}}const a=tr(e,l,o);a!==void 0&&t.push(a)}return t}function Xi(e,n,t){const r=wi(e.schema,n);if(!(t==null||typeof t=="number"&&Number.isNaN(t))){if(Array.isArray(t)&&(t=r.commaSeparated?si(t):Ei(t)),r.property==="style"){let i=typeof t=="object"?t:Yi(e,String(t));return e.stylePropertyNameCase==="css"&&(i=Ji(i)),["style",i]}return[e.elementAttributeNameCase==="react"&&r.space?yi[r.property]||r.property:r.attribute,t]}}function Yi(e,n){try{return(0,zi.default)(n,{reactCompat:!0})}catch(t){if(e.ignoreInvalidStyle)return{};const r=t,i=new ee("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:r,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw i.file=e.filePath||void 0,i.url=er+"#cannot-parse-style-attribute",i}}function rr(e,n,t){let r;if(!t)r={type:"Literal",value:n};else if(n.includes(".")){const i=n.split(".");let l=-1,o;for(;++l<i.length;){const a=rn(i[l])?{type:"Identifier",name:i[l]}:{type:"Literal",value:i[l]};o=o?{type:"MemberExpression",object:o,property:a,computed:!!(l&&a.type==="Literal"),optional:!1}:a}r=o}else r=rn(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(r.type==="Literal"){const i=r.value;return Ht.call(e.components,i)?e.components[i]:i}if(e.evaluater)return e.evaluater.evaluateExpression(r);We(e)}function We(e,n){const t=new ee("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:n,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw t.file=e.filePath||void 0,t.url=er+"#cannot-handle-mdx-estrees-without-createevaluater",t}function Ji(e){const n={};let t;for(t in e)Ht.call(e,t)&&(n[Ki(t)]=e[t]);return n}function Ki(e){let n=e.replace(Fi,Qi);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function Qi(e){return"-"+e.toLowerCase()}var pt={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"]},Gi={};function $t(e,n){const t=n||Gi;return ir(e,typeof t.includeImageAlt=="boolean"?t.includeImageAlt:!0,typeof t.includeHtml=="boolean"?t.includeHtml:!0)}function ir(e,n,t){if(Zi(e)){if("value"in e)return e.type==="html"&&!t?"":e.value;if(n&&"alt"in e&&e.alt)return e.alt;if("children"in e)return cn(e.children,n,t)}return Array.isArray(e)?cn(e,n,t):""}function cn(e,n,t){const r=[];let i=-1;for(;++i<e.length;)r[i]=ir(e[i],n,t);return r.join("")}function Zi(e){return!!(e&&typeof e=="object")}var fn=document.createElement("i");function Vt(e){const n="&"+e+";";fn.innerHTML=n;const t=fn.textContent;return t.charCodeAt(t.length-1)===59&&e!=="semi"||t===n?!1:t}function oe(e,n,t,r){const i=e.length;let l=0,o;if(n<0?n=-n>i?0:i+n:n=n>i?i:n,t=t>0?t:0,r.length<1e4)o=Array.from(r),o.unshift(n,t),e.splice(...o);else for(t&&e.splice(n,t);l<r.length;)o=r.slice(l,l+1e4),o.unshift(n,0),e.splice(...o),l+=1e4,n+=1e4}function ae(e,n){return e.length>0?(oe(e,e.length,0,n),e):n}var pn={}.hasOwnProperty;function lr(e){const n={};let t=-1;for(;++t<e.length;)el(n,e[t]);return n}function el(e,n){let t;for(t in n){const r=(pn.call(e,t)?e[t]:void 0)||(e[t]={}),i=n[t];let l;if(i)for(l in i){pn.call(r,l)||(r[l]=[]);const o=i[l];tl(r[l],Array.isArray(o)?o:o?[o]:[])}}}function tl(e,n){let t=-1;const r=[];for(;++t<n.length;)(n[t].add==="after"?e:r).push(n[t]);oe(e,0,0,r)}function or(e,n){const t=Number.parseInt(e,n);return t<9||t===11||t>13&&t<32||t>126&&t<160||t>55295&&t<57344||t>64975&&t<65008||(t&65535)===65535||(t&65535)===65534||t>1114111?"�":String.fromCodePoint(t)}function se(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}var te=Se(/[A-Za-z]/),Z=Se(/[\dA-Za-z]/),nl=Se(/[#-'*+\--9=?A-Z^-~]/);function it(e){return e!==null&&(e<32||e===127)}var Lt=Se(/\d/),rl=Se(/[\dA-Fa-f]/),il=Se(/[!-/:-@[-`{-~]/);function R(e){return e!==null&&e<-2}function V(e){return e!==null&&(e<0||e===32)}function j(e){return e===-2||e===-1||e===32}var at=Se(new RegExp("\\p{P}|\\p{S}","u")),Ie=Se(/\s/);function Se(e){return n;function n(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function Ne(e){const n=[];let t=-1,r=0,i=0;for(;++t<e.length;){const l=e.charCodeAt(t);let o="";if(l===37&&Z(e.charCodeAt(t+1))&&Z(e.charCodeAt(t+2)))i=2;else if(l<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(l))||(o=String.fromCharCode(l));else if(l>55295&&l<57344){const a=e.charCodeAt(t+1);l<56320&&a>56319&&a<57344?(o=String.fromCharCode(l,a),i=1):o="�"}else o=String.fromCharCode(l);o&&(n.push(e.slice(r,t),encodeURIComponent(o)),r=t+i+1,o=""),i&&(t+=i,i=0)}return n.join("")+e.slice(r)}function q(e,n,t,r){const i=r?r-1:Number.POSITIVE_INFINITY;let l=0;return o;function o(u){return j(u)?(e.enter(t),a(u)):n(u)}function a(u){return j(u)&&l++<i?(e.consume(u),a):(e.exit(t),n(u))}}var ll={tokenize:ol};function ol(e){const n=e.attempt(this.parser.constructs.contentInitial,r,i);let t;return n;function r(a){if(a===null){e.consume(a);return}return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),q(e,n,"linePrefix")}function i(a){return e.enter("paragraph"),l(a)}function l(a){const u=e.enter("chunkText",{contentType:"text",previous:t});return t&&(t.next=u),t=u,o(a)}function o(a){if(a===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(a);return}return R(a)?(e.consume(a),e.exit("chunkText"),l):(e.consume(a),o)}}var al={tokenize:ul},hn={tokenize:sl};function ul(e){const n=this,t=[];let r=0,i,l,o;return a;function a(b){if(r<t.length){const A=t[r];return n.containerState=A[1],e.attempt(A[0].continuation,u,s)(b)}return s(b)}function u(b){if(r++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,i&&v();const A=n.events.length;let P=A,S;for(;P--;)if(n.events[P][0]==="exit"&&n.events[P][1].type==="chunkFlow"){S=n.events[P][1].end;break}d(r);let B=A;for(;B<n.events.length;)n.events[B][1].end={...S},B++;return oe(n.events,P+1,0,n.events.slice(A)),n.events.length=B,s(b)}return a(b)}function s(b){if(r===t.length){if(!i)return h(b);if(i.currentConstruct&&i.currentConstruct.concrete)return x(b);n.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(hn,f,c)(b)}function f(b){return i&&v(),d(r),h(b)}function c(b){return n.parser.lazy[n.now().line]=r!==t.length,o=n.now().offset,x(b)}function h(b){return n.containerState={},e.attempt(hn,p,x)(b)}function p(b){return r++,t.push([n.currentConstruct,n.containerState]),h(b)}function x(b){if(b===null){i&&v(),d(0),e.consume(b);return}return i=i||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:i,contentType:"flow",previous:l}),k(b)}function k(b){if(b===null){C(e.exit("chunkFlow"),!0),d(0),e.consume(b);return}return R(b)?(e.consume(b),C(e.exit("chunkFlow")),r=0,n.interrupt=void 0,a):(e.consume(b),k)}function C(b,A){const P=n.sliceStream(b);if(A&&P.push(null),b.previous=l,l&&(l.next=b),l=b,i.defineSkip(b.start),i.write(P),n.parser.lazy[b.start.line]){let S=i.events.length;for(;S--;)if(i.events[S][1].start.offset<o&&(!i.events[S][1].end||i.events[S][1].end.offset>o))return;const B=n.events.length;let U=B,F,y;for(;U--;)if(n.events[U][0]==="exit"&&n.events[U][1].type==="chunkFlow"){if(F){y=n.events[U][1].end;break}F=!0}for(d(r),S=B;S<n.events.length;)n.events[S][1].end={...y},S++;oe(n.events,U+1,0,n.events.slice(B)),n.events.length=S}}function d(b){let A=t.length;for(;A-- >b;){const P=t[A];n.containerState=P[1],P[0].exit.call(n,e)}t.length=b}function v(){i.write([null]),l=void 0,i=void 0,n.containerState._closeFlow=void 0}}function sl(e,n,t){return q(e,e.attempt(this.parser.constructs.document,n,t),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function _e(e){if(e===null||V(e)||Ie(e))return 1;if(at(e))return 2}function ut(e,n,t){const r=[];let i=-1;for(;++i<e.length;){const l=e[i].resolveAll;l&&!r.includes(l)&&(n=l(n,t),r.push(l))}return n}var zt={name:"attention",resolveAll:cl,tokenize:fl};function cl(e,n){let t=-1,r,i,l,o,a,u,s,f;for(;++t<e.length;)if(e[t][0]==="enter"&&e[t][1].type==="attentionSequence"&&e[t][1]._close){for(r=t;r--;)if(e[r][0]==="exit"&&e[r][1].type==="attentionSequence"&&e[r][1]._open&&n.sliceSerialize(e[r][1]).charCodeAt(0)===n.sliceSerialize(e[t][1]).charCodeAt(0)){if((e[r][1]._close||e[t][1]._open)&&(e[t][1].end.offset-e[t][1].start.offset)%3&&!((e[r][1].end.offset-e[r][1].start.offset+e[t][1].end.offset-e[t][1].start.offset)%3))continue;u=e[r][1].end.offset-e[r][1].start.offset>1&&e[t][1].end.offset-e[t][1].start.offset>1?2:1;const c={...e[r][1].end},h={...e[t][1].start};mn(c,-u),mn(h,u),o={type:u>1?"strongSequence":"emphasisSequence",start:c,end:{...e[r][1].end}},a={type:u>1?"strongSequence":"emphasisSequence",start:{...e[t][1].start},end:h},l={type:u>1?"strongText":"emphasisText",start:{...e[r][1].end},end:{...e[t][1].start}},i={type:u>1?"strong":"emphasis",start:{...o.start},end:{...a.end}},e[r][1].end={...o.start},e[t][1].start={...a.end},s=[],e[r][1].end.offset-e[r][1].start.offset&&(s=ae(s,[["enter",e[r][1],n],["exit",e[r][1],n]])),s=ae(s,[["enter",i,n],["enter",o,n],["exit",o,n],["enter",l,n]]),s=ae(s,ut(n.parser.constructs.insideSpan.null,e.slice(r+1,t),n)),s=ae(s,[["exit",l,n],["enter",a,n],["exit",a,n],["exit",i,n]]),e[t][1].end.offset-e[t][1].start.offset?(f=2,s=ae(s,[["enter",e[t][1],n],["exit",e[t][1],n]])):f=0,oe(e,r-1,t-r+3,s),t=r+s.length-f-2;break}}for(t=-1;++t<e.length;)e[t][1].type==="attentionSequence"&&(e[t][1].type="data");return e}function fl(e,n){const t=this.parser.constructs.attentionMarkers.null,r=this.previous,i=_e(r);let l;return o;function o(u){return l=u,e.enter("attentionSequence"),a(u)}function a(u){if(u===l)return e.consume(u),a;const s=e.exit("attentionSequence"),f=_e(u),c=!f||f===2&&i||t.includes(u),h=!i||i===2&&f||t.includes(r);return s._open=!!(l===42?c:c&&(i||!h)),s._close=!!(l===42?h:h&&(f||!c)),n(u)}}function mn(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}var pl={name:"autolink",tokenize:hl};function hl(e,n,t){let r=0;return i;function i(p){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),l}function l(p){return te(p)?(e.consume(p),o):p===64?t(p):s(p)}function o(p){return p===43||p===45||p===46||Z(p)?(r=1,a(p)):s(p)}function a(p){return p===58?(e.consume(p),r=0,u):(p===43||p===45||p===46||Z(p))&&r++<32?(e.consume(p),a):(r=0,s(p))}function u(p){return p===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):p===null||p===32||p===60||it(p)?t(p):(e.consume(p),u)}function s(p){return p===64?(e.consume(p),f):nl(p)?(e.consume(p),s):t(p)}function f(p){return Z(p)?c(p):t(p)}function c(p){return p===46?(e.consume(p),r=0,f):p===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):h(p)}function h(p){if((p===45||Z(p))&&r++<63){const x=p===45?h:c;return e.consume(p),x}return t(p)}}var Qe={partial:!0,tokenize:ml};function ml(e,n,t){return r;function r(l){return j(l)?q(e,i,"linePrefix")(l):i(l)}function i(l){return l===null||R(l)?n(l):t(l)}}var ar={continuation:{tokenize:dl},exit:xl,name:"blockQuote",tokenize:gl};function gl(e,n,t){const r=this;return i;function i(o){if(o===62){const a=r.containerState;return a.open||(e.enter("blockQuote",{_container:!0}),a.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(o),e.exit("blockQuoteMarker"),l}return t(o)}function l(o){return j(o)?(e.enter("blockQuotePrefixWhitespace"),e.consume(o),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(o))}}function dl(e,n,t){const r=this;return i;function i(o){return j(o)?q(e,l,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o):l(o)}function l(o){return e.attempt(ar,n,t)(o)}}function xl(e){e.exit("blockQuote")}var ur={name:"characterEscape",tokenize:yl};function yl(e,n,t){return r;function r(l){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(l),e.exit("escapeMarker"),i}function i(l){return il(l)?(e.enter("characterEscapeValue"),e.consume(l),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):t(l)}}var sr={name:"characterReference",tokenize:kl};function kl(e,n,t){const r=this;let i=0,l,o;return a;function a(c){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(c),e.exit("characterReferenceMarker"),u}function u(c){return c===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(c),e.exit("characterReferenceMarkerNumeric"),s):(e.enter("characterReferenceValue"),l=31,o=Z,f(c))}function s(c){return c===88||c===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(c),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),l=6,o=rl,f):(e.enter("characterReferenceValue"),l=7,o=Lt,f(c))}function f(c){if(c===59&&i){const h=e.exit("characterReferenceValue");return o===Z&&!Vt(r.sliceSerialize(h))?t(c):(e.enter("characterReferenceMarker"),e.consume(c),e.exit("characterReferenceMarker"),e.exit("characterReference"),n)}return o(c)&&i++<l?(e.consume(c),f):t(c)}}var gn={partial:!0,tokenize:wl},dn={concrete:!0,name:"codeFenced",tokenize:bl};function bl(e,n,t){const r=this,i={partial:!0,tokenize:P};let l=0,o=0,a;return u;function u(S){return s(S)}function s(S){const B=r.events[r.events.length-1];return l=B&&B[1].type==="linePrefix"?B[2].sliceSerialize(B[1],!0).length:0,a=S,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),f(S)}function f(S){return S===a?(o++,e.consume(S),f):o<3?t(S):(e.exit("codeFencedFenceSequence"),j(S)?q(e,c,"whitespace")(S):c(S))}function c(S){return S===null||R(S)?(e.exit("codeFencedFence"),r.interrupt?n(S):e.check(gn,k,A)(S)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),h(S))}function h(S){return S===null||R(S)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),c(S)):j(S)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),q(e,p,"whitespace")(S)):S===96&&S===a?t(S):(e.consume(S),h)}function p(S){return S===null||R(S)?c(S):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),x(S))}function x(S){return S===null||R(S)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),c(S)):S===96&&S===a?t(S):(e.consume(S),x)}function k(S){return e.attempt(i,A,C)(S)}function C(S){return e.enter("lineEnding"),e.consume(S),e.exit("lineEnding"),d}function d(S){return l>0&&j(S)?q(e,v,"linePrefix",l+1)(S):v(S)}function v(S){return S===null||R(S)?e.check(gn,k,A)(S):(e.enter("codeFlowValue"),b(S))}function b(S){return S===null||R(S)?(e.exit("codeFlowValue"),v(S)):(e.consume(S),b)}function A(S){return e.exit("codeFenced"),n(S)}function P(S,B,U){let F=0;return y;function y(H){return S.enter("lineEnding"),S.consume(H),S.exit("lineEnding"),T}function T(H){return S.enter("codeFencedFence"),j(H)?q(S,L,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(H):L(H)}function L(H){return H===a?(S.enter("codeFencedFenceSequence"),$(H)):U(H)}function $(H){return H===a?(F++,S.consume(H),$):F>=o?(S.exit("codeFencedFenceSequence"),j(H)?q(S,X,"whitespace")(H):X(H)):U(H)}function X(H){return H===null||R(H)?(S.exit("codeFencedFence"),B(H)):U(H)}}}function wl(e,n,t){const r=this;return i;function i(o){return o===null?t(o):(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),l)}function l(o){return r.parser.lazy[r.now().line]?t(o):n(o)}}var ht={name:"codeIndented",tokenize:Sl},vl={partial:!0,tokenize:Cl};function Sl(e,n,t){const r=this;return i;function i(s){return e.enter("codeIndented"),q(e,l,"linePrefix",5)(s)}function l(s){const f=r.events[r.events.length-1];return f&&f[1].type==="linePrefix"&&f[2].sliceSerialize(f[1],!0).length>=4?o(s):t(s)}function o(s){return s===null?u(s):R(s)?e.attempt(vl,o,u)(s):(e.enter("codeFlowValue"),a(s))}function a(s){return s===null||R(s)?(e.exit("codeFlowValue"),o(s)):(e.consume(s),a)}function u(s){return e.exit("codeIndented"),n(s)}}function Cl(e,n,t){const r=this;return i;function i(o){return r.parser.lazy[r.now().line]?t(o):R(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i):q(e,l,"linePrefix",5)(o)}function l(o){const a=r.events[r.events.length-1];return a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?n(o):R(o)?i(o):t(o)}}var El={name:"codeText",previous:Al,resolve:Il,tokenize:Tl};function Il(e){let n=e.length-4,t=3,r,i;if((e[t][1].type==="lineEnding"||e[t][1].type==="space")&&(e[n][1].type==="lineEnding"||e[n][1].type==="space")){for(r=t;++r<n;)if(e[r][1].type==="codeTextData"){e[t][1].type="codeTextPadding",e[n][1].type="codeTextPadding",t+=2,n-=2;break}}for(r=t-1,n++;++r<=n;)i===void 0?r!==n&&e[r][1].type!=="lineEnding"&&(i=r):(r===n||e[r][1].type==="lineEnding")&&(e[i][1].type="codeTextData",r!==i+2&&(e[i][1].end=e[r-1][1].end,e.splice(i+2,r-i-2),n-=r-i-2,r=i+2),i=void 0);return e}function Al(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Tl(e,n,t){let r=0,i,l;return o;function o(c){return e.enter("codeText"),e.enter("codeTextSequence"),a(c)}function a(c){return c===96?(e.consume(c),r++,a):(e.exit("codeTextSequence"),u(c))}function u(c){return c===null?t(c):c===32?(e.enter("space"),e.consume(c),e.exit("space"),u):c===96?(l=e.enter("codeTextSequence"),i=0,f(c)):R(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),u):(e.enter("codeTextData"),s(c))}function s(c){return c===null||c===32||c===96||R(c)?(e.exit("codeTextData"),u(c)):(e.consume(c),s)}function f(c){return c===96?(e.consume(c),i++,f):i===r?(e.exit("codeTextSequence"),e.exit("codeText"),n(c)):(l.type="codeTextData",s(c))}}var Pl=class{constructor(e){this.left=e?[...e]:[],this.right=[]}get(e){if(e<0||e>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return e<this.left.length?this.left[e]:this.right[this.right.length-e+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(e,n){const t=n??Number.POSITIVE_INFINITY;return t<this.left.length?this.left.slice(e,t):e>this.left.length?this.right.slice(this.right.length-t+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-t+this.left.length).reverse())}splice(e,n,t){const r=n||0;this.setCursor(Math.trunc(e));const i=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return t&&qe(this.left,t),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(e){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(e)}pushMany(e){this.setCursor(Number.POSITIVE_INFINITY),qe(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),qe(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0))if(e<this.left.length){const n=this.left.splice(e,Number.POSITIVE_INFINITY);qe(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-e,Number.POSITIVE_INFINITY);qe(this.left,n.reverse())}}};function qe(e,n){let t=0;if(n.length<1e4)e.push(...n);else for(;t<n.length;)e.push(...n.slice(t,t+1e4)),t+=1e4}function cr(e){const n={};let t=-1,r,i,l,o,a,u,s;const f=new Pl(e);for(;++t<f.length;){for(;t in n;)t=n[t];if(r=f.get(t),t&&r[1].type==="chunkFlow"&&f.get(t-1)[1].type==="listItemPrefix"&&(u=r[1]._tokenizer.events,l=0,l<u.length&&u[l][1].type==="lineEndingBlank"&&(l+=2),l<u.length&&u[l][1].type==="content"))for(;++l<u.length&&u[l][1].type!=="content";)u[l][1].type==="chunkText"&&(u[l][1]._isInFirstContentOfListItem=!0,l++);if(r[0]==="enter")r[1].contentType&&(Object.assign(n,Ll(f,t)),t=n[t],s=!0);else if(r[1]._container){for(l=t,i=void 0;l--;)if(o=f.get(l),o[1].type==="lineEnding"||o[1].type==="lineEndingBlank")o[0]==="enter"&&(i&&(f.get(i)[1].type="lineEndingBlank"),o[1].type="lineEnding",i=l);else if(!(o[1].type==="linePrefix"||o[1].type==="listItemIndent"))break;i&&(r[1].end={...f.get(i)[1].start},a=f.slice(i,t),a.unshift(r),f.splice(i,t-i+1,a))}}return oe(e,0,Number.POSITIVE_INFINITY,f.slice(0)),!s}function Ll(e,n){const t=e.get(n)[1],r=e.get(n)[2];let i=n-1;const l=[];let o=t._tokenizer;o||(o=r.parser[t.contentType](t.start),t._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));const a=o.events,u=[],s={};let f,c,h=-1,p=t,x=0,k=0;const C=[k];for(;p;){for(;e.get(++i)[1]!==p;);l.push(i),p._tokenizer||(f=r.sliceStream(p),p.next||f.push(null),c&&o.defineSkip(p.start),p._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(f),p._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),c=p,p=p.next}for(p=t;++h<a.length;)a[h][0]==="exit"&&a[h-1][0]==="enter"&&a[h][1].type===a[h-1][1].type&&a[h][1].start.line!==a[h][1].end.line&&(k=h+1,C.push(k),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(o.events=[],p?(p._tokenizer=void 0,p.previous=void 0):C.pop(),h=C.length;h--;){const d=a.slice(C[h],C[h+1]),v=l.pop();u.push([v,v+d.length-1]),e.splice(v,2,d)}for(u.reverse(),h=-1;++h<u.length;)s[x+u[h][0]]=x+u[h][1],x+=u[h][1]-u[h][0]-1;return s}var zl={resolve:Fl,tokenize:Ml},Dl={partial:!0,tokenize:Rl};function Fl(e){return cr(e),e}function Ml(e,n){let t;return r;function r(a){return e.enter("content"),t=e.enter("chunkContent",{contentType:"content"}),i(a)}function i(a){return a===null?l(a):R(a)?e.check(Dl,o,l)(a):(e.consume(a),i)}function l(a){return e.exit("chunkContent"),e.exit("content"),n(a)}function o(a){return e.consume(a),e.exit("chunkContent"),t.next=e.enter("chunkContent",{contentType:"content",previous:t}),t=t.next,i}}function Rl(e,n,t){const r=this;return i;function i(o){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),q(e,l,"linePrefix")}function l(o){if(o===null||R(o))return t(o);const a=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?n(o):e.interrupt(r.parser.constructs.flow,t,n)(o)}}function fr(e,n,t,r,i,l,o,a,u){const s=u||Number.POSITIVE_INFINITY;let f=0;return c;function c(d){return d===60?(e.enter(r),e.enter(i),e.enter(l),e.consume(d),e.exit(l),h):d===null||d===32||d===41||it(d)?t(d):(e.enter(r),e.enter(o),e.enter(a),e.enter("chunkString",{contentType:"string"}),k(d))}function h(d){return d===62?(e.enter(l),e.consume(d),e.exit(l),e.exit(i),e.exit(r),n):(e.enter(a),e.enter("chunkString",{contentType:"string"}),p(d))}function p(d){return d===62?(e.exit("chunkString"),e.exit(a),h(d)):d===null||d===60||R(d)?t(d):(e.consume(d),d===92?x:p)}function x(d){return d===60||d===62||d===92?(e.consume(d),p):p(d)}function k(d){return!f&&(d===null||d===41||V(d))?(e.exit("chunkString"),e.exit(a),e.exit(o),e.exit(r),n(d)):f<s&&d===40?(e.consume(d),f++,k):d===41?(e.consume(d),f--,k):d===null||d===32||d===40||it(d)?t(d):(e.consume(d),d===92?C:k)}function C(d){return d===40||d===41||d===92?(e.consume(d),k):k(d)}}function pr(e,n,t,r,i,l){const o=this;let a=0,u;return s;function s(p){return e.enter(r),e.enter(i),e.consume(p),e.exit(i),e.enter(l),f}function f(p){return a>999||p===null||p===91||p===93&&!u||p===94&&!a&&"_hiddenFootnoteSupport"in o.parser.constructs?t(p):p===93?(e.exit(l),e.enter(i),e.consume(p),e.exit(i),e.exit(r),n):R(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),f):(e.enter("chunkString",{contentType:"string"}),c(p))}function c(p){return p===null||p===91||p===93||R(p)||a++>999?(e.exit("chunkString"),f(p)):(e.consume(p),u||(u=!j(p)),p===92?h:c)}function h(p){return p===91||p===92||p===93?(e.consume(p),a++,c):c(p)}}function hr(e,n,t,r,i,l){let o;return a;function a(h){return h===34||h===39||h===40?(e.enter(r),e.enter(i),e.consume(h),e.exit(i),o=h===40?41:h,u):t(h)}function u(h){return h===o?(e.enter(i),e.consume(h),e.exit(i),e.exit(r),n):(e.enter(l),s(h))}function s(h){return h===o?(e.exit(l),u(o)):h===null?t(h):R(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),q(e,s,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),f(h))}function f(h){return h===o||h===null||R(h)?(e.exit("chunkString"),s(h)):(e.consume(h),h===92?c:f)}function c(h){return h===o||h===92?(e.consume(h),f):f(h)}}function Ve(e,n){let t;return r;function r(i){return R(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t=!0,r):j(i)?q(e,r,t?"linePrefix":"lineSuffix")(i):n(i)}}var _l={name:"definition",tokenize:Nl},Ol={partial:!0,tokenize:Bl};function Nl(e,n,t){const r=this;let i;return l;function l(p){return e.enter("definition"),o(p)}function o(p){return pr.call(r,e,a,t,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function a(p){return i=se(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),u):t(p)}function u(p){return V(p)?Ve(e,s)(p):s(p)}function s(p){return fr(e,f,t,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function f(p){return e.attempt(Ol,c,c)(p)}function c(p){return j(p)?q(e,h,"whitespace")(p):h(p)}function h(p){return p===null||R(p)?(e.exit("definition"),r.parser.defined.push(i),n(p)):t(p)}}function Bl(e,n,t){return r;function r(a){return V(a)?Ve(e,i)(a):t(a)}function i(a){return hr(e,l,t,"definitionTitle","definitionTitleMarker","definitionTitleString")(a)}function l(a){return j(a)?q(e,o,"whitespace")(a):o(a)}function o(a){return a===null||R(a)?n(a):t(a)}}var jl={name:"hardBreakEscape",tokenize:Hl};function Hl(e,n,t){return r;function r(l){return e.enter("hardBreakEscape"),e.consume(l),i}function i(l){return R(l)?(e.exit("hardBreakEscape"),n(l)):t(l)}}var ql={name:"headingAtx",resolve:Ul,tokenize:$l};function Ul(e,n){let t=e.length-2,r=3,i,l;return e[r][1].type==="whitespace"&&(r+=2),t-2>r&&e[t][1].type==="whitespace"&&(t-=2),e[t][1].type==="atxHeadingSequence"&&(r===t-1||t-4>r&&e[t-2][1].type==="whitespace")&&(t-=r+1===t?2:4),t>r&&(i={type:"atxHeadingText",start:e[r][1].start,end:e[t][1].end},l={type:"chunkText",start:e[r][1].start,end:e[t][1].end,contentType:"text"},oe(e,r,t-r+1,[["enter",i,n],["enter",l,n],["exit",l,n],["exit",i,n]])),e}function $l(e,n,t){let r=0;return i;function i(f){return e.enter("atxHeading"),l(f)}function l(f){return e.enter("atxHeadingSequence"),o(f)}function o(f){return f===35&&r++<6?(e.consume(f),o):f===null||V(f)?(e.exit("atxHeadingSequence"),a(f)):t(f)}function a(f){return f===35?(e.enter("atxHeadingSequence"),u(f)):f===null||R(f)?(e.exit("atxHeading"),n(f)):j(f)?q(e,a,"whitespace")(f):(e.enter("atxHeadingText"),s(f))}function u(f){return f===35?(e.consume(f),u):(e.exit("atxHeadingSequence"),a(f))}function s(f){return f===null||f===35||V(f)?(e.exit("atxHeadingText"),a(f)):(e.consume(f),s)}}var Vl=["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"],xn=["pre","script","style","textarea"],Wl={concrete:!0,name:"htmlFlow",resolveTo:Jl,tokenize:Kl},Xl={partial:!0,tokenize:Gl},Yl={partial:!0,tokenize:Ql};function Jl(e){let n=e.length;for(;n--&&!(e[n][0]==="enter"&&e[n][1].type==="htmlFlow"););return n>1&&e[n-2][1].type==="linePrefix"&&(e[n][1].start=e[n-2][1].start,e[n+1][1].start=e[n-2][1].start,e.splice(n-2,2)),e}function Kl(e,n,t){const r=this;let i,l,o,a,u;return s;function s(g){return f(g)}function f(g){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(g),c}function c(g){return g===33?(e.consume(g),h):g===47?(e.consume(g),l=!0,k):g===63?(e.consume(g),i=3,r.interrupt?n:m):te(g)?(e.consume(g),o=String.fromCharCode(g),C):t(g)}function h(g){return g===45?(e.consume(g),i=2,p):g===91?(e.consume(g),i=5,a=0,x):te(g)?(e.consume(g),i=4,r.interrupt?n:m):t(g)}function p(g){return g===45?(e.consume(g),r.interrupt?n:m):t(g)}function x(g){return g==="CDATA[".charCodeAt(a++)?(e.consume(g),a===6?r.interrupt?n:L:x):t(g)}function k(g){return te(g)?(e.consume(g),o=String.fromCharCode(g),C):t(g)}function C(g){if(g===null||g===47||g===62||V(g)){const ke=g===47,Ce=o.toLowerCase();return!ke&&!l&&xn.includes(Ce)?(i=1,r.interrupt?n(g):L(g)):Vl.includes(o.toLowerCase())?(i=6,ke?(e.consume(g),d):r.interrupt?n(g):L(g)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?t(g):l?v(g):b(g))}return g===45||Z(g)?(e.consume(g),o+=String.fromCharCode(g),C):t(g)}function d(g){return g===62?(e.consume(g),r.interrupt?n:L):t(g)}function v(g){return j(g)?(e.consume(g),v):y(g)}function b(g){return g===47?(e.consume(g),y):g===58||g===95||te(g)?(e.consume(g),A):j(g)?(e.consume(g),b):y(g)}function A(g){return g===45||g===46||g===58||g===95||Z(g)?(e.consume(g),A):P(g)}function P(g){return g===61?(e.consume(g),S):j(g)?(e.consume(g),P):b(g)}function S(g){return g===null||g===60||g===61||g===62||g===96?t(g):g===34||g===39?(e.consume(g),u=g,B):j(g)?(e.consume(g),S):U(g)}function B(g){return g===u?(e.consume(g),u=null,F):g===null||R(g)?t(g):(e.consume(g),B)}function U(g){return g===null||g===34||g===39||g===47||g===60||g===61||g===62||g===96||V(g)?P(g):(e.consume(g),U)}function F(g){return g===47||g===62||j(g)?b(g):t(g)}function y(g){return g===62?(e.consume(g),T):t(g)}function T(g){return g===null||R(g)?L(g):j(g)?(e.consume(g),T):t(g)}function L(g){return g===45&&i===2?(e.consume(g),_):g===60&&i===1?(e.consume(g),M):g===62&&i===4?(e.consume(g),ye):g===63&&i===3?(e.consume(g),m):g===93&&i===5?(e.consume(g),ue):R(g)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(Xl,he,$)(g)):g===null||R(g)?(e.exit("htmlFlowData"),$(g)):(e.consume(g),L)}function $(g){return e.check(Yl,X,he)(g)}function X(g){return e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),H}function H(g){return g===null||R(g)?$(g):(e.enter("htmlFlowData"),L(g))}function _(g){return g===45?(e.consume(g),m):L(g)}function M(g){return g===47?(e.consume(g),o="",K):L(g)}function K(g){if(g===62){const ke=o.toLowerCase();return xn.includes(ke)?(e.consume(g),ye):L(g)}return te(g)&&o.length<8?(e.consume(g),o+=String.fromCharCode(g),K):L(g)}function ue(g){return g===93?(e.consume(g),m):L(g)}function m(g){return g===62?(e.consume(g),ye):g===45&&i===2?(e.consume(g),m):L(g)}function ye(g){return g===null||R(g)?(e.exit("htmlFlowData"),he(g)):(e.consume(g),ye)}function he(g){return e.exit("htmlFlow"),n(g)}}function Ql(e,n,t){const r=this;return i;function i(o){return R(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),l):t(o)}function l(o){return r.parser.lazy[r.now().line]?t(o):n(o)}}function Gl(e,n,t){return r;function r(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(Qe,n,t)}}var Zl={name:"htmlText",tokenize:eo};function eo(e,n,t){const r=this;let i,l,o;return a;function a(m){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(m),u}function u(m){return m===33?(e.consume(m),s):m===47?(e.consume(m),P):m===63?(e.consume(m),b):te(m)?(e.consume(m),U):t(m)}function s(m){return m===45?(e.consume(m),f):m===91?(e.consume(m),l=0,x):te(m)?(e.consume(m),v):t(m)}function f(m){return m===45?(e.consume(m),p):t(m)}function c(m){return m===null?t(m):m===45?(e.consume(m),h):R(m)?(o=c,M(m)):(e.consume(m),c)}function h(m){return m===45?(e.consume(m),p):c(m)}function p(m){return m===62?_(m):m===45?h(m):c(m)}function x(m){return m==="CDATA[".charCodeAt(l++)?(e.consume(m),l===6?k:x):t(m)}function k(m){return m===null?t(m):m===93?(e.consume(m),C):R(m)?(o=k,M(m)):(e.consume(m),k)}function C(m){return m===93?(e.consume(m),d):k(m)}function d(m){return m===62?_(m):m===93?(e.consume(m),d):k(m)}function v(m){return m===null||m===62?_(m):R(m)?(o=v,M(m)):(e.consume(m),v)}function b(m){return m===null?t(m):m===63?(e.consume(m),A):R(m)?(o=b,M(m)):(e.consume(m),b)}function A(m){return m===62?_(m):b(m)}function P(m){return te(m)?(e.consume(m),S):t(m)}function S(m){return m===45||Z(m)?(e.consume(m),S):B(m)}function B(m){return R(m)?(o=B,M(m)):j(m)?(e.consume(m),B):_(m)}function U(m){return m===45||Z(m)?(e.consume(m),U):m===47||m===62||V(m)?F(m):t(m)}function F(m){return m===47?(e.consume(m),_):m===58||m===95||te(m)?(e.consume(m),y):R(m)?(o=F,M(m)):j(m)?(e.consume(m),F):_(m)}function y(m){return m===45||m===46||m===58||m===95||Z(m)?(e.consume(m),y):T(m)}function T(m){return m===61?(e.consume(m),L):R(m)?(o=T,M(m)):j(m)?(e.consume(m),T):F(m)}function L(m){return m===null||m===60||m===61||m===62||m===96?t(m):m===34||m===39?(e.consume(m),i=m,$):R(m)?(o=L,M(m)):j(m)?(e.consume(m),L):(e.consume(m),X)}function $(m){return m===i?(e.consume(m),i=void 0,H):m===null?t(m):R(m)?(o=$,M(m)):(e.consume(m),$)}function X(m){return m===null||m===34||m===39||m===60||m===61||m===96?t(m):m===47||m===62||V(m)?F(m):(e.consume(m),X)}function H(m){return m===47||m===62||V(m)?F(m):t(m)}function _(m){return m===62?(e.consume(m),e.exit("htmlTextData"),e.exit("htmlText"),n):t(m)}function M(m){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),K}function K(m){return j(m)?q(e,ue,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(m):ue(m)}function ue(m){return e.enter("htmlTextData"),o(m)}}var Wt={name:"labelEnd",resolveAll:io,resolveTo:lo,tokenize:oo},to={tokenize:ao},no={tokenize:uo},ro={tokenize:so};function io(e){let n=-1;const t=[];for(;++n<e.length;){const r=e[n][1];if(t.push(e[n]),r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd"){const i=r.type==="labelImage"?4:2;r.type="data",n+=i}}return e.length!==t.length&&oe(e,0,e.length,t),e}function lo(e,n){let t=e.length,r=0,i,l,o,a;for(;t--;)if(i=e[t][1],l){if(i.type==="link"||i.type==="labelLink"&&i._inactive)break;e[t][0]==="enter"&&i.type==="labelLink"&&(i._inactive=!0)}else if(o){if(e[t][0]==="enter"&&(i.type==="labelImage"||i.type==="labelLink")&&!i._balanced&&(l=t,i.type!=="labelLink")){r=2;break}}else i.type==="labelEnd"&&(o=t);const u={type:e[l][1].type==="labelLink"?"link":"image",start:{...e[l][1].start},end:{...e[e.length-1][1].end}},s={type:"label",start:{...e[l][1].start},end:{...e[o][1].end}},f={type:"labelText",start:{...e[l+r+2][1].end},end:{...e[o-2][1].start}};return a=[["enter",u,n],["enter",s,n]],a=ae(a,e.slice(l+1,l+r+3)),a=ae(a,[["enter",f,n]]),a=ae(a,ut(n.parser.constructs.insideSpan.null,e.slice(l+r+4,o-3),n)),a=ae(a,[["exit",f,n],e[o-2],e[o-1],["exit",s,n]]),a=ae(a,e.slice(o+1)),a=ae(a,[["exit",u,n]]),oe(e,l,e.length,a),e}function oo(e,n,t){const r=this;let i=r.events.length,l,o;for(;i--;)if((r.events[i][1].type==="labelImage"||r.events[i][1].type==="labelLink")&&!r.events[i][1]._balanced){l=r.events[i][1];break}return a;function a(h){return l?l._inactive?c(h):(o=r.parser.defined.includes(se(r.sliceSerialize({start:l.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(h),e.exit("labelMarker"),e.exit("labelEnd"),u):t(h)}function u(h){return h===40?e.attempt(to,f,o?f:c)(h):h===91?e.attempt(no,f,o?s:c)(h):o?f(h):c(h)}function s(h){return e.attempt(ro,f,c)(h)}function f(h){return n(h)}function c(h){return l._balanced=!0,t(h)}}function ao(e,n,t){return r;function r(c){return e.enter("resource"),e.enter("resourceMarker"),e.consume(c),e.exit("resourceMarker"),i}function i(c){return V(c)?Ve(e,l)(c):l(c)}function l(c){return c===41?f(c):fr(e,o,a,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(c)}function o(c){return V(c)?Ve(e,u)(c):f(c)}function a(c){return t(c)}function u(c){return c===34||c===39||c===40?hr(e,s,t,"resourceTitle","resourceTitleMarker","resourceTitleString")(c):f(c)}function s(c){return V(c)?Ve(e,f)(c):f(c)}function f(c){return c===41?(e.enter("resourceMarker"),e.consume(c),e.exit("resourceMarker"),e.exit("resource"),n):t(c)}}function uo(e,n,t){const r=this;return i;function i(a){return pr.call(r,e,l,o,"reference","referenceMarker","referenceString")(a)}function l(a){return r.parser.defined.includes(se(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?n(a):t(a)}function o(a){return t(a)}}function so(e,n,t){return r;function r(l){return e.enter("reference"),e.enter("referenceMarker"),e.consume(l),e.exit("referenceMarker"),i}function i(l){return l===93?(e.enter("referenceMarker"),e.consume(l),e.exit("referenceMarker"),e.exit("reference"),n):t(l)}}var co={name:"labelStartImage",resolveAll:Wt.resolveAll,tokenize:fo};function fo(e,n,t){const r=this;return i;function i(a){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(a),e.exit("labelImageMarker"),l}function l(a){return a===91?(e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelImage"),o):t(a)}function o(a){return a===94&&"_hiddenFootnoteSupport"in r.parser.constructs?t(a):n(a)}}var po={name:"labelStartLink",resolveAll:Wt.resolveAll,tokenize:ho};function ho(e,n,t){const r=this;return i;function i(o){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelLink"),l}function l(o){return o===94&&"_hiddenFootnoteSupport"in r.parser.constructs?t(o):n(o)}}var mt={name:"lineEnding",tokenize:mo};function mo(e,n){return t;function t(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),q(e,n,"linePrefix")}}var rt={name:"thematicBreak",tokenize:go};function go(e,n,t){let r=0,i;return l;function l(s){return e.enter("thematicBreak"),o(s)}function o(s){return i=s,a(s)}function a(s){return s===i?(e.enter("thematicBreakSequence"),u(s)):r>=3&&(s===null||R(s))?(e.exit("thematicBreak"),n(s)):t(s)}function u(s){return s===i?(e.consume(s),r++,u):(e.exit("thematicBreakSequence"),j(s)?q(e,a,"whitespace")(s):a(s))}}var ne={continuation:{tokenize:bo},exit:vo,name:"list",tokenize:ko},xo={partial:!0,tokenize:So},yo={partial:!0,tokenize:wo};function ko(e,n,t){const r=this,i=r.events[r.events.length-1];let l=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,o=0;return a;function a(p){const x=r.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(x==="listUnordered"?!r.containerState.marker||p===r.containerState.marker:Lt(p)){if(r.containerState.type||(r.containerState.type=x,e.enter(x,{_container:!0})),x==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(rt,t,s)(p):s(p);if(!r.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),u(p)}return t(p)}function u(p){return Lt(p)&&++o<10?(e.consume(p),u):(!r.interrupt||o<2)&&(r.containerState.marker?p===r.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),s(p)):t(p)}function s(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||p,e.check(Qe,r.interrupt?t:f,e.attempt(xo,h,c))}function f(p){return r.containerState.initialBlankLine=!0,l++,h(p)}function c(p){return j(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),h):t(p)}function h(p){return r.containerState.size=l+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(p)}}function bo(e,n,t){const r=this;return r.containerState._closeFlow=void 0,e.check(Qe,i,l);function i(a){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,q(e,n,"listItemIndent",r.containerState.size+1)(a)}function l(a){return r.containerState.furtherBlankLines||!j(a)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(a)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(yo,n,o)(a))}function o(a){return r.containerState._closeFlow=!0,r.interrupt=void 0,q(e,e.attempt(ne,n,t),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}function wo(e,n,t){const r=this;return q(e,i,"listItemIndent",r.containerState.size+1);function i(l){const o=r.events[r.events.length-1];return o&&o[1].type==="listItemIndent"&&o[2].sliceSerialize(o[1],!0).length===r.containerState.size?n(l):t(l)}}function vo(e){e.exit(this.containerState.type)}function So(e,n,t){const r=this;return q(e,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(l){const o=r.events[r.events.length-1];return!j(l)&&o&&o[1].type==="listItemPrefixWhitespace"?n(l):t(l)}}var yn={name:"setextUnderline",resolveTo:Co,tokenize:Eo};function Co(e,n){let t=e.length,r,i,l;for(;t--;)if(e[t][0]==="enter"){if(e[t][1].type==="content"){r=t;break}e[t][1].type==="paragraph"&&(i=t)}else e[t][1].type==="content"&&e.splice(t,1),!l&&e[t][1].type==="definition"&&(l=t);const o={type:"setextHeading",start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[i][1].type="setextHeadingText",l?(e.splice(i,0,["enter",o,n]),e.splice(l+1,0,["exit",e[r][1],n]),e[r][1].end={...e[l][1].end}):e[r][1]=o,e.push(["exit",o,n]),e}function Eo(e,n,t){const r=this;let i;return l;function l(s){let f=r.events.length,c;for(;f--;)if(r.events[f][1].type!=="lineEnding"&&r.events[f][1].type!=="linePrefix"&&r.events[f][1].type!=="content"){c=r.events[f][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||c)?(e.enter("setextHeadingLine"),i=s,o(s)):t(s)}function o(s){return e.enter("setextHeadingLineSequence"),a(s)}function a(s){return s===i?(e.consume(s),a):(e.exit("setextHeadingLineSequence"),j(s)?q(e,u,"lineSuffix")(s):u(s))}function u(s){return s===null||R(s)?(e.exit("setextHeadingLine"),n(s)):t(s)}}var Io={tokenize:Ao};function Ao(e){const n=this,t=e.attempt(Qe,r,e.attempt(this.parser.constructs.flowInitial,i,q(e,e.attempt(this.parser.constructs.flow,i,e.attempt(zl,i)),"linePrefix")));return t;function r(l){if(l===null){e.consume(l);return}return e.enter("lineEndingBlank"),e.consume(l),e.exit("lineEndingBlank"),n.currentConstruct=void 0,t}function i(l){if(l===null){e.consume(l);return}return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),n.currentConstruct=void 0,t}}var To={resolveAll:gr()},Po=mr("string"),Lo=mr("text");function mr(e){return{resolveAll:gr(e==="text"?zo:void 0),tokenize:n};function n(t){const r=this,i=this.parser.constructs[e],l=t.attempt(i,o,a);return o;function o(f){return s(f)?l(f):a(f)}function a(f){if(f===null){t.consume(f);return}return t.enter("data"),t.consume(f),u}function u(f){return s(f)?(t.exit("data"),l(f)):(t.consume(f),u)}function s(f){if(f===null)return!0;const c=i[f];let h=-1;if(c)for(;++h<c.length;){const p=c[h];if(!p.previous||p.previous.call(r,r.previous))return!0}return!1}}}function gr(e){return n;function n(t,r){let i=-1,l;for(;++i<=t.length;)l===void 0?t[i]&&t[i][1].type==="data"&&(l=i,i++):(!t[i]||t[i][1].type!=="data")&&(i!==l+2&&(t[l][1].end=t[i-1][1].end,t.splice(l+2,i-l-2),i=l+2),l=void 0);return e?e(t,r):t}}function zo(e,n){let t=0;for(;++t<=e.length;)if((t===e.length||e[t][1].type==="lineEnding")&&e[t-1][1].type==="data"){const r=e[t-1][1],i=n.sliceStream(r);let l=i.length,o=-1,a=0,u;for(;l--;){const s=i[l];if(typeof s=="string"){for(o=s.length;s.charCodeAt(o-1)===32;)a++,o--;if(o)break;o=-1}else if(s===-2)u=!0,a++;else if(s!==-1){l++;break}}if(n._contentTypeTextTrailing&&t===e.length&&(a=0),a){const s={type:t===e.length||u||a<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:l?o:r.start._bufferIndex+o,_index:r.start._index+l,line:r.end.line,column:r.end.column-a,offset:r.end.offset-a},end:{...r.end}};r.end={...s.start},r.start.offset===r.end.offset?Object.assign(r,s):(e.splice(t,0,["enter",s,n],["exit",s,n]),t+=2)}t++}return e}var Do=fe.__exportAll({attentionMarkers:()=>jo,contentInitial:()=>Mo,disable:()=>Ho,document:()=>Fo,flow:()=>_o,flowInitial:()=>Ro,insideSpan:()=>Bo,string:()=>Oo,text:()=>No}),Fo={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:ar},Mo={91:_l},Ro={[-2]:ht,[-1]:ht,32:ht},_o={35:ql,42:rt,45:[yn,rt],60:Wl,61:yn,95:rt,96:dn,126:dn},Oo={38:sr,92:ur},No={[-5]:mt,[-4]:mt,[-3]:mt,33:co,38:sr,42:zt,60:[pl,Zl],91:po,92:[jl,ur],93:Wt,95:zt,96:El},Bo={null:[zt,To]},jo={null:[42,95]},Ho={null:[]};function qo(e,n,t){let r={_bufferIndex:-1,_index:0,line:t&&t.line||1,column:t&&t.column||1,offset:t&&t.offset||0};const i={},l=[];let o=[],a=[];const u={attempt:B(P),check:B(S),consume:v,enter:b,exit:A,interrupt:B(S,{interrupt:!0})},s={code:null,containerState:{},defineSkip:k,events:[],now:x,parser:e,previous:null,sliceSerialize:h,sliceStream:p,write:c};let f=n.tokenize.call(s,u);return n.resolveAll&&l.push(n),s;function c(T){return o=ae(o,T),C(),o[o.length-1]!==null?[]:(U(n,0),s.events=ut(l,s.events,s),s.events)}function h(T,L){return $o(p(T),L)}function p(T){return Uo(o,T)}function x(){const{_bufferIndex:T,_index:L,line:$,column:X,offset:H}=r;return{_bufferIndex:T,_index:L,line:$,column:X,offset:H}}function k(T){i[T.line]=T.column,y()}function C(){let T;for(;r._index<o.length;){const L=o[r._index];if(typeof L=="string")for(T=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===T&&r._bufferIndex<L.length;)d(L.charCodeAt(r._bufferIndex));else d(L)}}function d(T){f=f(T)}function v(T){R(T)?(r.line++,r.column=1,r.offset+=T===-3?2:1,y()):T!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===o[r._index].length&&(r._bufferIndex=-1,r._index++)),s.previous=T}function b(T,L){const $=L||{};return $.type=T,$.start=x(),s.events.push(["enter",$,s]),a.push($),$}function A(T){const L=a.pop();return L.end=x(),s.events.push(["exit",L,s]),L}function P(T,L){U(T,L.from)}function S(T,L){L.restore()}function B(T,L){return $;function $(X,H,_){let M,K,ue,m;return Array.isArray(X)?he(X):"tokenize"in X?he([X]):ye(X);function ye(G){return Be;function Be(me){const Te=me!==null&&G[me],Pe=me!==null&&G.null;return he([...Array.isArray(Te)?Te:Te?[Te]:[],...Array.isArray(Pe)?Pe:Pe?[Pe]:[]])(me)}}function he(G){return M=G,K=0,G.length===0?_:g(G[K])}function g(G){return Be;function Be(me){return m=F(),ue=G,G.partial||(s.currentConstruct=G),G.name&&s.parser.constructs.disable.null.includes(G.name)?Ce(me):G.tokenize.call(L?Object.assign(Object.create(s),L):s,u,ke,Ce)(me)}}function ke(G){return T(ue,m),H}function Ce(G){return m.restore(),++K<M.length?g(M[K]):_}}}function U(T,L){T.resolveAll&&!l.includes(T)&&l.push(T),T.resolve&&oe(s.events,L,s.events.length-L,T.resolve(s.events.slice(L),s)),T.resolveTo&&(s.events=T.resolveTo(s.events,s))}function F(){const T=x(),L=s.previous,$=s.currentConstruct,X=s.events.length,H=Array.from(a);return{from:X,restore:_};function _(){r=T,s.previous=L,s.currentConstruct=$,s.events.length=X,a=H,y()}}function y(){r.line in i&&r.column<2&&(r.column=i[r.line],r.offset+=i[r.line]-1)}}function Uo(e,n){const t=n.start._index,r=n.start._bufferIndex,i=n.end._index,l=n.end._bufferIndex;let o;if(t===i)o=[e[t].slice(r,l)];else{if(o=e.slice(t,i),r>-1){const a=o[0];typeof a=="string"?o[0]=a.slice(r):o.shift()}l>0&&o.push(e[i].slice(0,l))}return o}function $o(e,n){let t=-1;const r=[];let i;for(;++t<e.length;){const l=e[t];let o;if(typeof l=="string")o=l;else switch(l){case-5:o="\r";break;case-4:o=`
3
3
  `;break;case-3:o=`\r
4
4
  `;break;case-2:o=n?" ":" ";break;case-1:if(!n&&i)continue;o=" ";break;default:o=String.fromCharCode(l)}i=l===-2,r.push(o)}return r.join("")}function Vo(e){const n={constructs:lr([Do,...(e||{}).extensions||[]]),content:t(ll),defined:[],document:t(al),flow:t(Io),lazy:{},string:t(Po),text:t(Lo)};return n;function t(r){return i;function i(l){return qo(n,r,l)}}}function Wo(e){for(;!cr(e););return e}var kn=/[\0\t\n\r]/g;function Xo(){let e=1,n="",t=!0,r;return i;function i(l,o,a){const u=[];let s,f,c,h,p;for(l=n+(typeof l=="string"?l.toString():new TextDecoder(o||void 0).decode(l)),c=0,n="",t&&(l.charCodeAt(0)===65279&&c++,t=void 0);c<l.length;){if(kn.lastIndex=c,s=kn.exec(l),h=s&&s.index!==void 0?s.index:l.length,p=l.charCodeAt(h),!s){n=l.slice(c);break}if(p===10&&c===h&&r)u.push(-3),r=void 0;else switch(r&&(u.push(-5),r=void 0),c<h&&(u.push(l.slice(c,h)),e+=h-c),p){case 0:u.push(65533),e++;break;case 9:for(f=Math.ceil(e/4)*4,u.push(-2);e++<f;)u.push(-1);break;case 10:u.push(-4),e=1;break;default:r=!0,e=1}c=h+1}return a&&(r&&u.push(-5),n&&u.push(n),u.push(null)),u}}var Yo=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Jo(e){return e.replace(Yo,Ko)}function Ko(e,n,t){if(n)return n;if(t.charCodeAt(0)===35){const r=t.charCodeAt(1),i=r===120||r===88;return or(t.slice(i?2:1),i?16:10)}return Vt(t)||e}var dr={}.hasOwnProperty;function Qo(e,n,t){return typeof n!="string"&&(t=n,n=void 0),Go(t)(Wo(Vo(t).document().write(Xo()(e,n,!0))))}function Go(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:l(tn),autolinkProtocol:F,autolinkEmail:F,atxHeading:l(Gt),blockQuote:l(Pe),characterEscape:F,characterReference:F,codeFenced:l(Qt),codeFencedFenceInfo:o,codeFencedFenceMeta:o,codeIndented:l(Qt,o),codeText:l(Qr,o),codeTextData:F,data:F,codeFlowValue:F,definition:l(Gr),definitionDestinationString:o,definitionLabelString:o,definitionTitleString:o,emphasis:l(Zr),hardBreakEscape:l(Zt),hardBreakTrailing:l(Zt),htmlFlow:l(en,o),htmlFlowData:F,htmlText:l(en,o),htmlTextData:F,image:l(ei),label:o,link:l(tn),listItem:l(ti),listItemValue:h,listOrdered:l(nn,c),listUnordered:l(nn),paragraph:l(ni),reference:g,referenceString:o,resourceDestinationString:o,resourceTitleString:o,setextHeading:l(Gt),strong:l(ri),thematicBreak:l(li)},exit:{atxHeading:u(),atxHeadingSequence:P,autolink:u(),autolinkEmail:Te,autolinkProtocol:me,blockQuote:u(),characterEscapeValue:y,characterReferenceMarkerHexadecimal:Ce,characterReferenceMarkerNumeric:Ce,characterReferenceValue:G,characterReference:Be,codeFenced:u(C),codeFencedFence:k,codeFencedFenceInfo:p,codeFencedFenceMeta:x,codeFlowValue:y,codeIndented:u(d),codeText:u(H),codeTextData:y,data:y,definition:u(),definitionDestinationString:A,definitionLabelString:v,definitionTitleString:b,emphasis:u(),hardBreakEscape:u(L),hardBreakTrailing:u(L),htmlFlow:u($),htmlFlowData:y,htmlText:u(X),htmlTextData:y,image:u(M),label:ue,labelText:K,lineEnding:T,link:u(_),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:ke,resourceDestinationString:m,resourceTitleString:ye,resource:he,setextHeading:u(U),setextHeadingLineSequence:B,setextHeadingText:S,strong:u(),thematicBreak:u()}};xr(n,(e||{}).mdastExtensions||[]);const t={};return r;function r(w){let I={type:"root",children:[]};const O={stack:[I],tokenStack:[],config:n,enter:a,exit:s,buffer:o,resume:f,data:t},Y=[];let J=-1;for(;++J<w.length;)(w[J][1].type==="listOrdered"||w[J][1].type==="listUnordered")&&(w[J][0]==="enter"?Y.push(J):J=i(w,Y.pop(),J));for(J=-1;++J<w.length;){const be=n[w[J][0]];dr.call(be,w[J][1].type)&&be[w[J][1].type].call(Object.assign({sliceSerialize:w[J][2].sliceSerialize},O),w[J][1])}if(O.tokenStack.length>0){const be=O.tokenStack[O.tokenStack.length-1];(be[1]||bn).call(O,void 0,be[0])}for(I.position={start:we(w.length>0?w[0][1].start:{line:1,column:1,offset:0}),end:we(w.length>0?w[w.length-2][1].end:{line:1,column:1,offset:0})},J=-1;++J<n.transforms.length;)I=n.transforms[J](I)||I;return I}function i(w,I,O){let Y=I-1,J=-1,be=!1,Le,ge,je,He;for(;++Y<=O;){const ie=w[Y];switch(ie[1].type){case"listUnordered":case"listOrdered":case"blockQuote":ie[0]==="enter"?J++:J--,He=void 0;break;case"lineEndingBlank":ie[0]==="enter"&&(Le&&!He&&!J&&!je&&(je=Y),He=void 0);break;case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:He=void 0}if(!J&&ie[0]==="enter"&&ie[1].type==="listItemPrefix"||J===-1&&ie[0]==="exit"&&(ie[1].type==="listUnordered"||ie[1].type==="listOrdered")){if(Le){let ze=Y;for(ge=void 0;ze--;){const de=w[ze];if(de[1].type==="lineEnding"||de[1].type==="lineEndingBlank"){if(de[0]==="exit")continue;ge&&(w[ge][1].type="lineEndingBlank",be=!0),de[1].type="lineEnding",ge=ze}else if(!(de[1].type==="linePrefix"||de[1].type==="blockQuotePrefix"||de[1].type==="blockQuotePrefixWhitespace"||de[1].type==="blockQuoteMarker"||de[1].type==="listItemIndent"))break}je&&(!ge||je<ge)&&(Le._spread=!0),Le.end=Object.assign({},ge?w[ge][1].start:ie[1].end),w.splice(ge||Y,0,["exit",Le,ie[2]]),Y++,O++}if(ie[1].type==="listItemPrefix"){const ze={type:"listItem",_spread:!1,start:Object.assign({},ie[1].start),end:void 0};Le=ze,w.splice(Y,0,["enter",ze,ie[2]]),Y++,O++,je=void 0,He=!0}}}return w[I][1]._spread=be,O}function l(w,I){return O;function O(Y){a.call(this,w(Y),Y),I&&I.call(this,Y)}}function o(){this.stack.push({type:"fragment",children:[]})}function a(w,I,O){this.stack[this.stack.length-1].children.push(w),this.stack.push(w),this.tokenStack.push([I,O||void 0]),w.position={start:we(I.start),end:void 0}}function u(w){return I;function I(O){w&&w.call(this,O),s.call(this,O)}}function s(w,I){const O=this.stack.pop(),Y=this.tokenStack.pop();if(Y)Y[0].type!==w.type&&(I?I.call(this,w,Y[0]):(Y[1]||bn).call(this,w,Y[0]));else throw new Error("Cannot close `"+w.type+"` ("+$e({start:w.start,end:w.end})+"): it’s not open");O.position.end=we(w.end)}function f(){return $t(this.stack.pop())}function c(){this.data.expectingFirstListItemValue=!0}function h(w){if(this.data.expectingFirstListItemValue){const I=this.stack[this.stack.length-2];I.start=Number.parseInt(this.sliceSerialize(w),10),this.data.expectingFirstListItemValue=void 0}}function p(){const w=this.resume(),I=this.stack[this.stack.length-1];I.lang=w}function x(){const w=this.resume(),I=this.stack[this.stack.length-1];I.meta=w}function k(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function C(){const w=this.resume(),I=this.stack[this.stack.length-1];I.value=w.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function d(){const w=this.resume(),I=this.stack[this.stack.length-1];I.value=w.replace(/(\r?\n|\r)$/g,"")}function v(w){const I=this.resume(),O=this.stack[this.stack.length-1];O.label=I,O.identifier=se(this.sliceSerialize(w)).toLowerCase()}function b(){const w=this.resume(),I=this.stack[this.stack.length-1];I.title=w}function A(){const w=this.resume(),I=this.stack[this.stack.length-1];I.url=w}function P(w){const I=this.stack[this.stack.length-1];I.depth||(I.depth=this.sliceSerialize(w).length)}function S(){this.data.setextHeadingSlurpLineEnding=!0}function B(w){const I=this.stack[this.stack.length-1];I.depth=this.sliceSerialize(w).codePointAt(0)===61?1:2}function U(){this.data.setextHeadingSlurpLineEnding=void 0}function F(w){const I=this.stack[this.stack.length-1].children;let O=I[I.length-1];(!O||O.type!=="text")&&(O=ii(),O.position={start:we(w.start),end:void 0},I.push(O)),this.stack.push(O)}function y(w){const I=this.stack.pop();I.value+=this.sliceSerialize(w),I.position.end=we(w.end)}function T(w){const I=this.stack[this.stack.length-1];if(this.data.atHardBreak){const O=I.children[I.children.length-1];O.position.end=we(w.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(I.type)&&(F.call(this,w),y.call(this,w))}function L(){this.data.atHardBreak=!0}function $(){const w=this.resume(),I=this.stack[this.stack.length-1];I.value=w}function X(){const w=this.resume(),I=this.stack[this.stack.length-1];I.value=w}function H(){const w=this.resume(),I=this.stack[this.stack.length-1];I.value=w}function _(){const w=this.stack[this.stack.length-1];if(this.data.inReference){const I=this.data.referenceType||"shortcut";w.type+="Reference",w.referenceType=I,delete w.url,delete w.title}else delete w.identifier,delete w.label;this.data.referenceType=void 0}function M(){const w=this.stack[this.stack.length-1];if(this.data.inReference){const I=this.data.referenceType||"shortcut";w.type+="Reference",w.referenceType=I,delete w.url,delete w.title}else delete w.identifier,delete w.label;this.data.referenceType=void 0}function K(w){const I=this.sliceSerialize(w),O=this.stack[this.stack.length-2];O.label=Jo(I),O.identifier=se(I).toLowerCase()}function ue(){const w=this.stack[this.stack.length-1],I=this.resume(),O=this.stack[this.stack.length-1];this.data.inReference=!0,O.type==="link"?O.children=w.children:O.alt=I}function m(){const w=this.resume(),I=this.stack[this.stack.length-1];I.url=w}function ye(){const w=this.resume(),I=this.stack[this.stack.length-1];I.title=w}function he(){this.data.inReference=void 0}function g(){this.data.referenceType="collapsed"}function ke(w){const I=this.resume(),O=this.stack[this.stack.length-1];O.label=I,O.identifier=se(this.sliceSerialize(w)).toLowerCase(),this.data.referenceType="full"}function Ce(w){this.data.characterReferenceType=w.type}function G(w){const I=this.sliceSerialize(w),O=this.data.characterReferenceType;let Y;O?(Y=or(I,O==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Y=Vt(I);const J=this.stack[this.stack.length-1];J.value+=Y}function Be(w){const I=this.stack.pop();I.position.end=we(w.end)}function me(w){y.call(this,w);const I=this.stack[this.stack.length-1];I.url=this.sliceSerialize(w)}function Te(w){y.call(this,w);const I=this.stack[this.stack.length-1];I.url="mailto:"+this.sliceSerialize(w)}function Pe(){return{type:"blockquote",children:[]}}function Qt(){return{type:"code",lang:null,meta:null,value:""}}function Qr(){return{type:"inlineCode",value:""}}function Gr(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Zr(){return{type:"emphasis",children:[]}}function Gt(){return{type:"heading",depth:0,children:[]}}function Zt(){return{type:"break"}}function en(){return{type:"html",value:""}}function ei(){return{type:"image",title:null,url:"",alt:null}}function tn(){return{type:"link",title:null,url:"",children:[]}}function nn(w){return{type:"list",ordered:w.type==="listOrdered",start:null,spread:w._spread,children:[]}}function ti(w){return{type:"listItem",spread:w._spread,checked:null,children:[]}}function ni(){return{type:"paragraph",children:[]}}function ri(){return{type:"strong",children:[]}}function ii(){return{type:"text",value:""}}function li(){return{type:"thematicBreak"}}}function we(e){return{line:e.line,column:e.column,offset:e.offset}}function xr(e,n){let t=-1;for(;++t<n.length;){const r=n[t];Array.isArray(r)?xr(e,r):Zo(e,r)}}function Zo(e,n){let t;for(t in n)if(dr.call(n,t))switch(t){case"canContainEols":{const r=n[t];r&&e[t].push(...r);break}case"transforms":{const r=n[t];r&&e[t].push(...r);break}case"enter":case"exit":{const r=n[t];r&&Object.assign(e[t],r);break}}}function bn(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+$e({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+$e({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+$e({start:n.start,end:n.end})+") is still open")}function ea(e){const n=this;n.parser=t;function t(r){return Qo(r,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function ta(e,n){const t={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(n),!0)};return e.patch(n,t),e.applyData(n,t)}function na(e,n){const t={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,t),[e.applyData(n,t),{type:"text",value:`
package/dist/react.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { n as Wn, r as Xn, t as Ge } from "./rolldown-runtime-DxmricAu.js";
2
- import { t as ci } from "./AgoClient-CBLJfu90.js";
3
- import { i as fi, n as cf, r as Yn, t as Kn } from "./createFormCollector-CyD7KnjG.js";
2
+ import { t as ci } from "./AgoClient-j1sk1hK5.js";
3
+ import { i as fi, n as cf, r as Yn, t as Kn } from "./createFormCollector-BPKzKDeX.js";
4
4
  import { t as pf } from "./createMockClient-DwdxNwEn.js";
5
5
  import pi, { createContext as hi, useCallback as xe, useContext as Qn, useEffect as Z, useId as mi, useMemo as Me, useRef as Be, useState as ue, useSyncExternalStore as gi } from "react";
6
6
  import { Fragment as Gn, jsx as R, jsxs as ce } from "react/jsx-runtime";
package/dist/vue.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=require("./rolldown-runtime-CaekUdDJ.cjs"),p=require("./AgoClient-nYVPdI5x.cjs");let t=require("vue");var I=Symbol("ago-client"),y={install(o,n){const e=new p.AgoClient(n);o.provide(I,e)}};function g(o){if(o)return new p.AgoClient(o);const n=(0,t.inject)(I);if(!n)throw new Error("useAgo(): no AgoClient found. Either pass config or install AgoPlugin.");return n}function E(o={}){const n=o.client??g(),e=(0,t.ref)([]),s=(0,t.ref)(o.conversationId),i=(0,t.ref)(!1),r=(0,t.ref)(null),c=a=>{s.value||(s.value=a.conversationId)},f=a=>{const u=e.value.findIndex(v=>v.id===a.messageId);u>=0&&(e.value[u]={...e.value[u],content:e.value[u].content+a.content})},m=a=>{const u=e.value.findIndex(v=>v.id===a.id);u>=0?e.value[u]=a:e.value.push(a),i.value=!1},C=a=>{r.value=new Error(a.error),i.value=!1};(0,t.onMounted)(()=>{n.on("message:start",c),n.on("message:chunk",f),n.on("message:complete",m),n.on("message:error",C)}),(0,t.onUnmounted)(()=>{n.off("message:start",c),n.off("message:chunk",f),n.off("message:complete",m),n.off("message:error",C)});async function d(a,u){i.value=!0,r.value=null;const v={id:`temp-${Date.now()}`,conversationId:s.value||"",content:a,role:"user",status:"DONE",createdAt:new Date},L={id:`temp-assistant-${Date.now()}`,conversationId:s.value||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};e.value.push(v,L);try{const l=await n.sendMessage(a,{conversationId:s.value,files:u});l.conversationId&&!s.value&&(s.value=l.conversationId),e.value=e.value.filter(w=>!w.id.startsWith("temp-"));const A={...v,id:v.id.replace("temp-","user-"),conversationId:l.conversationId};return e.value.some(w=>w.id===l.id)?e.value.push(A):e.value.push(A,l),l}catch(l){return r.value=l instanceof Error?l:new Error("Failed to send"),i.value=!1,e.value=e.value.filter(A=>!A.id.startsWith("temp-")),null}}function h(){e.value=[],s.value=void 0,r.value=null}return{messages:e,isLoading:i,error:r,conversationId:s,sendMessage:d,clearMessages:h}}function M(o={}){const n=o.client??g(),e=o.autoLoad??!0,s=(0,t.ref)([]),i=(0,t.ref)(null),r=(0,t.ref)(!1),c=(0,t.ref)(null);async function f(){r.value=!0,c.value=null;try{s.value=await n.getConversations()}catch(d){c.value=d instanceof Error?d:new Error("Failed to load conversations")}finally{r.value=!1}}async function m(d){r.value=!0,c.value=null;try{i.value=await n.getConversation(d)}catch(h){c.value=h instanceof Error?h:new Error("Failed to load conversation")}finally{r.value=!1}}function C(){i.value=null}return(0,t.onMounted)(()=>{e&&f()}),{conversations:s,currentConversation:i,isLoading:r,error:c,selectConversation:m,startNewConversation:C,refreshConversations:f}}function N(o={}){const n=E({client:o.client,conversationId:o.conversationId}),e=M({client:o.client,autoLoad:o.autoLoad}),s=(0,t.computed)(()=>n.error.value||e.error.value);return{messages:n.messages,isLoading:n.isLoading,error:s,sendMessage:n.sendMessage,clearMessages:n.clearMessages,conversationId:n.conversationId,conversations:e.conversations,currentConversation:e.currentConversation,isConversationsLoading:e.isLoading,selectConversation:e.selectConversation,startNewConversation:e.startNewConversation,refreshConversations:e.refreshConversations}}function F(o,n){const e=g();(0,t.onMounted)(()=>{e.registerFunction(o,n.handler,{description:n.description,parameters:n.parameters})}),(0,t.onUnmounted)(()=>{e.unregisterFunction(o)})}function S(o,n){const e=g();(0,t.onMounted)(()=>{e.registerNavigationFunction(o,n)}),(0,t.onUnmounted)(()=>{e.unregisterFunction("navigateToPage")})}function _(o,n){const e=g();(0,t.onMounted)(()=>{e.on(o,n)}),(0,t.onUnmounted)(()=>{e.off(o,n)})}function D(o){const n=(0,t.shallowRef)(o.get());return(0,t.onScopeDispose)(o.subscribe(e=>{n.value=e})),n}exports.AGO_CLIENT_KEY=I;exports.AgoPlugin=y;exports.useAgo=g;exports.useAgoEvents=_;exports.useAgoFunction=F;exports.useAgoNavigation=S;exports.useAgoStore=D;exports.useChat=N;exports.useConversation=M;exports.useMessages=E;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=require("./rolldown-runtime-CaekUdDJ.cjs"),p=require("./AgoClient-1jgDndKs.cjs");let t=require("vue");var I=Symbol("ago-client"),y={install(o,n){const e=new p.AgoClient(n);o.provide(I,e)}};function g(o){if(o)return new p.AgoClient(o);const n=(0,t.inject)(I);if(!n)throw new Error("useAgo(): no AgoClient found. Either pass config or install AgoPlugin.");return n}function E(o={}){const n=o.client??g(),e=(0,t.ref)([]),s=(0,t.ref)(o.conversationId),i=(0,t.ref)(!1),r=(0,t.ref)(null),c=a=>{s.value||(s.value=a.conversationId)},f=a=>{const u=e.value.findIndex(v=>v.id===a.messageId);u>=0&&(e.value[u]={...e.value[u],content:e.value[u].content+a.content})},m=a=>{const u=e.value.findIndex(v=>v.id===a.id);u>=0?e.value[u]=a:e.value.push(a),i.value=!1},C=a=>{r.value=new Error(a.error),i.value=!1};(0,t.onMounted)(()=>{n.on("message:start",c),n.on("message:chunk",f),n.on("message:complete",m),n.on("message:error",C)}),(0,t.onUnmounted)(()=>{n.off("message:start",c),n.off("message:chunk",f),n.off("message:complete",m),n.off("message:error",C)});async function d(a,u){i.value=!0,r.value=null;const v={id:`temp-${Date.now()}`,conversationId:s.value||"",content:a,role:"user",status:"DONE",createdAt:new Date},L={id:`temp-assistant-${Date.now()}`,conversationId:s.value||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};e.value.push(v,L);try{const l=await n.sendMessage(a,{conversationId:s.value,files:u});l.conversationId&&!s.value&&(s.value=l.conversationId),e.value=e.value.filter(w=>!w.id.startsWith("temp-"));const A={...v,id:v.id.replace("temp-","user-"),conversationId:l.conversationId};return e.value.some(w=>w.id===l.id)?e.value.push(A):e.value.push(A,l),l}catch(l){return r.value=l instanceof Error?l:new Error("Failed to send"),i.value=!1,e.value=e.value.filter(A=>!A.id.startsWith("temp-")),null}}function h(){e.value=[],s.value=void 0,r.value=null}return{messages:e,isLoading:i,error:r,conversationId:s,sendMessage:d,clearMessages:h}}function M(o={}){const n=o.client??g(),e=o.autoLoad??!0,s=(0,t.ref)([]),i=(0,t.ref)(null),r=(0,t.ref)(!1),c=(0,t.ref)(null);async function f(){r.value=!0,c.value=null;try{s.value=await n.getConversations()}catch(d){c.value=d instanceof Error?d:new Error("Failed to load conversations")}finally{r.value=!1}}async function m(d){r.value=!0,c.value=null;try{i.value=await n.getConversation(d)}catch(h){c.value=h instanceof Error?h:new Error("Failed to load conversation")}finally{r.value=!1}}function C(){i.value=null}return(0,t.onMounted)(()=>{e&&f()}),{conversations:s,currentConversation:i,isLoading:r,error:c,selectConversation:m,startNewConversation:C,refreshConversations:f}}function N(o={}){const n=E({client:o.client,conversationId:o.conversationId}),e=M({client:o.client,autoLoad:o.autoLoad}),s=(0,t.computed)(()=>n.error.value||e.error.value);return{messages:n.messages,isLoading:n.isLoading,error:s,sendMessage:n.sendMessage,clearMessages:n.clearMessages,conversationId:n.conversationId,conversations:e.conversations,currentConversation:e.currentConversation,isConversationsLoading:e.isLoading,selectConversation:e.selectConversation,startNewConversation:e.startNewConversation,refreshConversations:e.refreshConversations}}function F(o,n){const e=g();(0,t.onMounted)(()=>{e.registerFunction(o,n.handler,{description:n.description,parameters:n.parameters})}),(0,t.onUnmounted)(()=>{e.unregisterFunction(o)})}function S(o,n){const e=g();(0,t.onMounted)(()=>{e.registerNavigationFunction(o,n)}),(0,t.onUnmounted)(()=>{e.unregisterFunction("navigateToPage")})}function _(o,n){const e=g();(0,t.onMounted)(()=>{e.on(o,n)}),(0,t.onUnmounted)(()=>{e.off(o,n)})}function D(o){const n=(0,t.shallowRef)(o.get());return(0,t.onScopeDispose)(o.subscribe(e=>{n.value=e})),n}exports.AGO_CLIENT_KEY=I;exports.AgoPlugin=y;exports.useAgo=g;exports.useAgoEvents=_;exports.useAgoFunction=F;exports.useAgoNavigation=S;exports.useAgoStore=D;exports.useChat=N;exports.useConversation=M;exports.useMessages=E;
package/dist/vue.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as A } from "./AgoClient-CBLJfu90.js";
1
+ import { t as A } from "./AgoClient-j1sk1hK5.js";
2
2
  import { computed as y, inject as F, onMounted as g, onScopeDispose as N, onUnmounted as I, ref as c, shallowRef as D } from "vue";
3
3
  var L = /* @__PURE__ */ Symbol("ago-client"), b = { install(t, n) {
4
4
  const e = new A(n);
package/dist/widget.cjs CHANGED
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ke=require("./AgoClient-nYVPdI5x.cjs"),$e=require("./createFormCollector-CQKfRjfj.cjs"),Ke=require("./createConversationSession-CnIchjFa.cjs");var Ve={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function U(o){return o.replace(/[&<>"']/g,n=>Ve[n])}function Ae(o){const n=o.trim();return/^(https?:|mailto:|tel:|#|\/|\.\/|\.\.\/)/i.test(n)||!/^[a-z][a-z0-9+.-]*:/i.test(n)?n:null}var Te='"IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, monospace',Q="";function M(o){const n=[],r=u=>(n.push(u),`${Q}${n.length-1}${Q}`);let t=o;return t=t.replace(/`([^`]+)`/g,(u,i)=>r(`<code style="background:#f0f2f5;padding:2px 5px;border-radius:4px;font-size:13px;font-family:${Te}">${U(i)}</code>`)),t=t.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g,(u,i,f)=>{const s=Ae(f);return s?r(`<img alt="${U(i)}" src="${U(s)}" style="max-width:100%;border-radius:8px;margin:4px 0" />`):u}),t=t.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(u,i,f)=>{const s=Ae(f);return s?r(`<a href="${U(s)}" target="_blank" rel="noopener noreferrer" style="color:#1b5fc4;text-decoration:underline">${M(i)}</a>`):u}),t=U(t),t=t.replace(/\*\*([^*]+?)\*\*/g,"<strong>$1</strong>").replace(/__([^_]+?)__/g,"<strong>$1</strong>").replace(/~~([^~]+?)~~/g,"<del>$1</del>").replace(/(^|[^*])\*(?!\s)([^*]+?)\*/g,"$1<em>$2</em>").replace(/(^|[^\w_])_(?!\s)([^_]+?)_/g,"$1<em>$2</em>"),t=t.replace(new RegExp(`${Q}(\\d+)${Q}`,"g"),(u,i)=>n[Number(i)]),t}function _(o,n,r){const t=document.createElement(o);return Object.assign(t.style,n),r!==void 0&&(t.innerHTML=r),t}var De=/^ {0,3}([-*_])( *\1){2,} *$/,Me=/^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/,Be=/^ {0,3}(```+|~~~+)/,Z=/^ {0,3}>\s?/,P=/^(\s*)([-*+]|\d+[.)])\s+(.*)$/,Qe=["20px","18px","16px","15px","14px","13px"],fe=o=>o.match(/^\s*/)?.[0].length??0;function Ye(o){return o.trim()===""||De.test(o)||Me.test(o)||Be.test(o)||Z.test(o)||P.test(o)}function ze(o){const n=o[0].match(P),r=n[1].length,t=/\d/.test(n[2]),u=_(t?"ol":"ul",{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:t?"decimal":"disc",listStylePosition:"outside"});let i=0;for(;i<o.length;){const f=o[i].match(P),s=[];for(i++;i<o.length&&fe(o[i])>r;)s.push(o[i]),i++;const p=_("li",{display:"list-item",margin:"2px 0",lineHeight:"1.6"}),c=f[3].match(/^\[([ xX])\]\s+(.*)$/);c?(p.style.listStyleType="none",p.style.marginLeft="-20px",p.innerHTML=`<span style="margin-right:6px">${c[1].toLowerCase()==="x"?"☑":"☐"}</span>${M(c[2])}`):p.innerHTML=M(f[3]),s.filter(h=>P.test(h)).length>0&&p.appendChild(ze(s.filter(h=>h.trim()!==""))),u.appendChild(p)}return u}function Ze(o){const n=s=>s.replace(/^\s*\|?/,"").replace(/\|?\s*$/,"").split("|").map(p=>p.trim()),r=_("div",{overflowX:"auto",margin:"0 0 8px 0"}),t=_("table",{borderCollapse:"collapse",width:"100%",fontSize:"13px"}),u=document.createElement("thead"),i=document.createElement("tr");for(const s of n(o[0]))i.appendChild(_("th",{border:"1px solid #dee3e8",padding:"6px 10px",textAlign:"left",backgroundColor:"#f5f7fa",fontWeight:"600"},M(s)));u.appendChild(i),t.appendChild(u);const f=document.createElement("tbody");for(const s of o.slice(2)){const p=document.createElement("tr");for(const c of n(s))p.appendChild(_("td",{border:"1px solid #dee3e8",padding:"6px 10px"},M(c)));f.appendChild(p)}return t.appendChild(f),r.appendChild(t),r}var Je=o=>!!o&&/^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/.test(o);function J(o){const n=document.createDocumentFragment(),r=o.replace(/\r\n?/g,`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ke=require("./AgoClient-1jgDndKs.cjs"),$e=require("./createFormCollector-B8V9YSGe.cjs"),Ke=require("./createConversationSession-BYNhYbkY.cjs");var Ve={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function U(o){return o.replace(/[&<>"']/g,n=>Ve[n])}function Ae(o){const n=o.trim();return/^(https?:|mailto:|tel:|#|\/|\.\/|\.\.\/)/i.test(n)||!/^[a-z][a-z0-9+.-]*:/i.test(n)?n:null}var Te='"IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, monospace',Q="";function M(o){const n=[],r=u=>(n.push(u),`${Q}${n.length-1}${Q}`);let t=o;return t=t.replace(/`([^`]+)`/g,(u,i)=>r(`<code style="background:#f0f2f5;padding:2px 5px;border-radius:4px;font-size:13px;font-family:${Te}">${U(i)}</code>`)),t=t.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g,(u,i,f)=>{const s=Ae(f);return s?r(`<img alt="${U(i)}" src="${U(s)}" style="max-width:100%;border-radius:8px;margin:4px 0" />`):u}),t=t.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(u,i,f)=>{const s=Ae(f);return s?r(`<a href="${U(s)}" target="_blank" rel="noopener noreferrer" style="color:#1b5fc4;text-decoration:underline">${M(i)}</a>`):u}),t=U(t),t=t.replace(/\*\*([^*]+?)\*\*/g,"<strong>$1</strong>").replace(/__([^_]+?)__/g,"<strong>$1</strong>").replace(/~~([^~]+?)~~/g,"<del>$1</del>").replace(/(^|[^*])\*(?!\s)([^*]+?)\*/g,"$1<em>$2</em>").replace(/(^|[^\w_])_(?!\s)([^_]+?)_/g,"$1<em>$2</em>"),t=t.replace(new RegExp(`${Q}(\\d+)${Q}`,"g"),(u,i)=>n[Number(i)]),t}function _(o,n,r){const t=document.createElement(o);return Object.assign(t.style,n),r!==void 0&&(t.innerHTML=r),t}var De=/^ {0,3}([-*_])( *\1){2,} *$/,Me=/^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/,Be=/^ {0,3}(```+|~~~+)/,Z=/^ {0,3}>\s?/,P=/^(\s*)([-*+]|\d+[.)])\s+(.*)$/,Qe=["20px","18px","16px","15px","14px","13px"],fe=o=>o.match(/^\s*/)?.[0].length??0;function Ye(o){return o.trim()===""||De.test(o)||Me.test(o)||Be.test(o)||Z.test(o)||P.test(o)}function ze(o){const n=o[0].match(P),r=n[1].length,t=/\d/.test(n[2]),u=_(t?"ol":"ul",{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:t?"decimal":"disc",listStylePosition:"outside"});let i=0;for(;i<o.length;){const f=o[i].match(P),s=[];for(i++;i<o.length&&fe(o[i])>r;)s.push(o[i]),i++;const p=_("li",{display:"list-item",margin:"2px 0",lineHeight:"1.6"}),c=f[3].match(/^\[([ xX])\]\s+(.*)$/);c?(p.style.listStyleType="none",p.style.marginLeft="-20px",p.innerHTML=`<span style="margin-right:6px">${c[1].toLowerCase()==="x"?"☑":"☐"}</span>${M(c[2])}`):p.innerHTML=M(f[3]),s.filter(h=>P.test(h)).length>0&&p.appendChild(ze(s.filter(h=>h.trim()!==""))),u.appendChild(p)}return u}function Ze(o){const n=s=>s.replace(/^\s*\|?/,"").replace(/\|?\s*$/,"").split("|").map(p=>p.trim()),r=_("div",{overflowX:"auto",margin:"0 0 8px 0"}),t=_("table",{borderCollapse:"collapse",width:"100%",fontSize:"13px"}),u=document.createElement("thead"),i=document.createElement("tr");for(const s of n(o[0]))i.appendChild(_("th",{border:"1px solid #dee3e8",padding:"6px 10px",textAlign:"left",backgroundColor:"#f5f7fa",fontWeight:"600"},M(s)));u.appendChild(i),t.appendChild(u);const f=document.createElement("tbody");for(const s of o.slice(2)){const p=document.createElement("tr");for(const c of n(s))p.appendChild(_("td",{border:"1px solid #dee3e8",padding:"6px 10px"},M(c)));f.appendChild(p)}return t.appendChild(f),r.appendChild(t),r}var Je=o=>!!o&&/^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/.test(o);function J(o){const n=document.createDocumentFragment(),r=o.replace(/\r\n?/g,`
2
2
  `).split(`
3
3
  `);let t=0;for(;t<r.length;){const i=r[t];if(i.trim()===""){t++;continue}const f=i.match(Be);if(f){const c=f[1][0],h=[];for(t++;t<r.length&&!new RegExp(`^ {0,3}${c==="`"?"`{3,}":"~{3,}"}\\s*$`).test(r[t]);)h.push(r[t]),t++;t++;const L=_("pre",{margin:"0 0 8px 0"});L.appendChild(_("code",{display:"block",background:"#f5f5f5",padding:"8px 12px",borderRadius:"6px",fontSize:"13px",overflowX:"auto",fontFamily:Te,whiteSpace:"pre"},U(h.join(`
4
4
  `)))),n.appendChild(L);continue}if(De.test(i)){n.appendChild(_("hr",{border:"none",borderTop:"1px solid #dee3e8",margin:"12px 0"})),t++;continue}const s=i.match(Me);if(s){const c=s[1].length;n.appendChild(_(`h${c}`,{margin:"16px 0 8px 0",fontSize:Qe[c-1],fontWeight:"600",lineHeight:"1.3"},M(s[2]))),t++;continue}if(Z.test(i)){const c=[];for(;t<r.length&&Z.test(r[t]);)c.push(r[t].replace(Z,"")),t++;const h=_("blockquote",{borderLeft:"4px solid #dee3e8",paddingLeft:"12px",margin:"0 0 8px 0",fontStyle:"italic",color:"#6b6d6f"});h.appendChild(J(c.join(`
package/dist/widget.js CHANGED
@@ -1,6 +1,6 @@
1
- import { t as Xe, u as Ke } from "./AgoClient-CBLJfu90.js";
2
- import { r as qe, t as Ve } from "./createFormCollector-CyD7KnjG.js";
3
- import { t as Qe } from "./createConversationSession-D3aHSSir.js";
1
+ import { t as Xe, u as Ke } from "./AgoClient-j1sk1hK5.js";
2
+ import { r as qe, t as Ve } from "./createFormCollector-BPKzKDeX.js";
3
+ import { t as Qe } from "./createConversationSession-CZhoTCtD.js";
4
4
  var Ye = {
5
5
  "&": "&amp;",
6
6
  "<": "&lt;",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@useago/sdk",
3
- "version": "1.0.3",
3
+ "version": "1.0.4",
4
4
  "description": "Create In-APP AI agents that answers question and performs actions. Works with React, Vue, Angular and vanilla JS/TS.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -1,6 +0,0 @@
1
- var h=class extends Error{constructor(e,t,s){super(e),this.code=t,this.statusCode=s,this.name="AgoError"}},u=class v extends h{constructor(t,s,r,n,i,a){super(t,s,r),this.type=n,this.param=i,this.docUrl=a,this.name="AgoApiError"}static fromResponse(t,s){const r=t.error;return new v(r.doc_url?`${r.message} See ${r.doc_url}`:r.message,r.code,s,r.type,r.param,r.doc_url)}},d=class extends h{constructor(e,t){super(e,"network_error"),this.originalError=t,this.name="AgoNetworkError"}},g=class extends h{constructor(e,t="stream_error"){super(e,t),this.name="AgoStreamError"}},m=class extends h{constructor(e,t,s){super(e,"function_error"),this.functionName=t,this.originalError=s,this.name="AgoFunctionError"}},A=class{constructor(e=!1){this.enabled=e}enable(){this.enabled=!0}disable(){this.enabled=!1}log(...e){this.enabled&&console.log("[AGO SDK]",...e)}warn(...e){this.enabled&&console.warn("[AGO SDK]",...e)}error(...e){console.error("[AGO SDK]",...e)}debug(...e){this.enabled&&console.debug("[AGO SDK]",...e)}},o=new A,p="ago_widget_id";function x(){if(typeof localStorage<"u"){const t=localStorage.getItem(p);if(t)return t}const e=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`ago-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`;if(typeof localStorage<"u")try{localStorage.setItem(p,e)}catch{}return e}var $=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.headers={"X-User-Anon-Id":e.widgetId||x()},e.userEmail&&(this.headers["X-User-Email"]=e.userEmail),e.userJwt&&(this.headers.Authorization=`Bearer ${e.userJwt}`),e.permission&&(this.headers["X-Widget-Permission"]=e.permission)}updateConfig(e){e.baseUrl&&(this.baseUrl=e.baseUrl.replace(/\/$/,"")),e.widgetId&&(this.headers["X-User-Anon-Id"]=e.widgetId),e.userEmail&&(this.headers["X-User-Email"]=e.userEmail),e.userJwt&&(this.headers.Authorization=`Bearer ${e.userJwt}`),e.permission!==void 0&&(e.permission?this.headers["X-Widget-Permission"]=e.permission:delete this.headers["X-Widget-Permission"])}async get(e){return this.request("GET",e)}async post(e,t){return this.request("POST",e,t)}async postStream(e,t){const s=`${this.baseUrl}${e}`;o.debug("POST (stream)",s,t);try{const r=await fetch(s,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0});return r.ok||await this.handleErrorResponse(r),r}catch(r){throw r instanceof u?r:new d(`Network error: ${r instanceof Error?r.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,r instanceof Error?r:void 0)}}async postFormData(e,t){const s=`${this.baseUrl}${e}`;o.debug("POST (formData)",s);const r={...this.headers};try{const n=await fetch(s,{method:"POST",headers:r,body:t});return n.ok||await this.handleErrorResponse(n),n}catch(n){throw n instanceof u?n:new d(`Network error: ${n instanceof Error?n.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,n instanceof Error?n:void 0)}}async request(e,t,s){const r=`${this.baseUrl}${t}`;o.debug(e,r,s);try{const n=await fetch(r,{method:e,headers:{...this.headers,"Content-Type":"application/json"},body:s?JSON.stringify(s):void 0});return n.ok||await this.handleErrorResponse(n),n.status===204?void 0:n.json()}catch(n){throw n instanceof u?n:new d(`Network error: ${n instanceof Error?n.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,n instanceof Error?n:void 0)}}async handleErrorResponse(e){let t;try{t=await e.json()}catch{}if(t?.error)throw u.fromResponse(t,e.status);let s="";throw e.status===401||e.status===403?s=" Check `userJwt` (and that it has not expired).":e.status===404&&(s=" Check that `baseUrl` points at your AGO API root."),new u(`HTTP ${e.status}: ${e.statusText}.${s}`,"http_error",e.status,"api_error")}},b=class{constructor(){this.functions=new Map}register(e,t,s){if(typeof e=="object"){const{name:n,handler:i,description:a,parameters:l}=e;return this.register(n,i,{description:a,parameters:l})}const r=e;if(!t||!s)throw new h(`registerFunction("${r}"): both a handler and a schema are required. Pass them as arguments or use the single-object form: registerFunction({ name, parameters, handler }).`,"function_invalid_registration");this.functions.has(r)&&o.warn(`Function "${r}" is being overwritten`),this.functions.set(r,{schema:{...s,name:r},handler:t}),o.log(`Registered function: ${r}`)}unregister(e){const t=this.functions.delete(e);return t&&o.log(`Unregistered function: ${e}`),t}get(e){return this.functions.get(e)}has(e){return this.functions.has(e)}getSchemas(){return Array.from(this.functions.values()).map(e=>e.schema)}async execute(e,t){const s=this.functions.get(e);if(!s)throw new m(`Function "${e}" is not registered`,e);o.log(`Executing function: ${e}`,t);try{const r=await s.handler(t);return o.log(`Function ${e} completed:`,r),r}catch(r){throw o.error(`Function ${e} failed:`,r),new m(`Function "${e}" execution failed: ${r instanceof Error?r.message:"Unknown error"}`,e,r instanceof Error?r:void 0)}}clear(){this.functions.clear(),o.log("Cleared all registered functions")}get size(){return this.functions.size}},C=class{constructor(){this.entries=new Map,this.dynamicProviders=new Map}set(e,t){this.entries.set(e,t),o.log(`ClientContext set: ${e}`)}remove(e){const t=this.entries.delete(e);return t&&o.log(`ClientContext removed: ${e}`),t}addDynamicProvider(e,t){this.dynamicProviders.set(e,t),o.log(`DynamicContext provider added: ${e}`)}removeDynamicProvider(e){const t=this.dynamicProviders.delete(e);return t&&o.log(`DynamicContext provider removed: ${e}`),t}getSnapshot(){if(this.entries.size===0&&this.dynamicProviders.size===0)return null;const e={};for(const[t,s]of this.entries)e[t]=s;for(const[t,s]of this.dynamicProviders)try{const r=s();r&&(e[t]=r)}catch(r){o.error(`DynamicContext provider "${t}" threw:`,r)}return Object.keys(e).length===0?null:{entries:e}}clear(){this.entries.clear(),this.dynamicProviders.clear(),o.log("ClientContext cleared")}},E=class{constructor(e){this.callbacks=e,this.buffer="",this.message={},this.toolCalls=[],this.sources=[],this.followUpReplies=[],this.isFirstChunk=!0,this.answerCompleteEmitted=!1}async processStream(e){if(!e.body)throw new g("Response has no body. The endpoint did not return a stream: check that `baseUrl` points at an AGO API and nothing (proxy, mock) strips the SSE body.","stream_no_body");const t=e.body.getReader(),s=new TextDecoder;try{for(;;){const{done:r,value:n}=await t.read();if(r)break;const i=s.decode(n,{stream:!0});this.buffer+=i,this.processBuffer()}return this.buffer.trim()&&this.processBuffer(),this.buildFinalMessage()}catch(r){const n=r instanceof Error?r:new g("Stream processing failed mid-flight. The connection may have dropped; retry the message.");throw this.callbacks.onError?.(n),n}finally{t.releaseLock()}}processBuffer(){const e=this.buffer.split(`
2
-
3
- `);this.buffer=e.pop()||"";for(const t of e){if(!t.trim())continue;const s=t.split(`
4
- `);for(const r of s)if(!r.startsWith(": ")&&r.startsWith("data: ")){const n=r.slice(6);try{const i=JSON.parse(n);this.handleChunk(i)}catch(i){o.warn("Failed to parse SSE data:",n,i)}}}}handleChunk(e){if(e.message_id&&!this.message.id&&(this.message.id=e.message_id),e.thread?.id&&(this.message.conversationId=e.thread.id,this.isFirstChunk&&this.message.id&&(this.isFirstChunk=!1,this.callbacks.onStart?.({conversationId:this.message.conversationId,messageId:this.message.id}))),e.content!==void 0&&(this.message.content=(this.message.content||"")+e.content,this.message.conversationId&&this.message.id&&this.callbacks.onChunk?.({content:e.content,conversationId:this.message.conversationId,messageId:this.message.id})),e.full_content!==void 0&&(this.message.content=e.full_content),e.status&&(this.message.status=e.status),e.agent&&(this.message.agent={id:e.agent.id,name:e.agent.name,displayName:e.agent.display_name}),e.knowledge_sources&&(this.sources=e.knowledge_sources.map(t=>{const s=t.knowledge_document;return{id:s.id,title:s.title,url:s.use_external_link?s.external_link_url:s.internal_link_url}})),e.type==="client_function"&&e.function_name&&this.callbacks.onClientFunction?.({invocationId:e.id||"",functionName:e.function_name,arguments:e.arguments||{},conversationId:this.message.conversationId||""}),e.tool_call_data&&e.type&&e.type!=="client_function"){const t=this.parseToolCall(e);this.callbacks.onToolCall?.(t);const s=this.toolCalls.findIndex(r=>r.id===t.id);s>=0?this.toolCalls[s]=t:this.toolCalls.push(t)}e.follow_up_replies&&(this.followUpReplies=e.follow_up_replies),this.message.status==="DONE"&&!this.answerCompleteEmitted&&this.message.id&&(this.answerCompleteEmitted=!0,this.callbacks.onAnswerComplete?.(this.buildMessage()))}parseToolCall(e){return{id:e.id||"",type:e.type||"status_message",status:e.status||"unknown",toolName:e.tool_name||"",toolDisplayName:e.tool_display_name,message:e.message,formSchema:e.form_schema,data:e.data,functionName:e.function_name,arguments:e.arguments}}buildMessage(){return{id:this.message.id||"",conversationId:this.message.conversationId||"",content:this.message.content||"",role:"assistant",status:this.message.status||"DONE",agent:this.message.agent,sources:this.sources.length>0?this.sources:void 0,toolCalls:this.toolCalls.length>0?this.toolCalls:void 0,followUpReplies:this.followUpReplies.length>0?this.followUpReplies:void 0,createdAt:new Date}}buildFinalMessage(){const e=this.buildMessage();return this.callbacks.onComplete?.(e),e}};function R(e){const t=e.message.toLowerCase();return t.includes("load failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("abort")}var _=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){const s=this.handlers.get(e);s&&s.delete(t)}emit(e,t){const s=this.handlers.get(e);s&&s.forEach(r=>{try{r(t)}catch(n){console.error(`Error in event handler for ${String(e)}:`,n)}})}once(e,t){const s=(r=>{this.off(e,s),t(r)});this.on(e,s)}waitFor(e,t){return new Promise((s,r)=>{let n;const i=(a=>{n&&clearTimeout(n),s(a)});this.once(e,i),t?.timeout&&(n=setTimeout(()=>{this.off(e,i),r(new Error(`waitFor("${String(e)}") timed out after ${t.timeout}ms`))},t.timeout))})}removeAllListeners(e){e?this.handlers.delete(e):this.handlers.clear()}},y='`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the live demo endpoint https://playground.api.useago.com. See docs/general/configuration.md#error-codes (config_missing_base_url).',I=/^[a-z][a-z0-9+.-]*:\/\//i,w=!1;function f(e,t="AgoClient"){if(typeof e!="object"||e===null)throw new h(`${t}: ${y}`,"config_missing_base_url");const s=e.baseUrl;if(typeof s!="string"||s.trim()==="")throw new h(`${t}: ${y}`,"config_missing_base_url");!s.startsWith("/")&&!I.test(s)&&(w||(w=!0,console.warn(`[AGO] ${t}: \`baseUrl\` has no protocol and is not a relative path (config_suspect_base_url). Requests will fail: Node throws a URL parse error, browsers fetch it as a relative path. Use "https://..." (or a "/path" for a same-origin proxy).`)))}var U=class S{constructor(t){this.warnedEmptyConversations=new Set,f(t,"AgoClient"),this.config=t,this.httpClient=new $(t),this.functionRegistry=new b,this.contextRegistry=new C,this.eventEmitter=new _,t.debug&&o.enable(),o.log("AgoClient initialized")}async sendMessage(t,s){const r=this.functionRegistry.getSchemas(),n=this.contextRegistry.getSnapshot(),i=this.config.agent||this.config.defaultAgentId,a={content:t,conversation_id:s?.conversationId,agent_id:s?.agentId||i};r.length>0&&(a.client_functions=r),n&&(a.client_context=n);let l;if(s?.files&&s.files.length>0){const c=new FormData;c.append("content",t),s.conversationId&&c.append("conversation_id",s.conversationId),(s.agentId||i)&&c.append("agent_id",s.agentId||i||""),r.length>0&&c.append("client_functions",JSON.stringify(r)),n&&c.append("client_context",JSON.stringify(n));for(const k of s.files)c.append("files",k);l=await this.httpClient.postFormData("/api/sdk/v1/messages",c)}else l=await this.httpClient.postStream("/api/sdk/v1/messages",a);return this.processSSEResponse(l)}async processSSEResponse(t){let s=!1;const r=await new E({onStart:n=>{this.eventEmitter.emit("message:start",n)},onChunk:n=>{this.eventEmitter.emit("message:chunk",n)},onToolCall:n=>{this.eventEmitter.emit("toolCall:received",n),n.type==="form"&&this.eventEmitter.emit("toolCall:form",n)},onClientFunction:async n=>{s=!0,this.eventEmitter.emit("function:invoke",n),await this.handleClientFunctionInvocation(n)},onAnswerComplete:n=>{this.eventEmitter.emit("message:answer-complete",n)},onComplete:n=>{this.eventEmitter.emit("message:complete",n)},onError:n=>{this.eventEmitter.emit("message:error",{error:n.message,code:n instanceof h?n.code:void 0})}}).processStream(t);return this.maybeFlagEmptyReply(r,s),r}maybeFlagEmptyReply(t,s){t.status==="DONE"&&(t.content??"").trim()===""&&!s&&!(t.toolCalls&&t.toolCalls.length>0)&&!(t.followUpReplies&&t.followUpReplies.length>0)&&setTimeout(()=>{if(this.eventEmitter.emit("message:empty",{conversationId:t.conversationId??"",messageId:t.id??""}),this.config.warnOnEmptyReply===!1)return;const r=t.conversationId||"(no conversation)";if(this.warnedEmptyConversations.has(r))return;this.warnedEmptyConversations.add(r);const n=this.config.agent||this.config.defaultAgentId;t.id?console.warn("[AGO] Reply completed with empty content. Possible causes: "+(n?`the agent "${n}" may not exist for this tenant, `:"an unknown `agent` slug, ")+"or the agent replied with no text. Listen for the `message:empty` event to handle this in your app; silence this warning with `warnOnEmptyReply: false`."):console.warn("[AGO] The stream completed without any message data. Possible causes: "+(n?`the agent "${n}" may not exist for this tenant, or `:"")+"`baseUrl` does not point at an AGO endpoint that returns server-sent events. Listen for the `message:empty` event to handle this in your app; silence this warning with `warnOnEmptyReply: false`.")},0)}async handleClientFunctionInvocation(t){let s,r;try{s=await this.functionRegistry.execute(t.functionName,t.arguments)}catch(n){r=n instanceof Error?n.message:"Unknown error",o.error("Client function execution failed:",n)}if(t.invocationId)try{await this.submitToolCallForm(t.invocationId,{result:s,error:r,_type:"client_function_result"})}catch(n){o.error("Failed to submit function result:",n)}this.eventEmitter.emit("function:result",{invocationId:t.invocationId,result:s,error:r})}async getConversations(){return(await this.httpClient.get("/api/sdk/v1/conversations")).items.map(t=>({id:t.id,title:t.title,lastMessageDate:new Date(t.last_message_date)}))}async getConversation(t){const s=await this.httpClient.get(`/api/sdk/v1/conversations/${t}`),r={id:s.id,title:s.title,lastMessageDate:new Date(s.last_message_date),messages:s.messages.map(n=>({id:n.id,conversationId:s.id,content:n.content,role:n.role,status:n.status,createdAt:new Date(n.created_at),toolCalls:S.mapPersistedToolCalls(n.tool_call_data)}))};return this.eventEmitter.emit("conversation:loaded",r),r}static mapPersistedToolCalls(t){if(!(!t||t.length===0))return t.map(s=>({id:String(s.id??""),type:s.type??"status_message",status:String(s.status??"unknown"),toolName:s.tool_name??"",toolDisplayName:s.tool_display_name,message:s.message,formSchema:s.form_schema,data:s.data,functionName:s.function_name,arguments:s.arguments}))}async getMessages(t){return(await this.getConversation(t)).messages||[]}async submitToolCallForm(t,s){await this.httpClient.post(`/api/sdk/v1/tool-calls/${t}/submit`,{formData:s})}async confirmToolCall(t){await this.httpClient.post(`/api/tool-calls/${t}/confirm/`)}async rejectToolCall(t){await this.httpClient.post(`/api/tool-calls/${t}/reject/`)}async getFormCollector(t){const s=await this.httpClient.get(`/api/sdk/v1/forms/${encodeURIComponent(t)}`);return{name:s.name,description:s.description,schema:s.schema,submit:s.submit??void 0}}async submitFormCollector(t,s){return this.httpClient.post("/api/sdk/v1/forms/submit",{name:t,values:s})}async submitFeedback(t,s){await this.httpClient.post(`/api/sdk/v1/messages/${t}/feedback`,{rating:s})}registerFunction(t,s,r){typeof t=="object"?this.functionRegistry.register(t):this.functionRegistry.register(t,s,r)}register(t){if(Array.isArray(t))for(const s of t)this.functionRegistry.register(s);else this.functionRegistry.register(t)}unregisterFunction(t){return this.functionRegistry.unregister(t)}getRegisteredFunctions(){return this.functionRegistry.getSchemas()}registerNavigationFunction(t,s){const r=s.map(i=>i.name),n=s.map(i=>`- "${i.name}": ${i.description}`).join(`
5
- `);this.registerFunction("navigateToPage",async i=>{const a=i.page,l=s.find(c=>c.name===a);return l?(t(l.path),{success:!0,navigatedTo:l.path}):{success:!1,error:`Unknown page: ${a}`}},{description:`Navigate the user to a page in the application. Available pages:
6
- ${n}`,parameters:{type:"object",properties:{page:{type:"string",description:"The page to navigate to",enum:r}},required:["page"]}})}setContext(t,s){this.contextRegistry.set(t,s),this.notifyContextChanged()}removeContext(t){const s=this.contextRegistry.remove(t);return s&&this.notifyContextChanged(),s}addDynamicContext(t,s){this.contextRegistry.addDynamicProvider(t,s),this.notifyContextChanged()}removeDynamicContext(t){const s=this.contextRegistry.removeDynamicProvider(t);return s&&this.notifyContextChanged(),s}notifyContextChanged(){this.eventEmitter.emit("context:changed",this.contextRegistry.getSnapshot())}enableAutoPageContext(){this.addDynamicContext("browser-page",()=>{const t=typeof window<"u"?window.location.href:void 0,s=typeof document<"u"?document.title:void 0;return!t&&!s?null:{name:"Browser page",description:"Current page the user is viewing",data:{url:t,title:s}}})}getContextSnapshot(){return this.contextRegistry.getSnapshot()}on(t,s){this.eventEmitter.on(t,s)}off(t,s){this.eventEmitter.off(t,s)}once(t,s){this.eventEmitter.once(t,s)}waitFor(t,s){return this.eventEmitter.waitFor(t,s)}updateConfig(t){const s={};for(const[n,i]of Object.entries(t))i!==void 0&&(s[n]=i);const r={...this.config,...s};f(r,"AgoClient.updateConfig"),this.config=r,this.httpClient.updateConfig(s),s.debug!==void 0&&(s.debug?o.enable():o.disable())}destroy(){this.eventEmitter.removeAllListeners(),this.functionRegistry.clear(),this.contextRegistry.clear(),o.log("AgoClient destroyed")}};Object.defineProperty(exports,"AgoApiError",{enumerable:!0,get:function(){return u}});Object.defineProperty(exports,"AgoClient",{enumerable:!0,get:function(){return U}});Object.defineProperty(exports,"AgoError",{enumerable:!0,get:function(){return h}});Object.defineProperty(exports,"AgoFunctionError",{enumerable:!0,get:function(){return m}});Object.defineProperty(exports,"AgoNetworkError",{enumerable:!0,get:function(){return d}});Object.defineProperty(exports,"AgoStreamError",{enumerable:!0,get:function(){return g}});Object.defineProperty(exports,"ClientContextRegistry",{enumerable:!0,get:function(){return C}});Object.defineProperty(exports,"EventEmitter",{enumerable:!0,get:function(){return _}});Object.defineProperty(exports,"FunctionRegistry",{enumerable:!0,get:function(){return b}});Object.defineProperty(exports,"SSEHandler",{enumerable:!0,get:function(){return E}});Object.defineProperty(exports,"isStreamNetworkError",{enumerable:!0,get:function(){return R}});Object.defineProperty(exports,"logger",{enumerable:!0,get:function(){return o}});Object.defineProperty(exports,"validateConfig",{enumerable:!0,get:function(){return f}});