@runtypelabs/persona 4.2.1 → 4.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +22 -6
  2. package/dist/animations/glyph-cycle.d.cts +1 -1
  3. package/dist/animations/glyph-cycle.d.ts +1 -1
  4. package/dist/animations/{types-B_xbfvR0.d.cts → types-C6tFDxKy.d.cts} +1 -1
  5. package/dist/animations/{types-B_xbfvR0.d.ts → types-C6tFDxKy.d.ts} +1 -1
  6. package/dist/animations/wipe.d.cts +1 -1
  7. package/dist/animations/wipe.d.ts +1 -1
  8. package/dist/codegen.cjs +6 -6
  9. package/dist/codegen.js +9 -9
  10. package/dist/index.cjs +32 -32
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +101 -3
  13. package/dist/index.d.ts +101 -3
  14. package/dist/index.global.js +23 -23
  15. package/dist/index.global.js.map +1 -1
  16. package/dist/index.js +32 -32
  17. package/dist/index.js.map +1 -1
  18. package/dist/install.global.js +1 -1
  19. package/dist/install.global.js.map +1 -1
  20. package/dist/launcher.global.js.map +1 -1
  21. package/dist/smart-dom-reader.d.cts +76 -1
  22. package/dist/smart-dom-reader.d.ts +76 -1
  23. package/dist/theme-editor-preview.cjs +27 -27
  24. package/dist/theme-editor-preview.d.cts +76 -1
  25. package/dist/theme-editor-preview.d.ts +76 -1
  26. package/dist/theme-editor-preview.js +29 -29
  27. package/dist/theme-editor.cjs +1 -1
  28. package/dist/theme-editor.d.cts +76 -1
  29. package/dist/theme-editor.d.ts +76 -1
  30. package/dist/theme-editor.js +1 -1
  31. package/dist/widget.css +3 -0
  32. package/package.json +1 -1
  33. package/src/client.test.ts +221 -29
  34. package/src/client.ts +71 -24
  35. package/src/defaults.ts +2 -0
  36. package/src/index-core.ts +2 -0
  37. package/src/install.ts +9 -1
  38. package/src/session.ts +6 -3
  39. package/src/session.voice.test.ts +65 -0
  40. package/src/styles/widget.css +3 -0
  41. package/src/types.ts +57 -2
  42. package/src/utils/__fixtures__/unified-translator.oracle.ts +3 -3
  43. package/src/utils/code-generators.ts +10 -0
  44. package/src/utils/target.test.ts +51 -0
  45. package/src/utils/target.ts +90 -0
package/README.md CHANGED
@@ -114,6 +114,9 @@ With **`dock.reveal: 'resize'`** (default), a **closed** dock uses a **`0px`** c
114
114
 
115
115
  The full reference lives in [`docs/`](./docs/) and the theming guide:
116
116
 
117
+ - [Extending Persona](./docs/EXTENDING.md): the map of every extension point: plugins, components, postprocessors, themes, stream parsers, animations, voice, sanitization, actions, context/WebMCP, layout slots, storage, and UI builders, each linked to its deep dive
118
+ - [Authoring Plugins](./docs/PLUGINS.md): the `AgentWidgetPlugin` contract, all 14 render hooks, global vs per-instance registration, lifecycle, and the `@runtypelabs/persona/plugin-kit` helpers
119
+ - [Contributing](../../CONTRIBUTING.md): current guidance for contributing plugins, themes, adapters, examples, and other customizations back to this monorepo
117
120
  - [Programmatic Control & Events](./docs/PROGRAMMATIC-CONTROL.md): controller API, message hooks and injection, enriched DOM context, WebMCP page tools, DOM and controller events, state loading
118
121
  - [UI Features & Components](./docs/UI-COMPONENTS.md): message actions and feedback, loading/idle indicators, approvals, built-in `ask_user_question` and `suggest_replies` tools, dropdown menus, button utilities, dynamic forms
119
122
  - [Script Tag Installation & Framework Integration](./docs/INSTALLATION-FRAMEWORKS.md): automatic installer, deferred launcher lifecycle hooks, manual script tag setup, React, Next.js, Remix, Gatsby, and Astro guides
@@ -126,9 +129,22 @@ The full reference lives in [`docs/`](./docs/) and the theming guide:
126
129
 
127
130
  ### Optional Runtype proxy server
128
131
 
129
- The `@runtypelabs/persona-proxy` package handles flow configuration and forwards requests to Runtype. You can configure it in three ways:
132
+ The `@runtypelabs/persona-proxy` package handles server-side API-key control and forwards requests to Runtype. You can configure it around a saved agent (recommended for most chat widgets) or a flow.
130
133
 
131
- **Option 1: Use default flow (recommended for getting started)**
134
+ **Option 1: Reference a Runtype agent ID (recommended)**
135
+
136
+ ```ts
137
+ // api/chat.ts
138
+ import { createChatProxyApp } from '@runtypelabs/persona-proxy';
139
+
140
+ export default createChatProxyApp({
141
+ path: '/api/chat/dispatch',
142
+ allowedOrigins: ['https://www.example.com'],
143
+ agentId: 'agent_abc123'
144
+ });
145
+ ```
146
+
147
+ **Option 2: Use default flow**
132
148
 
133
149
  ```ts
134
150
  // api/chat.ts
@@ -140,7 +156,7 @@ export default createChatProxyApp({
140
156
  });
141
157
  ```
142
158
 
143
- **Option 2: Reference a Runtype flow ID**
159
+ **Option 3: Reference a Runtype flow ID**
144
160
 
145
161
  ```ts
146
162
  import { createChatProxyApp } from '@runtypelabs/persona-proxy';
@@ -152,7 +168,7 @@ export default createChatProxyApp({
152
168
  });
153
169
  ```
154
170
 
155
- **Option 3: Define a custom flow**
171
+ **Option 4: Define a custom flow**
156
172
 
157
173
  ```ts
158
174
  import { createChatProxyApp } from '@runtypelabs/persona-proxy';
@@ -200,9 +216,9 @@ Add `RUNTYPE_API_KEY` to your environment. The proxy constructs the Runtype payl
200
216
 
201
217
  ### Development notes
202
218
 
203
- - The widget streams results using SSE and mirrors Persona's unified flow/agent events (which Runtype implements natively), including `await` local-tool pauses and `/resume` continuations.
219
+ - The widget streams results using SSE and mirrors Persona's flow/agent events (which Runtype implements natively), including `await` local-tool pauses and `/resume` continuations.
204
220
  - Tailwind classes are prefixed with `tvw-` and scoped to `[data-persona-root]`, so they won't collide with the host page.
205
- - Run `pnpm dev` from the repository root to boot the example Runtype proxy (`examples/vercel-edge`) and the vanilla demo (`apps/web`).
221
+ - Run `pnpm dev` from the repository root to boot the example Runtype proxy (`examples/runtype-hono-proxy`) and the vanilla demo (`apps/web`).
206
222
  - The proxy prefers port `43111` but automatically selects the next free port if needed.
207
223
  - `features.askUserQuestion.expose` and `features.suggestReplies.expose` advertise built-in LOCAL client tools through `clientTools[]`; leave `expose` off if the flow already declares those tools server-side.
208
224
  - `webmcp: { enabled: true }` snapshots page-registered tools on `document.modelContext`, sends them as `clientTools[]`, executes returned `webmcp:*` calls in the browser, and resumes the paused execution.
@@ -1,4 +1,4 @@
1
- import { S as StreamAnimationPlugin } from './types-B_xbfvR0.cjs';
1
+ import { S as StreamAnimationPlugin } from './types-C6tFDxKy.cjs';
2
2
 
3
3
  declare const glyphCycle: StreamAnimationPlugin;
4
4
 
@@ -1,4 +1,4 @@
1
- import { S as StreamAnimationPlugin } from './types-B_xbfvR0.js';
1
+ import { S as StreamAnimationPlugin } from './types-C6tFDxKy.js';
2
2
 
3
3
  declare const glyphCycle: StreamAnimationPlugin;
4
4
 
@@ -829,7 +829,7 @@ type AgentWidgetReasoning = {
829
829
  status: "pending" | "streaming" | "complete";
830
830
  chunks: string[];
831
831
  /**
832
- * Reasoning channel scope (unified spec). `"turn"` is ordinary per-turn
832
+ * Reasoning channel scope (wire spec). `"turn"` is ordinary per-turn
833
833
  * thinking; `"loop"` is a cross-iteration agent reflection (the fold that
834
834
  * replaced the legacy `agent_reflection` event). Absent for legacy streams.
835
835
  */
@@ -829,7 +829,7 @@ type AgentWidgetReasoning = {
829
829
  status: "pending" | "streaming" | "complete";
830
830
  chunks: string[];
831
831
  /**
832
- * Reasoning channel scope (unified spec). `"turn"` is ordinary per-turn
832
+ * Reasoning channel scope (wire spec). `"turn"` is ordinary per-turn
833
833
  * thinking; `"loop"` is a cross-iteration agent reflection (the fold that
834
834
  * replaced the legacy `agent_reflection` event). Absent for legacy streams.
835
835
  */
@@ -1,4 +1,4 @@
1
- import { S as StreamAnimationPlugin } from './types-B_xbfvR0.cjs';
1
+ import { S as StreamAnimationPlugin } from './types-C6tFDxKy.cjs';
2
2
 
3
3
  declare const wipe: StreamAnimationPlugin;
4
4
 
@@ -1,4 +1,4 @@
1
- import { S as StreamAnimationPlugin } from './types-B_xbfvR0.js';
1
+ import { S as StreamAnimationPlugin } from './types-C6tFDxKy.js';
2
2
 
3
3
  declare const wipe: StreamAnimationPlugin;
4
4
 
package/dist/codegen.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var $=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var R=Object.prototype.hasOwnProperty;var I=(e,r)=>{for(var n in r)$(e,n,{get:r[n],enumerable:!0})},W=(e,r,n,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of M(r))!R.call(e,o)&&o!==n&&$(e,o,{get:()=>r[o],enumerable:!(s=T(r,o))||s.enumerable});return e};var H=e=>W($({},"__esModule",{value:!0}),e);var B={};I(B,{generateCodeSnippet:()=>v});module.exports=H(B);var x="4.2.1";var c=x;function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function k(e){if(e)return{getHeaders:u(e.getHeaders),onFeedback:u(e.onFeedback),onCopy:u(e.onCopy),requestMiddleware:u(e.requestMiddleware),actionHandlers:u(e.actionHandlers),actionParsers:u(e.actionParsers),postprocessMessage:u(e.postprocessMessage),contextProviders:u(e.contextProviders),streamParser:u(e.streamParser)}}var A=`({ text, message }: any) => {
1
+ "use strict";var $=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var M=Object.prototype.hasOwnProperty;var R=(e,r)=>{for(var n in r)$(e,n,{get:r[n],enumerable:!0})},W=(e,r,n,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of T(r))!M.call(e,o)&&o!==n&&$(e,o,{get:()=>r[o],enumerable:!(s=_(r,o))||s.enumerable});return e};var H=e=>W($({},"__esModule",{value:!0}),e);var B={};R(B,{generateCodeSnippet:()=>v});module.exports=H(B);var x="4.3.1";var c=x;function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function k(e){if(e)return{getHeaders:u(e.getHeaders),onFeedback:u(e.onFeedback),onCopy:u(e.onCopy),requestMiddleware:u(e.requestMiddleware),actionHandlers:u(e.actionHandlers),actionParsers:u(e.actionParsers),postprocessMessage:u(e.postprocessMessage),contextProviders:u(e.contextProviders),streamParser:u(e.streamParser)}}var A=`({ text, message }: any) => {
2
2
  const jsonSource = (message as any).rawContent || text || message.content;
3
3
  if (!jsonSource || typeof jsonSource !== 'string') return null;
4
4
  let cleanJson = jsonSource
@@ -70,11 +70,11 @@
70
70
  if (parsed.action === 'message') return parsed.text || '';
71
71
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
72
72
  return parsed.text || null;
73
- }`;function J(e){if(!e)return null;let r=e.toString();return r.includes("createJsonStreamParser")||r.includes("partial-json")?"json":r.includes("createRegexJsonParser")||r.includes("regex")?"regex-json":r.includes("createXmlParser")||r.includes("<text>")?"xml":null}function h(e){var r,n;return(n=(r=e.parserType)!=null?r:J(e.streamParser))!=null?n:"plain"}function m(e,r){let n=[];return e.toolCall&&(n.push(`${r}toolCall: {`),Object.entries(e.toolCall).forEach(([s,o])=>{typeof o=="string"&&n.push(`${r} ${s}: "${o}",`)}),n.push(`${r}},`)),n}function f(e,r,n){let s=[],o=e.messageActions&&Object.entries(e.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),t=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(o||t)&&(s.push(`${r}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?s.push(`${r} ${i}: "${a}",`):typeof a=="boolean"&&s.push(`${r} ${i}: ${a},`))}),n!=null&&n.onFeedback&&s.push(`${r} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&s.push(`${r} onCopy: ${n.onCopy},`),s.push(`${r}},`)),s}function y(e,r){let n=[];if(e.markdown){let s=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(s||o)&&(n.push(`${r}markdown: {`),s&&(n.push(`${r} options: {`),Object.entries(e.markdown.options).forEach(([t,i])=>{typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`)}),n.push(`${r} },`)),o&&n.push(`${r} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${r}},`))}return n}function C(e,r){let n=[];if(e.layout){let s=e.layout.header&&Object.keys(e.layout.header).some(t=>t!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(t=>t!=="renderUserMessage"&&t!=="renderAssistantMessage");(s||o)&&(n.push(`${r}layout: {`),s&&(n.push(`${r} header: {`),Object.entries(e.layout.header).forEach(([t,i])=>{t!=="render"&&(typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`))}),n.push(`${r} },`)),o&&(n.push(`${r} messages: {`),Object.entries(e.layout.messages).forEach(([t,i])=>{t==="renderUserMessage"||t==="renderAssistantMessage"||(t==="avatar"&&typeof i=="object"&&i!==null?(n.push(`${r} avatar: {`),Object.entries(i).forEach(([a,p])=>{typeof p=="string"?n.push(`${r} ${a}: "${p}",`):typeof p=="boolean"&&n.push(`${r} ${a}: ${p},`)}),n.push(`${r} },`)):t==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([p])=>p!=="format")&&(n.push(`${r} timestamp: {`),Object.entries(i).forEach(([p,d])=>{p!=="format"&&(typeof d=="string"?n.push(`${r} ${p}: "${d}",`):typeof d=="boolean"&&n.push(`${r} ${p}: ${d},`))}),n.push(`${r} },`)):typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`))}),n.push(`${r} },`)),n.push(`${r}},`))}return n}function w(e,r){let n=[];return e&&(e.getHeaders&&n.push(`${r}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${r}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${r}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${r}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${r}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${r}streamParser: ${e.streamParser},`)),n}function P(e,r,n){Object.entries(r).forEach(([s,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${n}${s}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${n}${s}: {`),P(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${s}: ${JSON.stringify(o)},`)}})}function l(e,r,n,s){n&&(e.push(`${s}${r}: {`),P(e,n,`${s} `),e.push(`${s}},`))}function g(e){var r;return((r=e==null?void 0:e.target)!=null?r:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function v(e,r="esm",n){let s={...e};delete s.postprocessMessage,delete s.initialMessages;let o=n?{...n,hooks:k(n.hooks)}:void 0;return r==="esm"?q(s,o):r==="script-installer"?G(s,o):r==="script-advanced"?U(s,o):r==="react-component"?L(s,o):r==="react-advanced"?K(s,o):Y(s,o)}function q(e,r){let n=r==null?void 0:r.hooks,s=h(e),o=s!=="plain",t=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${g(r)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),o&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&l(t,"theme",e.theme," "),e.launcher&&l(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{t.push(` ${i}: "${a}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"?t.push(` ${i}: ${a},`):typeof a=="number"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{t.push(` ${i}: ${a},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...w(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
74
- `)}function L(e,r){let n=r==null?void 0:r.hooks,s=h(e),o=s!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${g(r)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),o&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&l(t,"theme",e.theme," "),e.launcher&&l(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{t.push(` ${i}: "${a}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"?t.push(` ${i}: ${a},`):typeof a=="number"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{t.push(` ${i}: ${a},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...w(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
75
- `)}function K(e,r){let n=r==null?void 0:r.hooks,s=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${g(r)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&l(s,"theme",e.theme," "),e.launcher&&l(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([o,t])=>{s.push(` ${o}: "${t}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"?s.push(` ${o}: ${t},`):typeof t=="number"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([o,t])=>{s.push(` ${o}: ${t},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{s.push(` "${o}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...m(e," ")),s.push(...f(e," ",n)),s.push(...y(e," ")),s.push(...C(e," ")),n!=null&&n.getHeaders&&s.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&s.push(` contextProviders: ${n.contextProviders},`),e.debug&&s.push(` debug: ${e.debug},`),s.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?s.push(` streamParser: ${n.streamParser},`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(` streamParser: () => createFlexibleJsonStreamParser(${D}),`)),n!=null&&n.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),s.push(" // Built-in parser for markdown-wrapped JSON"),s.push(` ${A}`),s.push(" ],")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" actionParsers: ["),s.push(" defaultJsonActionParser,"),s.push(" // Parser for markdown-wrapped JSON"),s.push(` ${A}`),s.push(" ],")),n!=null&&n.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` actionHandlers: [...(${n.actionHandlers}),`),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Built-in handler for nav_then_click action"),s.push(` ${O}`),s.push(" ],")):(s.push(" // Action handlers for navigation and other actions"),s.push(" actionHandlers: ["),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Handler for nav_then_click action"),s.push(` ${O}`),s.push(" ],")),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage},`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" requestMiddleware: ({ payload, config }) => {"),s.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),s.push(" const merged = customResult || payload;"),s.push(" return {"),s.push(" ...merged,"),s.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),s.push(" };"),s.push(" }")):(s.push(" requestMiddleware: ({ payload }) => {"),s.push(" return {"),s.push(" ...payload,"),s.push(" metadata: collectDOMContext()"),s.push(" };"),s.push(" }")),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Save state on message events"),s.push(" const handleMessage = () => {"),s.push(" const session = handle?.getSession?.();"),s.push(" if (session) {"),s.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),s.push(" messages: session.messages,"),s.push(" timestamp: new Date().toISOString()"),s.push(" }));"),s.push(" }"),s.push(" };"),s.push(""),s.push(" // Clear state on clear chat"),s.push(" const handleClearChat = () => {"),s.push(" localStorage.removeItem(STORAGE_KEY);"),s.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),s.push(" };"),s.push(""),s.push(" window.addEventListener('persona:message', handleMessage);"),s.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" window.removeEventListener('persona:message', handleMessage);"),s.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage: Collects DOM context for AI-powered navigation"),s.push("// Features:"),s.push("// - Extracts page elements (products, buttons, links)"),s.push("// - Persists chat history across page loads"),s.push("// - Handles navigation actions (nav_then_click)"),s.push("// - Processes structured JSON actions from AI"),s.push("//"),s.push("// Example usage in Next.js:"),s.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),s.push("//"),s.push("// export default function RootLayout({ children }) {"),s.push("// return ("),s.push('// <html lang="en">'),s.push("// <body>"),s.push("// {children}"),s.push("// <ChatWidgetAdvanced />"),s.push("// </body>"),s.push("// </html>"),s.push("// );"),s.push("// }"),s.join(`
76
- `)}function _(e){var o;let r=h(e),n=r!=="plain",s={};if(e.apiUrl&&(s.apiUrl=e.apiUrl),e.clientToken&&(s.clientToken=e.clientToken),e.flowId&&(s.flowId=e.flowId),n&&(s.parserType=r),e.theme&&(s.theme=e.theme),e.launcher&&(s.launcher=e.launcher),e.copy&&(s.copy=e.copy),e.sendButton&&(s.sendButton=e.sendButton),e.voiceRecognition&&(s.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(s.statusIndicator=e.statusIndicator),e.features&&(s.features=e.features),((o=e.suggestionChips)==null?void 0:o.length)>0&&(s.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(s.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(s.debug=e.debug),e.toolCall){let t={};Object.entries(e.toolCall).forEach(([i,a])=>{typeof a=="string"&&(t[i]=a)}),Object.keys(t).length>0&&(s.toolCall=t)}if(e.messageActions){let t={};Object.entries(e.messageActions).forEach(([i,a])=>{i!=="onFeedback"&&i!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(t[i]=a)}),Object.keys(t).length>0&&(s.messageActions=t)}if(e.markdown){let t={};e.markdown.options&&(t.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(t.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(t).length>0&&(s.markdown=t)}if(e.layout){let t={};if(e.layout.header){let i={};Object.entries(e.layout.header).forEach(([a,p])=>{a!=="render"&&(typeof p=="string"||typeof p=="boolean")&&(i[a]=p)}),Object.keys(i).length>0&&(t.header=i)}if(e.layout.messages){let i={};Object.entries(e.layout.messages).forEach(([a,p])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof p=="object"&&p!==null)i.avatar=p;else if(a==="timestamp"&&typeof p=="object"&&p!==null){let d={};Object.entries(p).forEach(([S,b])=>{S!=="format"&&(typeof b=="string"||typeof b=="boolean")&&(d[S]=b)}),Object.keys(d).length>0&&(i.timestamp=d)}else(typeof p=="string"||typeof p=="boolean")&&(i[a]=p)}),Object.keys(i).length>0&&(t.messages=i)}Object.keys(t).length>0&&(s.layout=t)}return s}function G(e,r){let n=_(e),o=!!(r!=null&&r.windowKey||r!=null&&r.target)?{config:n,...r!=null&&r.windowKey?{windowKey:r.windowKey}:{},...r!=null&&r.target?{target:r.target}:{}}:n,t=JSON.stringify(o,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/install.global.js" data-config='${t}'></script>`}function Y(e,r){let n=r==null?void 0:r.hooks,s=h(e),o=s!=="plain",t=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${g(r)}',`,...r!=null&&r.windowKey?[` windowKey: '${r.windowKey}',`]:[]," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),o&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&l(t,"theme",e.theme," "),e.launcher&&l(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{t.push(` ${i}: "${a}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"?t.push(` ${i}: ${a},`):typeof a=="number"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{t.push(` ${i}: ${a},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...w(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push("</script>"),t.join(`
77
- `)}function U(e,r){let n=r==null?void 0:r.hooks,s=_(e),t=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(s,null,2).split(`
73
+ }`;function J(e){if(!e)return null;let r=e.toString();return r.includes("createJsonStreamParser")||r.includes("partial-json")?"json":r.includes("createRegexJsonParser")||r.includes("regex")?"regex-json":r.includes("createXmlParser")||r.includes("<text>")?"xml":null}function h(e){var r,n;return(n=(r=e.parserType)!=null?r:J(e.streamParser))!=null?n:"plain"}function m(e,r){let n=[];return e.toolCall&&(n.push(`${r}toolCall: {`),Object.entries(e.toolCall).forEach(([s,o])=>{typeof o=="string"&&n.push(`${r} ${s}: "${o}",`)}),n.push(`${r}},`)),n}function f(e,r,n){let s=[],o=e.messageActions&&Object.entries(e.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),t=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(o||t)&&(s.push(`${r}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?s.push(`${r} ${i}: "${a}",`):typeof a=="boolean"&&s.push(`${r} ${i}: ${a},`))}),n!=null&&n.onFeedback&&s.push(`${r} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&s.push(`${r} onCopy: ${n.onCopy},`),s.push(`${r}},`)),s}function y(e,r){let n=[];if(e.markdown){let s=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(s||o)&&(n.push(`${r}markdown: {`),s&&(n.push(`${r} options: {`),Object.entries(e.markdown.options).forEach(([t,i])=>{typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`)}),n.push(`${r} },`)),o&&n.push(`${r} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${r}},`))}return n}function C(e,r){let n=[];if(e.layout){let s=e.layout.header&&Object.keys(e.layout.header).some(t=>t!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(t=>t!=="renderUserMessage"&&t!=="renderAssistantMessage");(s||o)&&(n.push(`${r}layout: {`),s&&(n.push(`${r} header: {`),Object.entries(e.layout.header).forEach(([t,i])=>{t!=="render"&&(typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`))}),n.push(`${r} },`)),o&&(n.push(`${r} messages: {`),Object.entries(e.layout.messages).forEach(([t,i])=>{t==="renderUserMessage"||t==="renderAssistantMessage"||(t==="avatar"&&typeof i=="object"&&i!==null?(n.push(`${r} avatar: {`),Object.entries(i).forEach(([a,p])=>{typeof p=="string"?n.push(`${r} ${a}: "${p}",`):typeof p=="boolean"&&n.push(`${r} ${a}: ${p},`)}),n.push(`${r} },`)):t==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([p])=>p!=="format")&&(n.push(`${r} timestamp: {`),Object.entries(i).forEach(([p,d])=>{p!=="format"&&(typeof d=="string"?n.push(`${r} ${p}: "${d}",`):typeof d=="boolean"&&n.push(`${r} ${p}: ${d},`))}),n.push(`${r} },`)):typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`))}),n.push(`${r} },`)),n.push(`${r}},`))}return n}function w(e,r){let n=[];return e&&(e.getHeaders&&n.push(`${r}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${r}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${r}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${r}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${r}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${r}streamParser: ${e.streamParser},`)),n}function P(e,r,n){Object.entries(r).forEach(([s,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${n}${s}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${n}${s}: {`),P(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${s}: ${JSON.stringify(o)},`)}})}function l(e,r,n,s){n&&(e.push(`${s}${r}: {`),P(e,n,`${s} `),e.push(`${s}},`))}function g(e){var r;return((r=e==null?void 0:e.target)!=null?r:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function v(e,r="esm",n){let s={...e};delete s.postprocessMessage,delete s.initialMessages;let o=n?{...n,hooks:k(n.hooks)}:void 0;return r==="esm"?q(s,o):r==="script-installer"?G(s,o):r==="script-advanced"?U(s,o):r==="react-component"?L(s,o):r==="react-advanced"?K(s,o):Y(s,o)}function q(e,r){let n=r==null?void 0:r.hooks,s=h(e),o=s!=="plain",t=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${g(r)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),o&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&l(t,"theme",e.theme," "),e.launcher&&l(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{t.push(` ${i}: "${a}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"?t.push(` ${i}: ${a},`):typeof a=="number"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{t.push(` ${i}: ${a},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...w(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
74
+ `)}function L(e,r){let n=r==null?void 0:r.hooks,s=h(e),o=s!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${g(r)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),o&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&l(t,"theme",e.theme," "),e.launcher&&l(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{t.push(` ${i}: "${a}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"?t.push(` ${i}: ${a},`):typeof a=="number"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{t.push(` ${i}: ${a},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...w(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
75
+ `)}function K(e,r){let n=r==null?void 0:r.hooks,s=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${g(r)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&l(s,"theme",e.theme," "),e.launcher&&l(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([o,t])=>{s.push(` ${o}: "${t}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"?s.push(` ${o}: ${t},`):typeof t=="number"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([o,t])=>{s.push(` ${o}: ${t},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{s.push(` "${o}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...m(e," ")),s.push(...f(e," ",n)),s.push(...y(e," ")),s.push(...C(e," ")),n!=null&&n.getHeaders&&s.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&s.push(` contextProviders: ${n.contextProviders},`),e.debug&&s.push(` debug: ${e.debug},`),s.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?s.push(` streamParser: ${n.streamParser},`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(` streamParser: () => createFlexibleJsonStreamParser(${D}),`)),n!=null&&n.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),s.push(" // Built-in parser for markdown-wrapped JSON"),s.push(` ${A}`),s.push(" ],")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" actionParsers: ["),s.push(" defaultJsonActionParser,"),s.push(" // Parser for markdown-wrapped JSON"),s.push(` ${A}`),s.push(" ],")),n!=null&&n.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` actionHandlers: [...(${n.actionHandlers}),`),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Built-in handler for nav_then_click action"),s.push(` ${O}`),s.push(" ],")):(s.push(" // Action handlers for navigation and other actions"),s.push(" actionHandlers: ["),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Handler for nav_then_click action"),s.push(` ${O}`),s.push(" ],")),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage},`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" requestMiddleware: ({ payload, config }) => {"),s.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),s.push(" const merged = customResult || payload;"),s.push(" return {"),s.push(" ...merged,"),s.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),s.push(" };"),s.push(" }")):(s.push(" requestMiddleware: ({ payload }) => {"),s.push(" return {"),s.push(" ...payload,"),s.push(" metadata: collectDOMContext()"),s.push(" };"),s.push(" }")),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Save state on message events"),s.push(" const handleMessage = () => {"),s.push(" const session = handle?.getSession?.();"),s.push(" if (session) {"),s.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),s.push(" messages: session.messages,"),s.push(" timestamp: new Date().toISOString()"),s.push(" }));"),s.push(" }"),s.push(" };"),s.push(""),s.push(" // Clear state on clear chat"),s.push(" const handleClearChat = () => {"),s.push(" localStorage.removeItem(STORAGE_KEY);"),s.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),s.push(" };"),s.push(""),s.push(" window.addEventListener('persona:message', handleMessage);"),s.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" window.removeEventListener('persona:message', handleMessage);"),s.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage: Collects DOM context for AI-powered navigation"),s.push("// Features:"),s.push("// - Extracts page elements (products, buttons, links)"),s.push("// - Persists chat history across page loads"),s.push("// - Handles navigation actions (nav_then_click)"),s.push("// - Processes structured JSON actions from AI"),s.push("//"),s.push("// Example usage in Next.js:"),s.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),s.push("//"),s.push("// export default function RootLayout({ children }) {"),s.push("// return ("),s.push('// <html lang="en">'),s.push("// <body>"),s.push("// {children}"),s.push("// <ChatWidgetAdvanced />"),s.push("// </body>"),s.push("// </html>"),s.push("// );"),s.push("// }"),s.join(`
76
+ `)}function I(e){var o;let r=h(e),n=r!=="plain",s={};if(e.apiUrl&&(s.apiUrl=e.apiUrl),e.clientToken&&(s.clientToken=e.clientToken),e.agentId&&(s.agentId=e.agentId),e.target&&(s.target=e.target),e.flowId&&(s.flowId=e.flowId),n&&(s.parserType=r),e.theme&&(s.theme=e.theme),e.launcher&&(s.launcher=e.launcher),e.copy&&(s.copy=e.copy),e.sendButton&&(s.sendButton=e.sendButton),e.voiceRecognition&&(s.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(s.statusIndicator=e.statusIndicator),e.features&&(s.features=e.features),((o=e.suggestionChips)==null?void 0:o.length)>0&&(s.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(s.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(s.debug=e.debug),e.toolCall){let t={};Object.entries(e.toolCall).forEach(([i,a])=>{typeof a=="string"&&(t[i]=a)}),Object.keys(t).length>0&&(s.toolCall=t)}if(e.messageActions){let t={};Object.entries(e.messageActions).forEach(([i,a])=>{i!=="onFeedback"&&i!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(t[i]=a)}),Object.keys(t).length>0&&(s.messageActions=t)}if(e.markdown){let t={};e.markdown.options&&(t.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(t.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(t).length>0&&(s.markdown=t)}if(e.layout){let t={};if(e.layout.header){let i={};Object.entries(e.layout.header).forEach(([a,p])=>{a!=="render"&&(typeof p=="string"||typeof p=="boolean")&&(i[a]=p)}),Object.keys(i).length>0&&(t.header=i)}if(e.layout.messages){let i={};Object.entries(e.layout.messages).forEach(([a,p])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof p=="object"&&p!==null)i.avatar=p;else if(a==="timestamp"&&typeof p=="object"&&p!==null){let d={};Object.entries(p).forEach(([S,b])=>{S!=="format"&&(typeof b=="string"||typeof b=="boolean")&&(d[S]=b)}),Object.keys(d).length>0&&(i.timestamp=d)}else(typeof p=="string"||typeof p=="boolean")&&(i[a]=p)}),Object.keys(i).length>0&&(t.messages=i)}Object.keys(t).length>0&&(s.layout=t)}return s}function G(e,r){let n=I(e),o=!!(r!=null&&r.windowKey||r!=null&&r.target)?{config:n,...r!=null&&r.windowKey?{windowKey:r.windowKey}:{},...r!=null&&r.target?{target:r.target}:{}}:n,t=JSON.stringify(o,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/install.global.js" data-config='${t}'></script>`}function Y(e,r){let n=r==null?void 0:r.hooks,s=h(e),o=s!=="plain",t=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${g(r)}',`,...r!=null&&r.windowKey?[` windowKey: '${r.windowKey}',`]:[]," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),o&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&l(t,"theme",e.theme," "),e.launcher&&l(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{t.push(` ${i}: "${a}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"?t.push(` ${i}: ${a},`):typeof a=="number"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{t.push(` ${i}: ${a},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...w(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push("</script>"),t.join(`
77
+ `)}function U(e,r){let n=r==null?void 0:r.hooks,s=I(e),t=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(s,null,2).split(`
78
78
  `).map((i,a)=>a===0?i:" "+i).join(`
79
79
  `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(t.push(` widgetConfig.getHeaders = ${n.getHeaders};`),t.push("")),n!=null&&n.contextProviders&&(t.push(` widgetConfig.contextProviders = ${n.contextProviders};`),t.push("")),n!=null&&n.streamParser?t.push(` widgetConfig.streamParser = ${n.streamParser};`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(" widgetConfig.streamParser = function() {"),t.push(` return agentWidget.createFlexibleJsonStreamParser(${F});`),t.push(" };")),t.push(""),n!=null&&n.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` var customParsers = ${n.actionParsers};`),t.push(" widgetConfig.actionParsers = customParsers.concat(["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${j}`),t.push(" ]);")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" widgetConfig.actionParsers = ["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${j}`),t.push(" ];")),t.push(""),n!=null&&n.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` var customHandlers = ${n.actionHandlers};`),t.push(" widgetConfig.actionHandlers = customHandlers.concat(["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${E}`),t.push(" ]);")):(t.push(" // Action handlers for navigation and other actions"),t.push(" widgetConfig.actionHandlers = ["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${E}`),t.push(" ];")),t.push(""),n!=null&&n.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(` var customResult = (${n.requestMiddleware})(ctx);`),t.push(" var merged = customResult || ctx.payload;"),t.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),t.push(" };")):(t.push(" // Send DOM context with each request"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),t.push(" };")),t.push(""),n!=null&&n.postprocessMessage?t.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(t.push(" // Markdown postprocessor"),t.push(" widgetConfig.postprocessMessage = function(ctx) {"),t.push(" return agentWidget.markdownPostprocessor(ctx.text);"),t.push(" };")),t.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(t.push(" // Message action callbacks"),t.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&t.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&t.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),t.push("")),t.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${g(r)}',`," useShadowDom: false,",...r!=null&&r.windowKey?[` windowKey: '${r.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),t.join(`
80
80
  `)}0&&(module.exports={generateCodeSnippet});
package/dist/codegen.js CHANGED
@@ -1,4 +1,4 @@
1
- var S="4.2.1";var c=S;function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function _(e){if(e)return{getHeaders:u(e.getHeaders),onFeedback:u(e.onFeedback),onCopy:u(e.onCopy),requestMiddleware:u(e.requestMiddleware),actionHandlers:u(e.actionHandlers),actionParsers:u(e.actionParsers),postprocessMessage:u(e.postprocessMessage),contextProviders:u(e.contextProviders),streamParser:u(e.streamParser)}}var x=`({ text, message }: any) => {
1
+ var S="4.3.1";var c=S;function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function I(e){if(e)return{getHeaders:u(e.getHeaders),onFeedback:u(e.onFeedback),onCopy:u(e.onCopy),requestMiddleware:u(e.requestMiddleware),actionHandlers:u(e.actionHandlers),actionParsers:u(e.actionParsers),postprocessMessage:u(e.postprocessMessage),contextProviders:u(e.contextProviders),streamParser:u(e.streamParser)}}var x=`({ text, message }: any) => {
2
2
  const jsonSource = (message as any).rawContent || text || message.content;
3
3
  if (!jsonSource || typeof jsonSource !== 'string') return null;
4
4
  let cleanJson = jsonSource
@@ -58,23 +58,23 @@ var S="4.2.1";var c=S;function u(e){if(e!==void 0)return typeof e=="string"?e:Ar
58
58
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
59
59
  window.location.href = targetUrl;
60
60
  return { handled: true, displayText: text };
61
- }`,T=`(parsed: any) => {
61
+ }`,_=`(parsed: any) => {
62
62
  if (!parsed || typeof parsed !== 'object') return null;
63
63
  if (parsed.action === 'nav_then_click') return 'Navigating...';
64
64
  if (parsed.action === 'message') return parsed.text || '';
65
65
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
66
66
  return parsed.text || null;
67
- }`,M=`function(parsed) {
67
+ }`,T=`function(parsed) {
68
68
  if (!parsed || typeof parsed !== 'object') return null;
69
69
  if (parsed.action === 'nav_then_click') return 'Navigating...';
70
70
  if (parsed.action === 'message') return parsed.text || '';
71
71
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
72
72
  return parsed.text || null;
73
- }`;function R(e){if(!e)return null;let r=e.toString();return r.includes("createJsonStreamParser")||r.includes("partial-json")?"json":r.includes("createRegexJsonParser")||r.includes("regex")?"regex-json":r.includes("createXmlParser")||r.includes("<text>")?"xml":null}function h(e){var r,n;return(n=(r=e.parserType)!=null?r:R(e.streamParser))!=null?n:"plain"}function m(e,r){let n=[];return e.toolCall&&(n.push(`${r}toolCall: {`),Object.entries(e.toolCall).forEach(([s,o])=>{typeof o=="string"&&n.push(`${r} ${s}: "${o}",`)}),n.push(`${r}},`)),n}function f(e,r,n){let s=[],o=e.messageActions&&Object.entries(e.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),t=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(o||t)&&(s.push(`${r}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?s.push(`${r} ${i}: "${a}",`):typeof a=="boolean"&&s.push(`${r} ${i}: ${a},`))}),n!=null&&n.onFeedback&&s.push(`${r} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&s.push(`${r} onCopy: ${n.onCopy},`),s.push(`${r}},`)),s}function y(e,r){let n=[];if(e.markdown){let s=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(s||o)&&(n.push(`${r}markdown: {`),s&&(n.push(`${r} options: {`),Object.entries(e.markdown.options).forEach(([t,i])=>{typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`)}),n.push(`${r} },`)),o&&n.push(`${r} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${r}},`))}return n}function C(e,r){let n=[];if(e.layout){let s=e.layout.header&&Object.keys(e.layout.header).some(t=>t!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(t=>t!=="renderUserMessage"&&t!=="renderAssistantMessage");(s||o)&&(n.push(`${r}layout: {`),s&&(n.push(`${r} header: {`),Object.entries(e.layout.header).forEach(([t,i])=>{t!=="render"&&(typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`))}),n.push(`${r} },`)),o&&(n.push(`${r} messages: {`),Object.entries(e.layout.messages).forEach(([t,i])=>{t==="renderUserMessage"||t==="renderAssistantMessage"||(t==="avatar"&&typeof i=="object"&&i!==null?(n.push(`${r} avatar: {`),Object.entries(i).forEach(([a,p])=>{typeof p=="string"?n.push(`${r} ${a}: "${p}",`):typeof p=="boolean"&&n.push(`${r} ${a}: ${p},`)}),n.push(`${r} },`)):t==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([p])=>p!=="format")&&(n.push(`${r} timestamp: {`),Object.entries(i).forEach(([p,d])=>{p!=="format"&&(typeof d=="string"?n.push(`${r} ${p}: "${d}",`):typeof d=="boolean"&&n.push(`${r} ${p}: ${d},`))}),n.push(`${r} },`)):typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`))}),n.push(`${r} },`)),n.push(`${r}},`))}return n}function $(e,r){let n=[];return e&&(e.getHeaders&&n.push(`${r}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${r}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${r}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${r}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${r}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${r}streamParser: ${e.streamParser},`)),n}function E(e,r,n){Object.entries(r).forEach(([s,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${n}${s}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${n}${s}: {`),E(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${s}: ${JSON.stringify(o)},`)}})}function l(e,r,n,s){n&&(e.push(`${s}${r}: {`),E(e,n,`${s} `),e.push(`${s}},`))}function g(e){var r;return((r=e==null?void 0:e.target)!=null?r:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function I(e,r="esm",n){let s={...e};delete s.postprocessMessage,delete s.initialMessages;let o=n?{...n,hooks:_(n.hooks)}:void 0;return r==="esm"?W(s,o):r==="script-installer"?k(s,o):r==="script-advanced"?F(s,o):r==="react-component"?H(s,o):r==="react-advanced"?N(s,o):D(s,o)}function W(e,r){let n=r==null?void 0:r.hooks,s=h(e),o=s!=="plain",t=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${g(r)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),o&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&l(t,"theme",e.theme," "),e.launcher&&l(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{t.push(` ${i}: "${a}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"?t.push(` ${i}: ${a},`):typeof a=="number"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{t.push(` ${i}: ${a},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...$(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
74
- `)}function H(e,r){let n=r==null?void 0:r.hooks,s=h(e),o=s!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${g(r)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),o&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&l(t,"theme",e.theme," "),e.launcher&&l(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{t.push(` ${i}: "${a}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"?t.push(` ${i}: ${a},`):typeof a=="number"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{t.push(` ${i}: ${a},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...$(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
75
- `)}function N(e,r){let n=r==null?void 0:r.hooks,s=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${g(r)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&l(s,"theme",e.theme," "),e.launcher&&l(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([o,t])=>{s.push(` ${o}: "${t}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"?s.push(` ${o}: ${t},`):typeof t=="number"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([o,t])=>{s.push(` ${o}: ${t},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{s.push(` "${o}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...m(e," ")),s.push(...f(e," ",n)),s.push(...y(e," ")),s.push(...C(e," ")),n!=null&&n.getHeaders&&s.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&s.push(` contextProviders: ${n.contextProviders},`),e.debug&&s.push(` debug: ${e.debug},`),s.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?s.push(` streamParser: ${n.streamParser},`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(` streamParser: () => createFlexibleJsonStreamParser(${T}),`)),n!=null&&n.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),s.push(" // Built-in parser for markdown-wrapped JSON"),s.push(` ${x}`),s.push(" ],")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" actionParsers: ["),s.push(" defaultJsonActionParser,"),s.push(" // Parser for markdown-wrapped JSON"),s.push(` ${x}`),s.push(" ],")),n!=null&&n.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` actionHandlers: [...(${n.actionHandlers}),`),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Built-in handler for nav_then_click action"),s.push(` ${j}`),s.push(" ],")):(s.push(" // Action handlers for navigation and other actions"),s.push(" actionHandlers: ["),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Handler for nav_then_click action"),s.push(` ${j}`),s.push(" ],")),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage},`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" requestMiddleware: ({ payload, config }) => {"),s.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),s.push(" const merged = customResult || payload;"),s.push(" return {"),s.push(" ...merged,"),s.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),s.push(" };"),s.push(" }")):(s.push(" requestMiddleware: ({ payload }) => {"),s.push(" return {"),s.push(" ...payload,"),s.push(" metadata: collectDOMContext()"),s.push(" };"),s.push(" }")),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Save state on message events"),s.push(" const handleMessage = () => {"),s.push(" const session = handle?.getSession?.();"),s.push(" if (session) {"),s.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),s.push(" messages: session.messages,"),s.push(" timestamp: new Date().toISOString()"),s.push(" }));"),s.push(" }"),s.push(" };"),s.push(""),s.push(" // Clear state on clear chat"),s.push(" const handleClearChat = () => {"),s.push(" localStorage.removeItem(STORAGE_KEY);"),s.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),s.push(" };"),s.push(""),s.push(" window.addEventListener('persona:message', handleMessage);"),s.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" window.removeEventListener('persona:message', handleMessage);"),s.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage: Collects DOM context for AI-powered navigation"),s.push("// Features:"),s.push("// - Extracts page elements (products, buttons, links)"),s.push("// - Persists chat history across page loads"),s.push("// - Handles navigation actions (nav_then_click)"),s.push("// - Processes structured JSON actions from AI"),s.push("//"),s.push("// Example usage in Next.js:"),s.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),s.push("//"),s.push("// export default function RootLayout({ children }) {"),s.push("// return ("),s.push('// <html lang="en">'),s.push("// <body>"),s.push("// {children}"),s.push("// <ChatWidgetAdvanced />"),s.push("// </body>"),s.push("// </html>"),s.push("// );"),s.push("// }"),s.join(`
76
- `)}function P(e){var o;let r=h(e),n=r!=="plain",s={};if(e.apiUrl&&(s.apiUrl=e.apiUrl),e.clientToken&&(s.clientToken=e.clientToken),e.flowId&&(s.flowId=e.flowId),n&&(s.parserType=r),e.theme&&(s.theme=e.theme),e.launcher&&(s.launcher=e.launcher),e.copy&&(s.copy=e.copy),e.sendButton&&(s.sendButton=e.sendButton),e.voiceRecognition&&(s.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(s.statusIndicator=e.statusIndicator),e.features&&(s.features=e.features),((o=e.suggestionChips)==null?void 0:o.length)>0&&(s.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(s.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(s.debug=e.debug),e.toolCall){let t={};Object.entries(e.toolCall).forEach(([i,a])=>{typeof a=="string"&&(t[i]=a)}),Object.keys(t).length>0&&(s.toolCall=t)}if(e.messageActions){let t={};Object.entries(e.messageActions).forEach(([i,a])=>{i!=="onFeedback"&&i!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(t[i]=a)}),Object.keys(t).length>0&&(s.messageActions=t)}if(e.markdown){let t={};e.markdown.options&&(t.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(t.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(t).length>0&&(s.markdown=t)}if(e.layout){let t={};if(e.layout.header){let i={};Object.entries(e.layout.header).forEach(([a,p])=>{a!=="render"&&(typeof p=="string"||typeof p=="boolean")&&(i[a]=p)}),Object.keys(i).length>0&&(t.header=i)}if(e.layout.messages){let i={};Object.entries(e.layout.messages).forEach(([a,p])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof p=="object"&&p!==null)i.avatar=p;else if(a==="timestamp"&&typeof p=="object"&&p!==null){let d={};Object.entries(p).forEach(([w,b])=>{w!=="format"&&(typeof b=="string"||typeof b=="boolean")&&(d[w]=b)}),Object.keys(d).length>0&&(i.timestamp=d)}else(typeof p=="string"||typeof p=="boolean")&&(i[a]=p)}),Object.keys(i).length>0&&(t.messages=i)}Object.keys(t).length>0&&(s.layout=t)}return s}function k(e,r){let n=P(e),o=!!(r!=null&&r.windowKey||r!=null&&r.target)?{config:n,...r!=null&&r.windowKey?{windowKey:r.windowKey}:{},...r!=null&&r.target?{target:r.target}:{}}:n,t=JSON.stringify(o,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/install.global.js" data-config='${t}'></script>`}function D(e,r){let n=r==null?void 0:r.hooks,s=h(e),o=s!=="plain",t=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${g(r)}',`,...r!=null&&r.windowKey?[` windowKey: '${r.windowKey}',`]:[]," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),o&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&l(t,"theme",e.theme," "),e.launcher&&l(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{t.push(` ${i}: "${a}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"?t.push(` ${i}: ${a},`):typeof a=="number"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{t.push(` ${i}: ${a},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...$(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push("</script>"),t.join(`
73
+ }`;function M(e){if(!e)return null;let r=e.toString();return r.includes("createJsonStreamParser")||r.includes("partial-json")?"json":r.includes("createRegexJsonParser")||r.includes("regex")?"regex-json":r.includes("createXmlParser")||r.includes("<text>")?"xml":null}function h(e){var r,n;return(n=(r=e.parserType)!=null?r:M(e.streamParser))!=null?n:"plain"}function m(e,r){let n=[];return e.toolCall&&(n.push(`${r}toolCall: {`),Object.entries(e.toolCall).forEach(([s,o])=>{typeof o=="string"&&n.push(`${r} ${s}: "${o}",`)}),n.push(`${r}},`)),n}function f(e,r,n){let s=[],o=e.messageActions&&Object.entries(e.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),t=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(o||t)&&(s.push(`${r}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?s.push(`${r} ${i}: "${a}",`):typeof a=="boolean"&&s.push(`${r} ${i}: ${a},`))}),n!=null&&n.onFeedback&&s.push(`${r} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&s.push(`${r} onCopy: ${n.onCopy},`),s.push(`${r}},`)),s}function y(e,r){let n=[];if(e.markdown){let s=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(s||o)&&(n.push(`${r}markdown: {`),s&&(n.push(`${r} options: {`),Object.entries(e.markdown.options).forEach(([t,i])=>{typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`)}),n.push(`${r} },`)),o&&n.push(`${r} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${r}},`))}return n}function C(e,r){let n=[];if(e.layout){let s=e.layout.header&&Object.keys(e.layout.header).some(t=>t!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(t=>t!=="renderUserMessage"&&t!=="renderAssistantMessage");(s||o)&&(n.push(`${r}layout: {`),s&&(n.push(`${r} header: {`),Object.entries(e.layout.header).forEach(([t,i])=>{t!=="render"&&(typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`))}),n.push(`${r} },`)),o&&(n.push(`${r} messages: {`),Object.entries(e.layout.messages).forEach(([t,i])=>{t==="renderUserMessage"||t==="renderAssistantMessage"||(t==="avatar"&&typeof i=="object"&&i!==null?(n.push(`${r} avatar: {`),Object.entries(i).forEach(([a,p])=>{typeof p=="string"?n.push(`${r} ${a}: "${p}",`):typeof p=="boolean"&&n.push(`${r} ${a}: ${p},`)}),n.push(`${r} },`)):t==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([p])=>p!=="format")&&(n.push(`${r} timestamp: {`),Object.entries(i).forEach(([p,d])=>{p!=="format"&&(typeof d=="string"?n.push(`${r} ${p}: "${d}",`):typeof d=="boolean"&&n.push(`${r} ${p}: ${d},`))}),n.push(`${r} },`)):typeof i=="string"?n.push(`${r} ${t}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${t}: ${i},`))}),n.push(`${r} },`)),n.push(`${r}},`))}return n}function $(e,r){let n=[];return e&&(e.getHeaders&&n.push(`${r}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${r}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${r}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${r}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${r}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${r}streamParser: ${e.streamParser},`)),n}function E(e,r,n){Object.entries(r).forEach(([s,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${n}${s}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${n}${s}: {`),E(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${s}: ${JSON.stringify(o)},`)}})}function l(e,r,n,s){n&&(e.push(`${s}${r}: {`),E(e,n,`${s} `),e.push(`${s}},`))}function g(e){var r;return((r=e==null?void 0:e.target)!=null?r:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function R(e,r="esm",n){let s={...e};delete s.postprocessMessage,delete s.initialMessages;let o=n?{...n,hooks:I(n.hooks)}:void 0;return r==="esm"?W(s,o):r==="script-installer"?k(s,o):r==="script-advanced"?F(s,o):r==="react-component"?H(s,o):r==="react-advanced"?N(s,o):D(s,o)}function W(e,r){let n=r==null?void 0:r.hooks,s=h(e),o=s!=="plain",t=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${g(r)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),o&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&l(t,"theme",e.theme," "),e.launcher&&l(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{t.push(` ${i}: "${a}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"?t.push(` ${i}: ${a},`):typeof a=="number"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{t.push(` ${i}: ${a},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...$(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
74
+ `)}function H(e,r){let n=r==null?void 0:r.hooks,s=h(e),o=s!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${g(r)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),o&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&l(t,"theme",e.theme," "),e.launcher&&l(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{t.push(` ${i}: "${a}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"?t.push(` ${i}: ${a},`):typeof a=="number"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{t.push(` ${i}: ${a},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...$(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
75
+ `)}function N(e,r){let n=r==null?void 0:r.hooks,s=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${g(r)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&l(s,"theme",e.theme," "),e.launcher&&l(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([o,t])=>{s.push(` ${o}: "${t}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"?s.push(` ${o}: ${t},`):typeof t=="number"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,t])=>{typeof t=="string"?s.push(` ${o}: "${t}",`):typeof t=="boolean"&&s.push(` ${o}: ${t},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([o,t])=>{s.push(` ${o}: ${t},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{s.push(` "${o}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...m(e," ")),s.push(...f(e," ",n)),s.push(...y(e," ")),s.push(...C(e," ")),n!=null&&n.getHeaders&&s.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&s.push(` contextProviders: ${n.contextProviders},`),e.debug&&s.push(` debug: ${e.debug},`),s.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?s.push(` streamParser: ${n.streamParser},`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(` streamParser: () => createFlexibleJsonStreamParser(${_}),`)),n!=null&&n.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),s.push(" // Built-in parser for markdown-wrapped JSON"),s.push(` ${x}`),s.push(" ],")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" actionParsers: ["),s.push(" defaultJsonActionParser,"),s.push(" // Parser for markdown-wrapped JSON"),s.push(` ${x}`),s.push(" ],")),n!=null&&n.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` actionHandlers: [...(${n.actionHandlers}),`),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Built-in handler for nav_then_click action"),s.push(` ${j}`),s.push(" ],")):(s.push(" // Action handlers for navigation and other actions"),s.push(" actionHandlers: ["),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Handler for nav_then_click action"),s.push(` ${j}`),s.push(" ],")),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage},`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" requestMiddleware: ({ payload, config }) => {"),s.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),s.push(" const merged = customResult || payload;"),s.push(" return {"),s.push(" ...merged,"),s.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),s.push(" };"),s.push(" }")):(s.push(" requestMiddleware: ({ payload }) => {"),s.push(" return {"),s.push(" ...payload,"),s.push(" metadata: collectDOMContext()"),s.push(" };"),s.push(" }")),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Save state on message events"),s.push(" const handleMessage = () => {"),s.push(" const session = handle?.getSession?.();"),s.push(" if (session) {"),s.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),s.push(" messages: session.messages,"),s.push(" timestamp: new Date().toISOString()"),s.push(" }));"),s.push(" }"),s.push(" };"),s.push(""),s.push(" // Clear state on clear chat"),s.push(" const handleClearChat = () => {"),s.push(" localStorage.removeItem(STORAGE_KEY);"),s.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),s.push(" };"),s.push(""),s.push(" window.addEventListener('persona:message', handleMessage);"),s.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" window.removeEventListener('persona:message', handleMessage);"),s.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage: Collects DOM context for AI-powered navigation"),s.push("// Features:"),s.push("// - Extracts page elements (products, buttons, links)"),s.push("// - Persists chat history across page loads"),s.push("// - Handles navigation actions (nav_then_click)"),s.push("// - Processes structured JSON actions from AI"),s.push("//"),s.push("// Example usage in Next.js:"),s.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),s.push("//"),s.push("// export default function RootLayout({ children }) {"),s.push("// return ("),s.push('// <html lang="en">'),s.push("// <body>"),s.push("// {children}"),s.push("// <ChatWidgetAdvanced />"),s.push("// </body>"),s.push("// </html>"),s.push("// );"),s.push("// }"),s.join(`
76
+ `)}function P(e){var o;let r=h(e),n=r!=="plain",s={};if(e.apiUrl&&(s.apiUrl=e.apiUrl),e.clientToken&&(s.clientToken=e.clientToken),e.agentId&&(s.agentId=e.agentId),e.target&&(s.target=e.target),e.flowId&&(s.flowId=e.flowId),n&&(s.parserType=r),e.theme&&(s.theme=e.theme),e.launcher&&(s.launcher=e.launcher),e.copy&&(s.copy=e.copy),e.sendButton&&(s.sendButton=e.sendButton),e.voiceRecognition&&(s.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(s.statusIndicator=e.statusIndicator),e.features&&(s.features=e.features),((o=e.suggestionChips)==null?void 0:o.length)>0&&(s.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(s.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(s.debug=e.debug),e.toolCall){let t={};Object.entries(e.toolCall).forEach(([i,a])=>{typeof a=="string"&&(t[i]=a)}),Object.keys(t).length>0&&(s.toolCall=t)}if(e.messageActions){let t={};Object.entries(e.messageActions).forEach(([i,a])=>{i!=="onFeedback"&&i!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(t[i]=a)}),Object.keys(t).length>0&&(s.messageActions=t)}if(e.markdown){let t={};e.markdown.options&&(t.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(t.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(t).length>0&&(s.markdown=t)}if(e.layout){let t={};if(e.layout.header){let i={};Object.entries(e.layout.header).forEach(([a,p])=>{a!=="render"&&(typeof p=="string"||typeof p=="boolean")&&(i[a]=p)}),Object.keys(i).length>0&&(t.header=i)}if(e.layout.messages){let i={};Object.entries(e.layout.messages).forEach(([a,p])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof p=="object"&&p!==null)i.avatar=p;else if(a==="timestamp"&&typeof p=="object"&&p!==null){let d={};Object.entries(p).forEach(([w,b])=>{w!=="format"&&(typeof b=="string"||typeof b=="boolean")&&(d[w]=b)}),Object.keys(d).length>0&&(i.timestamp=d)}else(typeof p=="string"||typeof p=="boolean")&&(i[a]=p)}),Object.keys(i).length>0&&(t.messages=i)}Object.keys(t).length>0&&(s.layout=t)}return s}function k(e,r){let n=P(e),o=!!(r!=null&&r.windowKey||r!=null&&r.target)?{config:n,...r!=null&&r.windowKey?{windowKey:r.windowKey}:{},...r!=null&&r.target?{target:r.target}:{}}:n,t=JSON.stringify(o,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/install.global.js" data-config='${t}'></script>`}function D(e,r){let n=r==null?void 0:r.hooks,s=h(e),o=s!=="plain",t=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${g(r)}',`,...r!=null&&r.windowKey?[` windowKey: '${r.windowKey}',`]:[]," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),o&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&l(t,"theme",e.theme," "),e.launcher&&l(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([i,a])=>{t.push(` ${i}: "${a}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"?t.push(` ${i}: ${a},`):typeof a=="number"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,a])=>{typeof a=="string"?t.push(` ${i}: "${a}",`):typeof a=="boolean"&&t.push(` ${i}: ${a},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([i,a])=>{t.push(` ${i}: ${a},`)}),t.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{t.push(` "${i}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...m(e," ")),t.push(...f(e," ",n)),t.push(...y(e," ")),t.push(...C(e," ")),t.push(...$(n," ")),e.debug&&t.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?t.push(` postprocessMessage: ${n.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push("</script>"),t.join(`
77
77
  `)}function F(e,r){let n=r==null?void 0:r.hooks,s=P(e),t=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(s,null,2).split(`
78
78
  `).map((i,a)=>a===0?i:" "+i).join(`
79
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(t.push(` widgetConfig.getHeaders = ${n.getHeaders};`),t.push("")),n!=null&&n.contextProviders&&(t.push(` widgetConfig.contextProviders = ${n.contextProviders};`),t.push("")),n!=null&&n.streamParser?t.push(` widgetConfig.streamParser = ${n.streamParser};`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(" widgetConfig.streamParser = function() {"),t.push(` return agentWidget.createFlexibleJsonStreamParser(${M});`),t.push(" };")),t.push(""),n!=null&&n.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` var customParsers = ${n.actionParsers};`),t.push(" widgetConfig.actionParsers = customParsers.concat(["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${A}`),t.push(" ]);")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" widgetConfig.actionParsers = ["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${A}`),t.push(" ];")),t.push(""),n!=null&&n.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` var customHandlers = ${n.actionHandlers};`),t.push(" widgetConfig.actionHandlers = customHandlers.concat(["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${O}`),t.push(" ]);")):(t.push(" // Action handlers for navigation and other actions"),t.push(" widgetConfig.actionHandlers = ["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${O}`),t.push(" ];")),t.push(""),n!=null&&n.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(` var customResult = (${n.requestMiddleware})(ctx);`),t.push(" var merged = customResult || ctx.payload;"),t.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),t.push(" };")):(t.push(" // Send DOM context with each request"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),t.push(" };")),t.push(""),n!=null&&n.postprocessMessage?t.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(t.push(" // Markdown postprocessor"),t.push(" widgetConfig.postprocessMessage = function(ctx) {"),t.push(" return agentWidget.markdownPostprocessor(ctx.text);"),t.push(" };")),t.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(t.push(" // Message action callbacks"),t.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&t.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&t.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),t.push("")),t.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${g(r)}',`," useShadowDom: false,",...r!=null&&r.windowKey?[` windowKey: '${r.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),t.join(`
80
- `)}export{I as generateCodeSnippet};
79
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(t.push(` widgetConfig.getHeaders = ${n.getHeaders};`),t.push("")),n!=null&&n.contextProviders&&(t.push(` widgetConfig.contextProviders = ${n.contextProviders};`),t.push("")),n!=null&&n.streamParser?t.push(` widgetConfig.streamParser = ${n.streamParser};`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(" widgetConfig.streamParser = function() {"),t.push(` return agentWidget.createFlexibleJsonStreamParser(${T});`),t.push(" };")),t.push(""),n!=null&&n.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` var customParsers = ${n.actionParsers};`),t.push(" widgetConfig.actionParsers = customParsers.concat(["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${A}`),t.push(" ]);")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" widgetConfig.actionParsers = ["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${A}`),t.push(" ];")),t.push(""),n!=null&&n.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` var customHandlers = ${n.actionHandlers};`),t.push(" widgetConfig.actionHandlers = customHandlers.concat(["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${O}`),t.push(" ]);")):(t.push(" // Action handlers for navigation and other actions"),t.push(" widgetConfig.actionHandlers = ["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${O}`),t.push(" ];")),t.push(""),n!=null&&n.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(` var customResult = (${n.requestMiddleware})(ctx);`),t.push(" var merged = customResult || ctx.payload;"),t.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),t.push(" };")):(t.push(" // Send DOM context with each request"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),t.push(" };")),t.push(""),n!=null&&n.postprocessMessage?t.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(t.push(" // Markdown postprocessor"),t.push(" widgetConfig.postprocessMessage = function(ctx) {"),t.push(" return agentWidget.markdownPostprocessor(ctx.text);"),t.push(" };")),t.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(t.push(" // Message action callbacks"),t.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&t.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&t.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),t.push("")),t.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${g(r)}',`," useShadowDom: false,",...r!=null&&r.windowKey?[` windowKey: '${r.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),t.join(`
80
+ `)}export{R as generateCodeSnippet};