@runtypelabs/persona 4.13.0 → 4.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-DveIaNx6.d.cts → types-BpWGm7_6.d.cts} +17 -0
- package/dist/animations/{types-DveIaNx6.d.ts → types-BpWGm7_6.d.ts} +17 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/chunk-QJ4LV2KW.js +1 -0
- package/dist/codegen.cjs +12 -11
- package/dist/codegen.js +14 -13
- package/dist/{context-mentions-ONG7A7M6.js → context-mentions-BTSTIBFC.js} +1 -1
- package/dist/context-mentions.cjs +11 -8
- package/dist/context-mentions.d.cts +339 -22
- package/dist/context-mentions.d.ts +339 -22
- package/dist/context-mentions.js +11 -8
- package/dist/index.cjs +68 -67
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +483 -48
- package/dist/index.d.ts +483 -48
- package/dist/index.global.js +61 -58
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +70 -69
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +5 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +339 -22
- package/dist/smart-dom-reader.d.ts +339 -22
- package/dist/theme-editor-preview.cjs +67 -67
- package/dist/theme-editor-preview.d.cts +355 -23
- package/dist/theme-editor-preview.d.ts +355 -23
- package/dist/theme-editor-preview.js +75 -75
- package/dist/theme-editor.cjs +10 -10
- package/dist/theme-editor.d.cts +376 -24
- package/dist/theme-editor.d.ts +376 -24
- package/dist/theme-editor.js +10 -10
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +38 -0
- package/dist/theme-reference.d.ts +38 -0
- package/dist/theme-reference.js +1 -1
- package/dist/widget.css +1 -1
- package/package.json +1 -1
- package/src/artifacts-session.test.ts +106 -0
- package/src/ask-user-question-tool.ts +10 -7
- package/src/client.test.ts +2 -2
- package/src/client.ts +4 -1
- package/src/components/artifact-card.ts +13 -2
- package/src/components/artifact-inline.ts +11 -2
- package/src/components/artifact-preview.ts +1 -1
- package/src/components/composer-builder.test.ts +2 -0
- package/src/components/composer-builder.ts +1 -1
- package/src/components/composer-parts.test.ts +105 -4
- package/src/components/composer-parts.ts +54 -16
- package/src/components/message-bubble.test.ts +7 -1
- package/src/components/message-bubble.ts +11 -8
- package/src/components/messages.ts +5 -2
- package/src/components/panel.ts +31 -5
- package/src/components/pill-composer-builder.test.ts +18 -0
- package/src/components/suggestions.test.ts +233 -0
- package/src/components/suggestions.ts +463 -81
- package/src/components/widget-view.ts +4 -0
- package/src/defaults.ts +5 -3
- package/src/generated/runtype-openapi-contract.ts +17 -0
- package/src/index-core.ts +52 -2
- package/src/launcher-global.ts +1 -1
- package/src/plugins/types.ts +71 -3
- package/src/presets.ts +3 -3
- package/src/session.ts +55 -12
- package/src/styles/widget-styles.test.ts +162 -0
- package/src/styles/widget.css +440 -1
- package/src/suggest-replies-tool.test.ts +233 -2
- package/src/suggest-replies-tool.ts +115 -39
- package/src/theme-editor/index.ts +5 -0
- package/src/theme-editor/presets.test.ts +43 -0
- package/src/theme-editor/presets.ts +101 -87
- package/src/theme-editor/preview-utils.test.ts +34 -0
- package/src/theme-editor/preview-utils.ts +77 -2
- package/src/theme-editor/sections.test.ts +72 -7
- package/src/theme-editor/sections.ts +113 -13
- package/src/theme-editor/state-preferences.test.ts +15 -0
- package/src/theme-editor/state.ts +46 -0
- package/src/theme-editor/types.ts +15 -1
- package/src/theme-editor/webmcp/tools.test.ts +13 -0
- package/src/theme-editor/webmcp/tools.ts +5 -0
- package/src/theme-reference.ts +9 -2
- package/src/types/theme.ts +32 -0
- package/src/types.ts +291 -25
- package/src/ui.artifact-pane-gating.test.ts +5 -5
- package/src/ui.config-preferences.test.ts +166 -0
- package/src/ui.detached-panel.test.ts +1 -1
- package/src/ui.suggest-replies.test.ts +1066 -1
- package/src/ui.ts +311 -45
- package/src/ui.typing-indicator.test.ts +135 -0
- package/src/utils/artifact-display.test.ts +180 -16
- package/src/utils/artifact-display.ts +155 -14
- package/src/utils/artifact-file.test.ts +1 -1
- package/src/utils/code-generators.test.ts +40 -0
- package/src/utils/code-generators.ts +22 -0
- package/src/utils/config-merge.test.ts +84 -0
- package/src/utils/config-merge.ts +6 -1
- package/src/utils/feature-preferences.test.ts +326 -0
- package/src/utils/feature-preferences.ts +498 -0
- package/src/utils/icons.test.ts +26 -0
- package/src/utils/icons.ts +8 -0
- package/src/utils/theme.test.ts +171 -0
- package/src/utils/tokens.ts +71 -7
- package/dist/chunk-MMUPR2JW.js +0 -1
package/README.md
CHANGED
|
@@ -42,7 +42,7 @@ createAgentExperience(inlineHost, {
|
|
|
42
42
|
theme: {
|
|
43
43
|
semantic: { colors: { accent: '#2563eb' } }
|
|
44
44
|
},
|
|
45
|
-
|
|
45
|
+
suggestions: { starters: { items: ['What can you do?', 'Show API docs'] } },
|
|
46
46
|
postprocessMessage: ({ text }) => markdownPostprocessor(text)
|
|
47
47
|
});
|
|
48
48
|
|
|
@@ -127,12 +127,12 @@ With **`dock.reveal: 'resize'`** (default), a **closed** dock uses a **`0px`** c
|
|
|
127
127
|
The full reference lives in [`docs/`](./docs/) and the theming guide:
|
|
128
128
|
|
|
129
129
|
- [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
|
|
130
|
-
- [Authoring Plugins](./docs/PLUGINS.md): the `AgentWidgetPlugin` contract,
|
|
130
|
+
- [Authoring Plugins](./docs/PLUGINS.md): the `AgentWidgetPlugin` contract, render/data/interaction hooks, global vs per-instance registration, lifecycle, and the `@runtypelabs/persona/plugin-kit` helpers
|
|
131
131
|
- [Contributing](../../CONTRIBUTING.md): current guidance for contributing plugins, themes, adapters, examples, and other customizations back to this monorepo
|
|
132
132
|
- [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
|
|
133
133
|
- [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
|
|
134
134
|
- [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
|
|
135
|
-
- [Configuration Reference](./docs/CONFIGURATION-REFERENCE.md): every config option: core, client token mode, agent mode, UI & theme, launcher/docking, layout, voice, WebMCP, tool calls, features,
|
|
135
|
+
- [Configuration Reference](./docs/CONFIGURATION-REFERENCE.md): every config option: core, client token mode, agent mode, UI & theme, launcher/docking, layout, voice, WebMCP, tool calls, features, suggestions, state & storage
|
|
136
136
|
- [Context Mentions](./docs/CONTEXT-MENTIONS.md): `@`-mention sources, resolve lifecycle, chip vs inline display, menu positioning, slash commands, and render overrides
|
|
137
137
|
- [Stream Parser Configuration](./docs/STREAM-PARSERS.md): JSON, XML, and plain-text stream parsers and custom parser factories
|
|
138
138
|
- [Message Injection](./docs/MESSAGE-INJECTION.md): full injection and component-directive reference
|
|
@@ -233,5 +233,5 @@ Add `RUNTYPE_API_KEY` to your environment. The proxy constructs the Runtype payl
|
|
|
233
233
|
- Tailwind classes are prefixed with `tvw-` and scoped to `[data-persona-root]`, so they won't collide with the host page.
|
|
234
234
|
- Run `pnpm dev` from the repository root to boot the example Runtype proxy (`examples/runtype-hono-proxy`) and the vanilla demo (`apps/web`).
|
|
235
235
|
- The proxy prefers port `43111` but automatically selects the next free port if needed.
|
|
236
|
-
- `features.askUserQuestion.expose` and `
|
|
236
|
+
- `features.askUserQuestion.expose` and `suggestions.followUps.expose` advertise built-in LOCAL client tools through `clientTools[]`; leave `expose` off if the flow already declares those tools server-side.
|
|
237
237
|
- `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.
|
|
@@ -251,7 +251,24 @@ type RuntypeExecutionStreamEvent = ({
|
|
|
251
251
|
type: "source";
|
|
252
252
|
url?: string;
|
|
253
253
|
[key: string]: unknown;
|
|
254
|
+
} | {
|
|
255
|
+
executionId: string;
|
|
256
|
+
iteration?: number;
|
|
257
|
+
seq: number;
|
|
258
|
+
state: Record<string, unknown>;
|
|
259
|
+
type: "state_snapshot";
|
|
254
260
|
} | ({
|
|
261
|
+
executionId: string;
|
|
262
|
+
iteration?: number;
|
|
263
|
+
patch: Array<{
|
|
264
|
+
from?: string;
|
|
265
|
+
op: "add" | "remove" | "replace" | "move" | "copy" | "test";
|
|
266
|
+
path: string;
|
|
267
|
+
value?: unknown;
|
|
268
|
+
}>;
|
|
269
|
+
seq: number;
|
|
270
|
+
type: "state_delta";
|
|
271
|
+
}) | ({
|
|
255
272
|
executionId: string;
|
|
256
273
|
hiddenParameterNames?: Array<string>;
|
|
257
274
|
iteration?: number;
|
|
@@ -251,7 +251,24 @@ type RuntypeExecutionStreamEvent = ({
|
|
|
251
251
|
type: "source";
|
|
252
252
|
url?: string;
|
|
253
253
|
[key: string]: unknown;
|
|
254
|
+
} | {
|
|
255
|
+
executionId: string;
|
|
256
|
+
iteration?: number;
|
|
257
|
+
seq: number;
|
|
258
|
+
state: Record<string, unknown>;
|
|
259
|
+
type: "state_snapshot";
|
|
254
260
|
} | ({
|
|
261
|
+
executionId: string;
|
|
262
|
+
iteration?: number;
|
|
263
|
+
patch: Array<{
|
|
264
|
+
from?: string;
|
|
265
|
+
op: "add" | "remove" | "replace" | "move" | "copy" | "test";
|
|
266
|
+
path: string;
|
|
267
|
+
value?: unknown;
|
|
268
|
+
}>;
|
|
269
|
+
seq: number;
|
|
270
|
+
type: "state_delta";
|
|
271
|
+
}) | ({
|
|
255
272
|
executionId: string;
|
|
256
273
|
hiddenParameterNames?: Array<string>;
|
|
257
274
|
iteration?: number;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var Kt=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var Wt=()=>document.createDocumentFragment(),Ut=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))o.setAttribute(s,a);if(t.style){let s=o.style,a=t.style;for(let c of Object.keys(a)){let l=a[c];l!=null&&(s[c]=l)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},jt=(...e)=>e.filter(Boolean).join(" ");import{Activity as A,ArrowDown as k,ArrowUp as P,ArrowUpRight as L,Bot as I,ChevronDown as R,ChevronUp as D,ChevronRight as H,ChevronLeft as O,Check as z,Clipboard as B,ClipboardCopy as F,CodeXml as K,Copy as W,File as U,FileCode as j,FileSpreadsheet as $,FileText as q,ImagePlus as V,Loader as X,LoaderCircle as G,Mic as _,Paperclip as Y,RefreshCw as Z,Search as J,Send as Q,ShieldAlert as ee,ShieldCheck as te,ShieldX as ne,Square as oe,ThumbsDown as re,ThumbsUp as ie,Upload as se,Volume2 as ae,X as le,User as ce,Mail as de,Phone as ue,Calendar as me,Clock as pe,Building as ge,MapPin as he,Lock as fe,Key as we,CreditCard as ye,AtSign as be,Hash as ve,Globe as xe,Link as Ce,CircleCheck as Se,CircleX as Ee,TriangleAlert as Te,Info as Me,Ban as Ne,Shield as Ae,ArrowLeft as ke,ArrowRight as Pe,ExternalLink as Le,Ellipsis as Ie,EllipsisVertical as Re,Menu as De,House as He,Plus as Oe,Minus as ze,Pencil as Be,PenLine as Fe,Trash as Ke,Trash2 as We,Save as Ue,Download as je,Share as $e,Funnel as qe,Settings as Ve,RotateCw as Xe,Maximize as Ge,Minimize as _e,ShoppingCart as Ye,ShoppingBag as Ze,Package as Je,Truck as Qe,Tag as et,Gift as tt,Receipt as nt,Wallet as ot,Store as rt,DollarSign as it,Percent as st,Play as at,Pause as lt,VolumeX as ct,Camera as dt,Image as ut,Film as mt,Headphones as pt,MessageCircle as gt,MessageSquare as ht,Bell as ft,Heart as wt,Star as yt,Eye as bt,EyeOff as vt,Bookmark as xt,CalendarDays as Ct,History as St,Timer as Et,Folder as Tt,FolderOpen as Mt,Files as Nt,ChartColumn as At,Sparkles as kt,Zap as Pt,Sun as Lt,Moon as It,Flag as Rt,Lightbulb as Dt,Monitor as Ht,Smartphone as Ot}from"lucide";var zt={activity:A,"arrow-down":k,"arrow-up":P,"arrow-up-right":L,bot:I,"chevron-down":R,"chevron-up":D,"chevron-right":H,"chevron-left":O,check:z,clipboard:B,"clipboard-copy":F,"code-xml":K,copy:W,file:U,"file-code":j,"file-spreadsheet":$,"file-text":q,"image-plus":V,loader:X,"loader-circle":G,mic:_,paperclip:Y,"refresh-cw":Z,search:J,send:Q,"shield-alert":ee,"shield-check":te,"shield-x":ne,square:oe,"thumbs-down":re,"thumbs-up":ie,upload:se,"volume-2":ae,x:le,user:ce,mail:de,phone:ue,calendar:me,clock:pe,building:ge,"map-pin":he,lock:fe,key:we,"credit-card":ye,"at-sign":be,hash:ve,globe:xe,link:Ce,"circle-check":Se,"circle-x":Ee,"triangle-alert":Te,info:Me,ban:Ne,shield:Ae,"arrow-left":ke,"arrow-right":Pe,"external-link":Le,ellipsis:Ie,"ellipsis-vertical":Re,menu:De,house:He,plus:Oe,minus:ze,pencil:Be,"pen-line":Fe,trash:Ke,"trash-2":We,save:Ue,download:je,share:$e,funnel:qe,settings:Ve,"rotate-cw":Xe,maximize:Ge,minimize:_e,"shopping-cart":Ye,"shopping-bag":Ze,package:Je,truck:Qe,tag:et,gift:tt,receipt:nt,wallet:ot,store:rt,"dollar-sign":it,percent:st,play:at,pause:lt,"volume-x":ct,camera:dt,image:ut,film:mt,headphones:pt,"message-circle":gt,"message-square":ht,bell:ft,heart:wt,star:yt,eye:bt,"eye-off":vt,bookmark:xt,"calendar-days":Ct,history:St,timer:Et,folder:Tt,"folder-open":Mt,files:Nt,"chart-column":At,sparkles:kt,zap:Pt,sun:Lt,moon:It,flag:Rt,lightbulb:Dt,monitor:Ht,smartphone:Ot},Vt=(e,t=24,n="currentColor",o=2)=>{let r=zt[e];return r?Bt(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Bt(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],c=s[1];if(!c)return;let l=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(c).forEach(([h,f])=>{h!=="stroke"&&l.setAttribute(h,String(f))}),r.appendChild(l)}),r}function Gt(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[t,...n]}function T(e){let t=e.getRootNode?.();return t instanceof ShadowRoot||t instanceof Document?t:e.ownerDocument??document}function b(e,t,n){let o=e instanceof Document?e.head:e,r=t.replace(/["\\]/g,"\\$&");if(o.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let a=(e instanceof Document?e:e.ownerDocument??document).createElement("style");a.setAttribute("data-persona-plugin-style",t),a.textContent=n,o.appendChild(a)}function Yt(e,t,n){if(e instanceof Document||e instanceof ShadowRoot){b(e,t,n);return}let o=e;if(o.isConnected){b(T(o),t,n);return}let r=o.ownerDocument??document;b(r,t,n),queueMicrotask(()=>{let s=T(o);s!==r&&b(s,t,n)})}function Ft(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Zt(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:c,zIndex:l=2147483e3,onOpen:h,onDismiss:f}=e,M=e.container??Ft(t),d=!1,w=null,v=()=>{if(!d)return;let i=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${i.width}px`),a&&(n.style.maxWidth=`${i.width}px`);let m=n.getBoundingClientRect(),u=c?.()??null,y=u!=null?i.top+u:i.top,x=o==="top-start"||o==="top-end"?y-r-m.height:i.bottom+r,g=o==="bottom-end"||o==="top-end"?i.right-m.width:i.left,E=a?.()??null;if(E!=null){let N=Math.max(i.left,i.right-m.width);g=Math.min(Math.max(i.left+E,i.left),N)}n.style.top=`${x}px`,n.style.left=`${g}px`},p=()=>{d&&(d=!1,w&&(w(),w=null),n.remove())},S=()=>{if(d)return;d=!0,l!=null&&(n.style.zIndex=String(l)),M.appendChild(n),v();let i=(t.ownerDocument??document).defaultView??window,m=t.ownerDocument??document,u=()=>{if(!t.isConnected){p(),f?.("anchor-removed");return}v()},y=C=>{let g=typeof C.composedPath=="function"?C.composedPath():[];g.includes(n)||g.includes(t)||(p(),f?.("outside"))},x=i.setTimeout(()=>{m.addEventListener("pointerdown",y,!0)},0);i.addEventListener("scroll",u,!0),i.addEventListener("resize",u),w=()=>{i.clearTimeout(x),m.removeEventListener("pointerdown",y,!0),i.removeEventListener("scroll",u,!0),i.removeEventListener("resize",u)},h?.()};return{get isOpen(){return d},open:S,close:p,toggle:()=>d?p():S(),reposition:v,destroy:p}}function Jt(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}export{Kt as a,Wt as b,Ut as c,jt as d,Vt as e,Gt as f,Yt as g,Zt as h,Jt as i};
|
package/dist/codegen.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var $=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var M=Object.prototype.hasOwnProperty;var R=(e,i)=>{for(var r in i)$(e,r,{get:i[r],enumerable:!0})},W=(e,i,r,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let a of T(i))!M.call(e,a)&&a!==r&&$(e,a,{get:()=>i[a],enumerable:!(s=_(i,a))||s.enumerable});return e};var H=e=>W($({},"__esModule",{value:!0}),e);var z={};R(z,{generateCodeSnippet:()=>I});module.exports=H(z);var x="4.15.0";var A=x;function w(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,r=>`%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${A}/dist`}function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(i=>i.toString()).join(", ")}]`:e.toString()}function D(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 j=`({ 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
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
12
12
|
} catch (e) { return null; }
|
|
13
13
|
return null;
|
|
14
|
-
}`,
|
|
14
|
+
}`,O=`function(ctx) {
|
|
15
15
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
16
16
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
17
17
|
var cleanJson = jsonSource
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
25
25
|
} catch (e) { return null; }
|
|
26
26
|
return null;
|
|
27
|
-
}`,
|
|
27
|
+
}`,E=`(action: any, context: any) => {
|
|
28
28
|
if (action.type !== 'nav_then_click') return;
|
|
29
29
|
const payload = action.payload || action.raw || {};
|
|
30
30
|
const url = payload?.page;
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
42
42
|
window.location.href = targetUrl;
|
|
43
43
|
return { handled: true, displayText: text };
|
|
44
|
-
}`,
|
|
44
|
+
}`,k=`function(action, context) {
|
|
45
45
|
if (action.type !== 'nav_then_click') return;
|
|
46
46
|
var payload = action.payload || action.raw || {};
|
|
47
47
|
var url = payload.page;
|
|
@@ -58,7 +58,7 @@
|
|
|
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
|
-
}`,
|
|
61
|
+
}`,J=`(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 || '';
|
|
@@ -70,11 +70,12 @@
|
|
|
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
|
|
74
|
-
`)}function
|
|
75
|
-
`)}function K(e,i){let r=i?.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: '${c(i)}',`," 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&&d(s,"theme",e.theme," "),e.launcher&&d(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,t])=>{s.push(` ${a}: "${t}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"?s.push(` ${a}: ${t},`):typeof t=="number"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,t])=>{s.push(` ${a}: ${t},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),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(...g(e," ")),s.push(...m(e," ",r)),s.push(...f(e," ")),s.push(...y(e," ")),r?.getHeaders&&s.push(` getHeaders: ${r.getHeaders},`),r?.contextProviders&&s.push(` contextProviders: ${r.contextProviders},`),e.debug&&s.push(` debug: ${e.debug},`),s.push(" initialMessages: loadSavedMessages(),"),r?.streamParser?s.push(` streamParser: ${r.streamParser},`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(` streamParser: () => createFlexibleJsonStreamParser(${D}),`)),r?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` actionParsers: [...(${r.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(" ],")),r?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` actionHandlers: [...(${r.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(" ],")),r?.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage},`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" requestMiddleware: ({ payload, config }) => {"),s.push(` const customResult = (${r.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){let i=h(e),r=i!=="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),r&&(s.parserType=i),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),e.suggestionChips?.length>0&&(s.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(s.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(s.debug=e.debug),e.toolCall){let a={};Object.entries(e.toolCall).forEach(([t,n])=>{typeof n=="string"&&(a[t]=n)}),Object.keys(a).length>0&&(s.toolCall=a)}if(e.messageActions){let a={};Object.entries(e.messageActions).forEach(([t,n])=>{t!=="onFeedback"&&t!=="onCopy"&&n!==void 0&&(typeof n=="string"||typeof n=="boolean")&&(a[t]=n)}),Object.keys(a).length>0&&(s.messageActions=a)}if(e.markdown){let a={};e.markdown.options&&(a.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(a.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(a).length>0&&(s.markdown=a)}if(e.layout){let a={};if(e.layout.header){let t={};Object.entries(e.layout.header).forEach(([n,o])=>{n!=="render"&&(typeof o=="string"||typeof o=="boolean")&&(t[n]=o)}),Object.keys(t).length>0&&(a.header=t)}if(e.layout.messages){let t={};Object.entries(e.layout.messages).forEach(([n,o])=>{if(n!=="renderUserMessage"&&n!=="renderAssistantMessage")if(n==="avatar"&&typeof o=="object"&&o!==null)t.avatar=o;else if(n==="timestamp"&&typeof o=="object"&&o!==null){let p={};Object.entries(o).forEach(([l,C])=>{l!=="format"&&(typeof C=="string"||typeof C=="boolean")&&(p[l]=C)}),Object.keys(p).length>0&&(t.timestamp=p)}else(typeof o=="string"||typeof o=="boolean")&&(t[n]=o)}),Object.keys(t).length>0&&(a.messages=t)}Object.keys(a).length>0&&(s.layout=a)}return s}function G(e,i){let r=I(e),a=!!(i?.windowKey||i?.target)?{config:r,...i?.windowKey?{windowKey:i.windowKey}:{},...i?.target?{target:i.target}:{}}:r,t=JSON.stringify(a,null,0).replace(/'/g,"'");return`<script src="${$(i)}/install.global.js" data-config='${t}'></script>`}function B(e,i){let r=i?.hooks,s=h(e),a=s!=="plain",t=$(i),n=["<!-- Load CSS -->",`<link rel="stylesheet" href="${t}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${t}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${c(i)}',`,...i?.windowKey?[` windowKey: '${i.windowKey}',`]:[]," config: {"];return e.apiUrl&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.agentId&&n.push(` agentId: "${e.agentId}",`),e.target&&n.push(` target: "${e.target}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),a&&n.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(n,"theme",e.theme," "),e.launcher&&d(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([o,p])=>{n.push(` ${o}: "${p}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"?n.push(` ${o}: ${p},`):typeof p=="number"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([o,p])=>{n.push(` ${o}: ${p},`)}),n.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{n.push(` "${o}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...g(e," ")),n.push(...m(e," ",r)),n.push(...f(e," ")),n.push(...y(e," ")),n.push(...w(r," ")),e.debug&&n.push(` debug: ${e.debug},`),r?.postprocessMessage?n.push(` postprocessMessage: ${r.postprocessMessage}`):n.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),n.push(" }"),n.push(" });"),n.push("</script>"),n.join(`
|
|
77
|
-
`)}function Y(e,i){let r=i?.hooks,s=
|
|
73
|
+
}`;function q(e){if(!e)return null;let i=e.toString();return i.includes("createJsonStreamParser")||i.includes("partial-json")?"json":i.includes("createRegexJsonParser")||i.includes("regex")?"regex-json":i.includes("createXmlParser")||i.includes("<text>")?"xml":null}function h(e){return e.parserType??q(e.streamParser)??"plain"}function g(e,i){let r=[];return e.toolCall&&(r.push(`${i}toolCall: {`),Object.entries(e.toolCall).forEach(([s,a])=>{typeof a=="string"&&r.push(`${i} ${s}: "${a}",`)}),r.push(`${i}},`)),r}function m(e,i,r){let s=[],a=e.messageActions&&Object.entries(e.messageActions).some(([n,o])=>n!=="onFeedback"&&n!=="onCopy"&&o!==void 0),t=r?.onFeedback||r?.onCopy;return(a||t)&&(s.push(`${i}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([n,o])=>{n==="onFeedback"||n==="onCopy"||(typeof o=="string"?s.push(`${i} ${n}: "${o}",`):typeof o=="boolean"&&s.push(`${i} ${n}: ${o},`))}),r?.onFeedback&&s.push(`${i} onFeedback: ${r.onFeedback},`),r?.onCopy&&s.push(`${i} onCopy: ${r.onCopy},`),s.push(`${i}},`)),s}function f(e,i){let r=[];if(e.markdown){let s=e.markdown.options&&Object.keys(e.markdown.options).length>0,a=e.markdown.disableDefaultStyles!==void 0;(s||a)&&(r.push(`${i}markdown: {`),s&&(r.push(`${i} options: {`),Object.entries(e.markdown.options).forEach(([t,n])=>{typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`)}),r.push(`${i} },`)),a&&r.push(`${i} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),r.push(`${i}},`))}return r}function y(e,i){if(!e.suggestions)return[];let r=JSON.stringify(e.suggestions,null,2).split(`
|
|
74
|
+
`);return r.map((s,a)=>{let t=a===0?`${i}suggestions: `:i,n=a===r.length-1?",":"";return`${t}${s}${n}`})}function C(e,i){let r=[];if(e.layout){let s=e.layout.header&&Object.keys(e.layout.header).some(t=>t!=="render"),a=e.layout.messages&&Object.keys(e.layout.messages).some(t=>t!=="renderUserMessage"&&t!=="renderAssistantMessage");(s||a)&&(r.push(`${i}layout: {`),s&&(r.push(`${i} header: {`),Object.entries(e.layout.header).forEach(([t,n])=>{t!=="render"&&(typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`))}),r.push(`${i} },`)),a&&(r.push(`${i} messages: {`),Object.entries(e.layout.messages).forEach(([t,n])=>{t==="renderUserMessage"||t==="renderAssistantMessage"||(t==="avatar"&&typeof n=="object"&&n!==null?(r.push(`${i} avatar: {`),Object.entries(n).forEach(([o,p])=>{typeof p=="string"?r.push(`${i} ${o}: "${p}",`):typeof p=="boolean"&&r.push(`${i} ${o}: ${p},`)}),r.push(`${i} },`)):t==="timestamp"&&typeof n=="object"&&n!==null?Object.entries(n).some(([p])=>p!=="format")&&(r.push(`${i} timestamp: {`),Object.entries(n).forEach(([p,l])=>{p!=="format"&&(typeof l=="string"?r.push(`${i} ${p}: "${l}",`):typeof l=="boolean"&&r.push(`${i} ${p}: ${l},`))}),r.push(`${i} },`)):typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`))}),r.push(`${i} },`)),r.push(`${i}},`))}return r}function S(e,i){let r=[];return e&&(e.getHeaders&&r.push(`${i}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&r.push(`${i}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&r.push(`${i}actionParsers: ${e.actionParsers},`),e.actionHandlers&&r.push(`${i}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&r.push(`${i}contextProviders: ${e.contextProviders},`),e.streamParser&&r.push(`${i}streamParser: ${e.streamParser},`)),r}function P(e,i,r){Object.entries(i).forEach(([s,a])=>{if(!(a===void 0||typeof a=="function")){if(Array.isArray(a)){e.push(`${r}${s}: ${JSON.stringify(a)},`);return}if(a&&typeof a=="object"){e.push(`${r}${s}: {`),P(e,a,`${r} `),e.push(`${r}},`);return}e.push(`${r}${s}: ${JSON.stringify(a)},`)}})}function d(e,i,r,s){r&&(e.push(`${s}${i}: {`),P(e,r,`${s} `),e.push(`${s}},`))}function c(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function I(e,i="esm",r){let s={...e};delete s.postprocessMessage,delete s.initialMessages;let a=r?{...r,hooks:D(r.hooks)}:void 0;return i==="esm"?L(s,a):i==="script-installer"?B(s,a):i==="script-advanced"?U(s,a):i==="react-component"?K(s,a):i==="react-advanced"?G(s,a):Y(s,a)}function L(e,i){let r=i?.hooks,s=h(e),a=s!=="plain",t=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${c(i)}',`," 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}",`),a&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(t,"theme",e.theme," "),e.launcher&&d(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([n,o])=>{t.push(` ${n}: "${o}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"?t.push(` ${n}: ${o},`):typeof o=="number"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([n,o])=>{t.push(` ${n}: ${o},`)}),t.push(" },")),t.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(n=>{t.push(` "${n}",`)}),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(...g(e," ")),t.push(...m(e," ",r)),t.push(...f(e," ")),t.push(...C(e," ")),t.push(...S(r," ")),e.debug&&t.push(` debug: ${e.debug},`),r?.postprocessMessage?t.push(` postprocessMessage: ${r.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
|
|
75
|
+
`)}function K(e,i){let r=i?.hooks,s=h(e),a=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: '${c(i)}',`," 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}",`),a&&t.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(t,"theme",e.theme," "),e.launcher&&d(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([n,o])=>{t.push(` ${n}: "${o}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"?t.push(` ${n}: ${o},`):typeof o=="number"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([n,o])=>{t.push(` ${n}: ${o},`)}),t.push(" },")),t.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(n=>{t.push(` "${n}",`)}),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(...g(e," ")),t.push(...m(e," ",r)),t.push(...f(e," ")),t.push(...C(e," ")),t.push(...S(r," ")),e.debug&&t.push(` debug: ${e.debug},`),r?.postprocessMessage?t.push(` postprocessMessage: ${r.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(`
|
|
76
|
+
`)}function G(e,i){let r=i?.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: '${c(i)}',`," 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&&d(s,"theme",e.theme," "),e.launcher&&d(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,t])=>{s.push(` ${a}: "${t}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"?s.push(` ${a}: ${t},`):typeof t=="number"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,t])=>{s.push(` ${a}: ${t},`)}),s.push(" },")),s.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),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(...g(e," ")),s.push(...m(e," ",r)),s.push(...f(e," ")),s.push(...C(e," ")),r?.getHeaders&&s.push(` getHeaders: ${r.getHeaders},`),r?.contextProviders&&s.push(` contextProviders: ${r.contextProviders},`),e.debug&&s.push(` debug: ${e.debug},`),s.push(" initialMessages: loadSavedMessages(),"),r?.streamParser?s.push(` streamParser: ${r.streamParser},`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(` streamParser: () => createFlexibleJsonStreamParser(${J}),`)),r?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),s.push(" // Built-in parser for markdown-wrapped JSON"),s.push(` ${j}`),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(` ${j}`),s.push(" ],")),r?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` actionHandlers: [...(${r.actionHandlers}),`),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Built-in handler for nav_then_click action"),s.push(` ${E}`),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(` ${E}`),s.push(" ],")),r?.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage},`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" requestMiddleware: ({ payload, config }) => {"),s.push(` const customResult = (${r.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(`
|
|
77
|
+
`)}function v(e){let i=h(e),r=i!=="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),r&&(s.parserType=i),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),e.suggestions&&(s.suggestions=e.suggestions),e.suggestionChips?.length>0&&(s.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(s.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(s.debug=e.debug),e.toolCall){let a={};Object.entries(e.toolCall).forEach(([t,n])=>{typeof n=="string"&&(a[t]=n)}),Object.keys(a).length>0&&(s.toolCall=a)}if(e.messageActions){let a={};Object.entries(e.messageActions).forEach(([t,n])=>{t!=="onFeedback"&&t!=="onCopy"&&n!==void 0&&(typeof n=="string"||typeof n=="boolean")&&(a[t]=n)}),Object.keys(a).length>0&&(s.messageActions=a)}if(e.markdown){let a={};e.markdown.options&&(a.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(a.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(a).length>0&&(s.markdown=a)}if(e.layout){let a={};if(e.layout.header){let t={};Object.entries(e.layout.header).forEach(([n,o])=>{n!=="render"&&(typeof o=="string"||typeof o=="boolean")&&(t[n]=o)}),Object.keys(t).length>0&&(a.header=t)}if(e.layout.messages){let t={};Object.entries(e.layout.messages).forEach(([n,o])=>{if(n!=="renderUserMessage"&&n!=="renderAssistantMessage")if(n==="avatar"&&typeof o=="object"&&o!==null)t.avatar=o;else if(n==="timestamp"&&typeof o=="object"&&o!==null){let p={};Object.entries(o).forEach(([l,b])=>{l!=="format"&&(typeof b=="string"||typeof b=="boolean")&&(p[l]=b)}),Object.keys(p).length>0&&(t.timestamp=p)}else(typeof o=="string"||typeof o=="boolean")&&(t[n]=o)}),Object.keys(t).length>0&&(a.messages=t)}Object.keys(a).length>0&&(s.layout=a)}return s}function B(e,i){let r=v(e),a=!!(i?.windowKey||i?.target)?{config:r,...i?.windowKey?{windowKey:i.windowKey}:{},...i?.target?{target:i.target}:{}}:r,t=JSON.stringify(a,null,0).replace(/'/g,"'");return`<script src="${w(i)}/install.global.js" data-config='${t}'></script>`}function Y(e,i){let r=i?.hooks,s=h(e),a=s!=="plain",t=w(i),n=["<!-- Load CSS -->",`<link rel="stylesheet" href="${t}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${t}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${c(i)}',`,...i?.windowKey?[` windowKey: '${i.windowKey}',`]:[]," config: {"];return e.apiUrl&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.agentId&&n.push(` agentId: "${e.agentId}",`),e.target&&n.push(` target: "${e.target}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),a&&n.push(` parserType: "${s}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(n,"theme",e.theme," "),e.launcher&&d(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([o,p])=>{n.push(` ${o}: "${p}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"?n.push(` ${o}: ${p},`):typeof p=="number"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([o,p])=>{n.push(` ${o}: ${p},`)}),n.push(" },")),n.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{n.push(` "${o}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...g(e," ")),n.push(...m(e," ",r)),n.push(...f(e," ")),n.push(...C(e," ")),n.push(...S(r," ")),e.debug&&n.push(` debug: ${e.debug},`),r?.postprocessMessage?n.push(` postprocessMessage: ${r.postprocessMessage}`):n.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),n.push(" }"),n.push(" });"),n.push("</script>"),n.join(`
|
|
78
|
+
`)}function U(e,i){let r=i?.hooks,s=v(e),t=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(s,null,2).split(`
|
|
78
79
|
`).map((n,o)=>o===0?n:" "+n).join(`
|
|
79
|
-
`)};`,""," // Constants",` var CDN_BASE = '${
|
|
80
|
+
`)};`,""," // Constants",` var CDN_BASE = '${w(i)}';`," 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 r?.getHeaders&&(t.push(` widgetConfig.getHeaders = ${r.getHeaders};`),t.push("")),r?.contextProviders&&(t.push(` widgetConfig.contextProviders = ${r.contextProviders};`),t.push("")),r?.streamParser?t.push(` widgetConfig.streamParser = ${r.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(""),r?.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` var customParsers = ${r.actionParsers};`),t.push(" widgetConfig.actionParsers = customParsers.concat(["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${O}`),t.push(" ]);")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" widgetConfig.actionParsers = ["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${O}`),t.push(" ];")),t.push(""),r?.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` var customHandlers = ${r.actionHandlers};`),t.push(" widgetConfig.actionHandlers = customHandlers.concat(["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${k}`),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(` ${k}`),t.push(" ];")),t.push(""),r?.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(` var customResult = (${r.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(""),r?.postprocessMessage?t.push(` widgetConfig.postprocessMessage = ${r.postprocessMessage};`):(t.push(" // Markdown postprocessor"),t.push(" widgetConfig.postprocessMessage = function(ctx) {"),t.push(" return agentWidget.markdownPostprocessor(ctx.text);"),t.push(" };")),t.push(""),(r?.onFeedback||r?.onCopy)&&(t.push(" // Message action callbacks"),t.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),r?.onFeedback&&t.push(` widgetConfig.messageActions.onFeedback = ${r.onFeedback};`),r?.onCopy&&t.push(` widgetConfig.messageActions.onCopy = ${r.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: '${c(i)}',`," useShadowDom: false,",...i?.windowKey?[` windowKey: '${i.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
81
|
`)}0&&(module.exports={generateCodeSnippet});
|