@usereq/widget 0.1.0 → 0.1.2
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 +7 -7
- package/dist/widget.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -26,12 +26,12 @@ This repo publishes **one npm package**: `@usereq/widget` (scoped; see `package.
|
|
|
26
26
|
|
|
27
27
|
These matter when you run **`bun run build`** (specifically the Vite embed step). Vite reads them from the repo root via `.env`, `.env.local`, `.env.production`, `.env.production.local`, and so on (see [Vite env files](https://vitejs.dev/guide/env-and-mode.html#env-files)). `vite build` uses mode **`production`**, so `.env.production` is the usual place for release API URLs.
|
|
28
28
|
|
|
29
|
-
| Variable
|
|
30
|
-
|
|
|
31
|
-
| `USEREQ_WIDGET_DEV_API_BASE` | Embed build | Highest-priority API origin (useful for dev-tag releases). If set, it overrides `USEREQ_WIDGET_API_BASE`.
|
|
32
|
-
| `USEREQ_WIDGET_API_BASE`
|
|
33
|
-
| `NEXT_PUBLIC_API_URL`
|
|
34
|
-
|
|
|
29
|
+
| Variable | When set | Effect |
|
|
30
|
+
| ---------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
31
|
+
| `USEREQ_WIDGET_DEV_API_BASE` | Embed build | Highest-priority API origin (useful for dev-tag releases). If set, it overrides `USEREQ_WIDGET_API_BASE`. |
|
|
32
|
+
| `USEREQ_WIDGET_API_BASE` | Embed build | Preferred API origin string inlined into `dist/widget.js` (no trailing slash normalization at build time; the runtime trims and strips trailing slashes). |
|
|
33
|
+
| `NEXT_PUBLIC_API_URL` | Embed build | Used only if `USEREQ_WIDGET_API_BASE` is empty—handy if you already define this in a Next.js monorepo. |
|
|
34
|
+
| _(neither set)_ | Embed build | Falls back to `http://localhost:3000` in the Vite config. |
|
|
35
35
|
|
|
36
36
|
**Runtime `globalThis` (advanced):** `getWidgetApiBase()` (see `src/runtime/api-origin.ts`) prefers the compile-time `__USEREQ_WIDGET_API_BASE__` value when it is non-empty after trimming. The Vite embed build always defines that symbol to a non-empty string (see defaults above), so **changing the API URL for the published `dist/widget.js` requires a rebuild with a different `USEREQ_WIDGET_API_BASE`**. The `globalThis.__USEREQ_WIDGET_API_BASE__` path mainly applies when consuming source from this package without inlining a base URL (for example your own bundler without that `define`). If nothing resolves, the function falls back to `http://localhost:4000`.
|
|
37
37
|
|
|
@@ -154,7 +154,7 @@ npm view @usereq/widget version
|
|
|
154
154
|
- **Publish** (`.github/workflows/publish.yml`): runs when you push tags matching:
|
|
155
155
|
- `v*` (for example `v0.2.0`) → publishes to npm default `latest` tag.
|
|
156
156
|
- `dev-v*` (for example `dev-v0.2.0-dev.1`) → publishes to npm `dev` dist-tag.
|
|
157
|
-
|
|
157
|
+
Configure repository secrets:
|
|
158
158
|
- **`NPM_TOKEN`** (required): npm automation token able to publish `@usereq/widget`.
|
|
159
159
|
- **`USEREQ_WIDGET_API_BASE`** (optional): production API base for normal `v*` releases.
|
|
160
160
|
- **`USEREQ_WIDGET_DEV_API_BASE`** (optional): dev API base used by `dev-v*` releases.
|
package/dist/widget.js
CHANGED
|
@@ -3469,7 +3469,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
|
|
|
3469
3469
|
max-width: none !important;
|
|
3470
3470
|
}
|
|
3471
3471
|
}
|
|
3472
|
-
`;function WHt(e){return typeof e=="number"&&!Number.isNaN(e)&&e>=0}function YHt(e,t){const r=document.getElementById(e);if(r instanceof HTMLElement)return t(r),()=>{};const i=document.body??document.documentElement;if(!i)return()=>{};let n=!1;const a=new MutationObserver(()=>{if(n)return;const s=document.getElementById(e);s instanceof HTMLElement&&(n=!0,a.disconnect(),t(s))});return a.observe(i,{childList:!0,subtree:!0}),()=>{n=!0,a.disconnect()}}function jHt(e){const[t,r]=(0,Ie.useState)(e==null);return(typeof window>"u"?Ie.useEffect:Ie.useLayoutEffect)(()=>{let i=!1;const n=()=>{i||r(!0)};if(!e)return r(!0),()=>{i=!0};r(!1);let a=()=>{};switch(e.triggerRuleType){case"time_delay":{if(!WHt(e.timeDelay))return n(),()=>{i=!0};const s=window.setTimeout(n,e.timeDelay*1e3);a=()=>{window.clearTimeout(s)};break}case"scroll_to_bottom":{if(!e.scrollToBottom)return n(),()=>{i=!0};const s=()=>{const o=window.scrollY,l=window.innerHeight,u=document.documentElement.scrollHeight;o+l>=u-1&&n()};s(),window.addEventListener("scroll",s,{passive:!0}),window.addEventListener("resize",s),a=()=>{window.removeEventListener("scroll",s),window.removeEventListener("resize",s)};break}case"element_displayed":{if(!e.elementDisplayed)return n(),()=>{i=!0};let s=null;const o=YHt(e.elementDisplayed,l=>{s=new IntersectionObserver(u=>{u.some(h=>h.isIntersecting)&&n()}),s.observe(l)});a=()=>{s?.disconnect(),o()};break}case"element_clicked":{if(!e.elementClicked)return n(),()=>{i=!0};const s=`#${CSS.escape(e.elementClicked)}`,o=l=>{const u=l.target;u instanceof Element&&u.closest(s)&&n()};document.addEventListener("click",o,!0),a=()=>{document.removeEventListener("click",o,!0)};break}default:return n(),()=>{i=!0}}return()=>{i=!0,a()}},[e]),{ready:t||e==null}}var XHt={default:Yet,box:zHt,chatbar:qHt};function KHt({mode:e,agentId:t,variant:r,placement:i,appearance:n,agentAvatarUrl:a,widgetTitle:s,spotlights:o,open:l,status:u,messages:h,errorMessage:d,triggerRule:f,emptyAction:p,sendDisabled:g=!1,onOpenChange:y,onSendMessage:b,onStopConversation:T,onConfirmationDecision:w,portalContainer:x,onWidgetVisible:C,onLinkClick:L,onLauncherClick:_}){const{ready:S}=jHt(f),{horizontal:A,vertical:P}=xoe(i),M=XHt[r]??Yet,O=QHt(e,i),U=a?.trim()||void 0,R=gft(h)!=null,F=R||u==="booting"||u==="sending",I=g||R||u==="booting",B=Ie.useRef(!1);return Ie.useEffect(()=>{e!=="embed"||!S||B.current||(B.current=!0,C?.(f?.triggerRuleType??null))},[e,C,S,f]),S?(0,Je.jsxs)(Je.Fragment,{children:[(0,Je.jsx)("style",{children:GHt}),(0,Je.jsx)("div",{"data-agent-id":t,"data-mode":e,"data-horizontal":A,"data-vertical":P,"data-variant":r,"data-open":String(l),"data-status":u,style:O,className:"widget-shell",children:(0,Je.jsx)("div",{style:{pointerEvents:"auto"},children:(0,Je.jsx)(M,{agentName:s,agentAvatarUrl:U,appearance:n,spotlightMessages:o,messages:h,status:u,errorMessage:d,emptyAction:p,sendDisabled:I,onSendMessage:b,open:l,onOpenChange:y,onStopConversation:T,stopDisabled:F,onConfirmationDecision:w,onLauncherClick:_,onLinkClick:L,portalContainer:x})})})]}):null}function QHt(e,t){const r={pointerEvents:"none"};if(e==="preview"){const{horizontal:i,vertical:n}=xoe(t);return Object.assign(r,{position:"relative",display:"flex",width:"100%",minHeight:"720px",padding:"24px",overflow:"hidden",alignItems:n==="top"?"flex-start":"flex-end",justifyContent:i==="left"?"flex-start":i==="center"?"center":"flex-end"}),r}switch(Object.assign(r,{position:"fixed",zIndex:2147483646}),t){case"top-left":Object.assign(r,{left:"24px",top:"24px"});break;case"top-center":Object.assign(r,{left:"50%",top:"24px",transform:"translateX(-50%)"});break;case"top-right":Object.assign(r,{right:"24px",top:"24px"});break;case"bottom-left":Object.assign(r,{left:"24px",bottom:"24px"});break;case"bottom-center":Object.assign(r,{left:"50%",bottom:"24px",transform:"translateX(-50%)"});break;default:Object.assign(r,{right:"24px",bottom:"24px"});break}return r}function Qet(e){const t=e?.trim();return t?t.replace(/\/+$/,""):null}function Zet(){const e="https://api-dev.usereq.com",t=globalThis.__USEREQ_WIDGET_API_BASE__;return Qet(e)??Qet(t)??"http://localhost:4000"}async function Vx(e,t){const r=await fetch(new URL(e,`${Zet()}/`).toString(),{...t,headers:{"Content-Type":"application/json",...t.headers??{}},credentials:"omit"}),i=await r.text(),n=i?JSON.parse(i):null;if(!r.ok)throw new Error(typeof n=="object"&&n&&"error"in n?String(n.error??r.statusText):r.statusText);return n}async function ZHt(e){return Vx("/api/widget/sessions",{method:"POST",body:JSON.stringify(e)})}async function JHt(e){return Vx("/api/conversations/public/start",{method:"POST",headers:{Authorization:`Bearer ${e.sessionToken}`},body:JSON.stringify({agentId:e.agentId})})}async function eVt(e){return Vx(`/api/conversations/public/${encodeURIComponent(e.conversationId)}/messages`,{method:"POST",headers:{Authorization:`Bearer ${e.sessionToken}`},body:JSON.stringify({content:e.content})})}async function tVt(e){return Vx(`/api/conversations/public/${encodeURIComponent(e.conversationId)}/messages`,{method:"POST",headers:{Authorization:`Bearer ${e.sessionToken}`},body:JSON.stringify({content:e.content})})}async function rVt(e){return Vx("/api/conversations/public/current",{method:"GET",headers:{Authorization:`Bearer ${e}`}})}async function iVt(e){const t=new URLSearchParams;return e.cursor&&t.set("cursor",e.cursor),Vx(`/api/conversations/public/${encodeURIComponent(e.conversationId)}/messages?${t.toString()}`,{method:"GET",headers:{Authorization:`Bearer ${e.sessionToken}`}})}function uae(e){return`usereq-widget:${e}`}function nVt(e){try{const t=sessionStorage.getItem(uae(e));if(!t)return null;const r=JSON.parse(t);return!r?.sessionToken||!r?.expiresAt||!r?.widgetConfig?.agentId||!r?.widgetConfig?.name?null:r}catch{return null}}function $I(e,t){sessionStorage.setItem(uae(e),JSON.stringify(t))}function aVt(e){sessionStorage.removeItem(uae(e))}function zI(e){return[...e].sort((t,r)=>new Date(t.createdAt).getTime()-new Date(r.createdAt).getTime())}var Jet={loadSession:nVt,saveSession:$I,mintWidgetSession:ZHt,getCurrentConversation:rVt,listConversationMessages:iVt,getOrigin:()=>window.location.origin,now:()=>Date.now()};function sVt(e,t=Date.now()){if(!e)return!1;const r=new Date(e.expiresAt).getTime();return Number.isFinite(r)&&r>t}async function UI(e,t=Jet,r){const i=t.loadSession(e.agentId),n=sVt(i,t.now());if(n&&!r?.refreshWidgetConfig)return i;if(n&&r?.refreshWidgetConfig)try{const o=await t.mintWidgetSession({agentId:e.agentId,origin:t.getOrigin(),pageUrl:e.pageUrl,referrer:e.referrer}),l={...i,widgetConfig:o.widgetConfig};return t.saveSession(e.agentId,l),l}catch{return i}const a=await t.mintWidgetSession({agentId:e.agentId,origin:t.getOrigin(),pageUrl:e.pageUrl,referrer:e.referrer}),s={sessionToken:a.sessionToken,expiresAt:a.expiresAt,widgetConfig:a.widgetConfig};return t.saveSession(e.agentId,s),s}async function oVt(e,t){const r=await UI(e,t,{refreshWidgetConfig:!0});let i=r.conversationId,n=[];if(i)try{n=zI((await t.listConversationMessages({conversationId:i,sessionToken:r.sessionToken})).data)}catch{i=void 0,n=[]}else try{i=(await t.getCurrentConversation(r.sessionToken)).conversation?.id??void 0,i&&(n=zI((await t.listConversationMessages({conversationId:i,sessionToken:r.sessionToken})).data))}catch{i=void 0,n=[]}const a={...r,conversationId:i};return t.saveSession(e.agentId,a),{session:a,conversationId:i,messages:n}}async function lVt(e){return oVt(e,Jet)}async function cVt(e){const t=await UI({agentId:e.agentId,pageUrl:window.location.href,referrer:document.referrer||void 0});if(!t.conversationId)throw new Error("Widget conversation not started");const r=await eVt({conversationId:t.conversationId,sessionToken:t.sessionToken,content:e.content}),i={...t,conversationId:t.conversationId};return $I(e.agentId,i),{session:i,conversationId:t.conversationId,messages:zI([r.userMessage,...r.assistantMessages]),userMessage:r.userMessage,assistantMessages:r.assistantMessages}}async function ett(e){const t=await UI({agentId:e.agentId,pageUrl:window.location.href,referrer:document.referrer||void 0});if(!t.conversationId)throw new Error("Widget conversation not started");const r=e.decision!=null?fft({confirmationId:e.confirmationId,decision:e.decision}):dft({confirmationId:e.confirmationId,prompt:e.prompt}),i=await tVt({conversationId:t.conversationId,sessionToken:t.sessionToken,content:r}),n={...t,conversationId:t.conversationId};return $I(e.agentId,n),{session:n,conversationId:t.conversationId,confirmationMessage:i.confirmationMessage}}async function uVt(e){const t=await UI({agentId:e.agentId,pageUrl:window.location.href,referrer:document.referrer||void 0}),r=await JHt({agentId:e.agentId,sessionToken:t.sessionToken}),i={...t,conversationId:r.conversation.id};return $I(e.agentId,i),{session:i,conversationId:r.conversation.id,messages:zI([r.welcomeMessage]),welcomeMessage:r.welcomeMessage}}async function hVt(e){aVt(e)}var dVt="/api/widget/events/batch",fVt=10,pVt=2500,ttt="usereq-widget:unique-script-loaded:",gVt=class{mode;agentId;getSession;getConversationId;batchSize;flushIntervalMs;uniqueScriptSeen=new Set;flushTimer=null;queue=[];disposed=!1;constructor(e){this.mode=e.mode,this.agentId=e.agentId,this.getSession=e.getSession,this.getConversationId=e.getConversationId,this.batchSize=Math.max(1,e.batchSize??fVt),this.flushIntervalMs=Math.max(200,e.flushIntervalMs??pVt),this.mode==="embed"&&(window.addEventListener("pagehide",this.handlePageHide,{capture:!0}),document.addEventListener("visibilitychange",this.handleVisibilityChange,!0))}dispose(){this.disposed||(this.disposed=!0,this.clearFlushTimer(),window.removeEventListener("pagehide",this.handlePageHide,!0),document.removeEventListener("visibilitychange",this.handleVisibilityChange,!0),this.flush({transport:"beacon"}))}trackScriptLoaded(){this.track({eventType:"SCRIPT_LOADED"})}trackUniqueScriptLoaded(){const e=this.getSession()?.sessionToken?.trim();if(!e)return;const t=`${this.agentId}:${e}`;if(!this.uniqueScriptSeen.has(t)){if(this.hasSessionUniqueScriptLoaded(t)){this.uniqueScriptSeen.add(t);return}this.uniqueScriptSeen.add(t),this.setSessionUniqueScriptLoaded(t),this.track({eventType:"UNIQUE_SCRIPT_LOADED"})}}trackView(e){this.track({eventType:"VIEW",triggerRuleType:e}),e==="element_displayed"&&this.track({eventType:"DISPLAY_AFTER_ELEMENT_SHOWED",triggerRuleType:e})}trackClick(){this.track({eventType:"CLICK"})}trackLinkClicked(e){const t=e.trim();if(!t)return;const r=this.normalizeLinkUrl(t);this.track({eventType:"LINK_CLICKED",linkUrl:r})}track(e){if(this.disposed||this.mode!=="embed")return;const t=this.getSession()?.sessionToken?.trim();if(!t)return;const{occurredAt:r,conversationId:i,triggerRuleType:n,linkUrl:a,...s}=e,o=i??this.getConversationId(),l={...s,occurredAt:r??new Date().toISOString(),...o?{conversationId:o}:{},...n?{triggerRuleType:n}:{},...a?{linkUrl:a}:{}};if(this.queue.push({event:l,sessionToken:t}),this.queue.length>=this.batchSize){this.flush();return}this.scheduleFlush()}async flush(e){if(this.disposed||this.queue.length===0)return;this.clearFlushTimer();const t=e?.transport??"default",r=this.queue;this.queue=[];const i=new Map;for(const a of r){const s=i.get(a.sessionToken);s?s.push(a.event):i.set(a.sessionToken,[a.event])}const n=[];for(const[a,s]of i.entries())if(!await this.sendBatch({events:s,sessionToken:a,transport:t}))for(const o of s)n.push({event:o,sessionToken:a});n.length>0&&(this.queue=[...n,...this.queue],this.scheduleFlush())}async sendBatch(e){if(e.events.length===0)return!0;const t=new URL(dVt,`${Zet()}/`).toString(),r={events:e.events.map(i=>{const{conversationId:n,triggerRuleType:a,linkUrl:s,...o}=i;return{...o,...n?{conversationId:n}:{},...a?{triggerRuleType:a}:{},...s?{linkUrl:s}:{}}}),pageUrl:window.location.href,referrer:document.referrer||void 0,sessionToken:e.sessionToken};if(e.transport==="beacon"&&typeof navigator.sendBeacon=="function"){const i=new Blob([JSON.stringify(r)],{type:"application/json"});if(navigator.sendBeacon(t,i))return!0}try{return(await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.sessionToken}`,"Content-Type":"application/json"},body:JSON.stringify(r),credentials:"omit",keepalive:e.transport==="beacon"})).ok}catch{return!1}}scheduleFlush(){this.flushTimer==null&&(this.flushTimer=window.setTimeout(()=>{this.flushTimer=null,this.flush()},this.flushIntervalMs))}clearFlushTimer(){this.flushTimer!=null&&(window.clearTimeout(this.flushTimer),this.flushTimer=null)}hasSessionUniqueScriptLoaded(e){try{return sessionStorage.getItem(`${ttt}${e}`)==="1"}catch{return!1}}setSessionUniqueScriptLoaded(e){try{sessionStorage.setItem(`${ttt}${e}`,"1")}catch{}}handlePageHide=()=>{this.flush({transport:"beacon"})};handleVisibilityChange=()=>{document.visibilityState==="hidden"&&this.flush({transport:"beacon"})};normalizeLinkUrl(e){try{return new URL(e,window.location.href).toString()}catch{return e}}};function mVt(e){return new gVt(e)}var yVt=`
|
|
3472
|
+
`;function WHt(e){return typeof e=="number"&&!Number.isNaN(e)&&e>=0}function YHt(e,t){const r=document.getElementById(e);if(r instanceof HTMLElement)return t(r),()=>{};const i=document.body??document.documentElement;if(!i)return()=>{};let n=!1;const a=new MutationObserver(()=>{if(n)return;const s=document.getElementById(e);s instanceof HTMLElement&&(n=!0,a.disconnect(),t(s))});return a.observe(i,{childList:!0,subtree:!0}),()=>{n=!0,a.disconnect()}}function jHt(e){const[t,r]=(0,Ie.useState)(e==null);return(typeof window>"u"?Ie.useEffect:Ie.useLayoutEffect)(()=>{let i=!1;const n=()=>{i||r(!0)};if(!e)return r(!0),()=>{i=!0};r(!1);let a=()=>{};switch(e.triggerRuleType){case"time_delay":{if(!WHt(e.timeDelay))return n(),()=>{i=!0};const s=window.setTimeout(n,e.timeDelay*1e3);a=()=>{window.clearTimeout(s)};break}case"scroll_to_bottom":{if(!e.scrollToBottom)return n(),()=>{i=!0};const s=()=>{const o=window.scrollY,l=window.innerHeight,u=document.documentElement.scrollHeight;o+l>=u-1&&n()};s(),window.addEventListener("scroll",s,{passive:!0}),window.addEventListener("resize",s),a=()=>{window.removeEventListener("scroll",s),window.removeEventListener("resize",s)};break}case"element_displayed":{if(!e.elementDisplayed)return n(),()=>{i=!0};let s=null;const o=YHt(e.elementDisplayed,l=>{s=new IntersectionObserver(u=>{u.some(h=>h.isIntersecting)&&n()}),s.observe(l)});a=()=>{s?.disconnect(),o()};break}case"element_clicked":{if(!e.elementClicked)return n(),()=>{i=!0};const s=`#${CSS.escape(e.elementClicked)}`,o=l=>{const u=l.target;u instanceof Element&&u.closest(s)&&n()};document.addEventListener("click",o,!0),a=()=>{document.removeEventListener("click",o,!0)};break}default:return n(),()=>{i=!0}}return()=>{i=!0,a()}},[e]),{ready:t||e==null}}var XHt={default:Yet,box:zHt,chatbar:qHt};function KHt({mode:e,agentId:t,variant:r,placement:i,appearance:n,agentAvatarUrl:a,widgetTitle:s,spotlights:o,open:l,status:u,messages:h,errorMessage:d,triggerRule:f,emptyAction:p,sendDisabled:g=!1,onOpenChange:y,onSendMessage:b,onStopConversation:T,onConfirmationDecision:w,portalContainer:x,onWidgetVisible:C,onLinkClick:L,onLauncherClick:_}){const{ready:S}=jHt(f),{horizontal:A,vertical:P}=xoe(i),M=XHt[r]??Yet,O=QHt(e,i),U=a?.trim()||void 0,R=gft(h)!=null,F=R||u==="booting"||u==="sending",I=g||R||u==="booting",B=Ie.useRef(!1);return Ie.useEffect(()=>{e!=="embed"||!S||B.current||(B.current=!0,C?.(f?.triggerRuleType??null))},[e,C,S,f]),S?(0,Je.jsxs)(Je.Fragment,{children:[(0,Je.jsx)("style",{children:GHt}),(0,Je.jsx)("div",{"data-agent-id":t,"data-mode":e,"data-horizontal":A,"data-vertical":P,"data-variant":r,"data-open":String(l),"data-status":u,style:O,className:"widget-shell",children:(0,Je.jsx)("div",{style:{pointerEvents:"auto"},children:(0,Je.jsx)(M,{agentName:s,agentAvatarUrl:U,appearance:n,spotlightMessages:o,messages:h,status:u,errorMessage:d,emptyAction:p,sendDisabled:I,onSendMessage:b,open:l,onOpenChange:y,onStopConversation:T,stopDisabled:F,onConfirmationDecision:w,onLauncherClick:_,onLinkClick:L,portalContainer:x})})})]}):null}function QHt(e,t){const r={pointerEvents:"none"};if(e==="preview"){const{horizontal:i,vertical:n}=xoe(t);return Object.assign(r,{position:"relative",display:"flex",width:"100%",minHeight:"720px",padding:"24px",overflow:"hidden",alignItems:n==="top"?"flex-start":"flex-end",justifyContent:i==="left"?"flex-start":i==="center"?"center":"flex-end"}),r}switch(Object.assign(r,{position:"fixed",zIndex:2147483646}),t){case"top-left":Object.assign(r,{left:"24px",top:"24px"});break;case"top-center":Object.assign(r,{left:"50%",top:"24px",transform:"translateX(-50%)"});break;case"top-right":Object.assign(r,{right:"24px",top:"24px"});break;case"bottom-left":Object.assign(r,{left:"24px",bottom:"24px"});break;case"bottom-center":Object.assign(r,{left:"50%",bottom:"24px",transform:"translateX(-50%)"});break;default:Object.assign(r,{right:"24px",bottom:"24px"});break}return r}function Qet(e){const t=e?.trim();return t?t.replace(/\/+$/,""):null}function Zet(){const e="https://api.usereq.com",t=globalThis.__USEREQ_WIDGET_API_BASE__;return Qet(e)??Qet(t)??"http://localhost:4000"}async function Vx(e,t){const r=await fetch(new URL(e,`${Zet()}/`).toString(),{...t,headers:{"Content-Type":"application/json",...t.headers??{}},credentials:"omit"}),i=await r.text(),n=i?JSON.parse(i):null;if(!r.ok)throw new Error(typeof n=="object"&&n&&"error"in n?String(n.error??r.statusText):r.statusText);return n}async function ZHt(e){return Vx("/api/widget/sessions",{method:"POST",body:JSON.stringify(e)})}async function JHt(e){return Vx("/api/conversations/public/start",{method:"POST",headers:{Authorization:`Bearer ${e.sessionToken}`},body:JSON.stringify({agentId:e.agentId})})}async function eVt(e){return Vx(`/api/conversations/public/${encodeURIComponent(e.conversationId)}/messages`,{method:"POST",headers:{Authorization:`Bearer ${e.sessionToken}`},body:JSON.stringify({content:e.content})})}async function tVt(e){return Vx(`/api/conversations/public/${encodeURIComponent(e.conversationId)}/messages`,{method:"POST",headers:{Authorization:`Bearer ${e.sessionToken}`},body:JSON.stringify({content:e.content})})}async function rVt(e){return Vx("/api/conversations/public/current",{method:"GET",headers:{Authorization:`Bearer ${e}`}})}async function iVt(e){const t=new URLSearchParams;return e.cursor&&t.set("cursor",e.cursor),Vx(`/api/conversations/public/${encodeURIComponent(e.conversationId)}/messages?${t.toString()}`,{method:"GET",headers:{Authorization:`Bearer ${e.sessionToken}`}})}function uae(e){return`usereq-widget:${e}`}function nVt(e){try{const t=sessionStorage.getItem(uae(e));if(!t)return null;const r=JSON.parse(t);return!r?.sessionToken||!r?.expiresAt||!r?.widgetConfig?.agentId||!r?.widgetConfig?.name?null:r}catch{return null}}function $I(e,t){sessionStorage.setItem(uae(e),JSON.stringify(t))}function aVt(e){sessionStorage.removeItem(uae(e))}function zI(e){return[...e].sort((t,r)=>new Date(t.createdAt).getTime()-new Date(r.createdAt).getTime())}var Jet={loadSession:nVt,saveSession:$I,mintWidgetSession:ZHt,getCurrentConversation:rVt,listConversationMessages:iVt,getOrigin:()=>window.location.origin,now:()=>Date.now()};function sVt(e,t=Date.now()){if(!e)return!1;const r=new Date(e.expiresAt).getTime();return Number.isFinite(r)&&r>t}async function UI(e,t=Jet,r){const i=t.loadSession(e.agentId),n=sVt(i,t.now());if(n&&!r?.refreshWidgetConfig)return i;if(n&&r?.refreshWidgetConfig)try{const o=await t.mintWidgetSession({agentId:e.agentId,origin:t.getOrigin(),pageUrl:e.pageUrl,referrer:e.referrer}),l={...i,widgetConfig:o.widgetConfig};return t.saveSession(e.agentId,l),l}catch{return i}const a=await t.mintWidgetSession({agentId:e.agentId,origin:t.getOrigin(),pageUrl:e.pageUrl,referrer:e.referrer}),s={sessionToken:a.sessionToken,expiresAt:a.expiresAt,widgetConfig:a.widgetConfig};return t.saveSession(e.agentId,s),s}async function oVt(e,t){const r=await UI(e,t,{refreshWidgetConfig:!0});let i=r.conversationId,n=[];if(i)try{n=zI((await t.listConversationMessages({conversationId:i,sessionToken:r.sessionToken})).data)}catch{i=void 0,n=[]}else try{i=(await t.getCurrentConversation(r.sessionToken)).conversation?.id??void 0,i&&(n=zI((await t.listConversationMessages({conversationId:i,sessionToken:r.sessionToken})).data))}catch{i=void 0,n=[]}const a={...r,conversationId:i};return t.saveSession(e.agentId,a),{session:a,conversationId:i,messages:n}}async function lVt(e){return oVt(e,Jet)}async function cVt(e){const t=await UI({agentId:e.agentId,pageUrl:window.location.href,referrer:document.referrer||void 0});if(!t.conversationId)throw new Error("Widget conversation not started");const r=await eVt({conversationId:t.conversationId,sessionToken:t.sessionToken,content:e.content}),i={...t,conversationId:t.conversationId};return $I(e.agentId,i),{session:i,conversationId:t.conversationId,messages:zI([r.userMessage,...r.assistantMessages]),userMessage:r.userMessage,assistantMessages:r.assistantMessages}}async function ett(e){const t=await UI({agentId:e.agentId,pageUrl:window.location.href,referrer:document.referrer||void 0});if(!t.conversationId)throw new Error("Widget conversation not started");const r=e.decision!=null?fft({confirmationId:e.confirmationId,decision:e.decision}):dft({confirmationId:e.confirmationId,prompt:e.prompt}),i=await tVt({conversationId:t.conversationId,sessionToken:t.sessionToken,content:r}),n={...t,conversationId:t.conversationId};return $I(e.agentId,n),{session:n,conversationId:t.conversationId,confirmationMessage:i.confirmationMessage}}async function uVt(e){const t=await UI({agentId:e.agentId,pageUrl:window.location.href,referrer:document.referrer||void 0}),r=await JHt({agentId:e.agentId,sessionToken:t.sessionToken}),i={...t,conversationId:r.conversation.id};return $I(e.agentId,i),{session:i,conversationId:r.conversation.id,messages:zI([r.welcomeMessage]),welcomeMessage:r.welcomeMessage}}async function hVt(e){aVt(e)}var dVt="/api/widget/events/batch",fVt=10,pVt=2500,ttt="usereq-widget:unique-script-loaded:",gVt=class{mode;agentId;getSession;getConversationId;batchSize;flushIntervalMs;uniqueScriptSeen=new Set;flushTimer=null;queue=[];disposed=!1;constructor(e){this.mode=e.mode,this.agentId=e.agentId,this.getSession=e.getSession,this.getConversationId=e.getConversationId,this.batchSize=Math.max(1,e.batchSize??fVt),this.flushIntervalMs=Math.max(200,e.flushIntervalMs??pVt),this.mode==="embed"&&(window.addEventListener("pagehide",this.handlePageHide,{capture:!0}),document.addEventListener("visibilitychange",this.handleVisibilityChange,!0))}dispose(){this.disposed||(this.disposed=!0,this.clearFlushTimer(),window.removeEventListener("pagehide",this.handlePageHide,!0),document.removeEventListener("visibilitychange",this.handleVisibilityChange,!0),this.flush({transport:"beacon"}))}trackScriptLoaded(){this.track({eventType:"SCRIPT_LOADED"})}trackUniqueScriptLoaded(){const e=this.getSession()?.sessionToken?.trim();if(!e)return;const t=`${this.agentId}:${e}`;if(!this.uniqueScriptSeen.has(t)){if(this.hasSessionUniqueScriptLoaded(t)){this.uniqueScriptSeen.add(t);return}this.uniqueScriptSeen.add(t),this.setSessionUniqueScriptLoaded(t),this.track({eventType:"UNIQUE_SCRIPT_LOADED"})}}trackView(e){this.track({eventType:"VIEW",triggerRuleType:e}),e==="element_displayed"&&this.track({eventType:"DISPLAY_AFTER_ELEMENT_SHOWED",triggerRuleType:e})}trackClick(){this.track({eventType:"CLICK"})}trackLinkClicked(e){const t=e.trim();if(!t)return;const r=this.normalizeLinkUrl(t);this.track({eventType:"LINK_CLICKED",linkUrl:r})}track(e){if(this.disposed||this.mode!=="embed")return;const t=this.getSession()?.sessionToken?.trim();if(!t)return;const{occurredAt:r,conversationId:i,triggerRuleType:n,linkUrl:a,...s}=e,o=i??this.getConversationId(),l={...s,occurredAt:r??new Date().toISOString(),...o?{conversationId:o}:{},...n?{triggerRuleType:n}:{},...a?{linkUrl:a}:{}};if(this.queue.push({event:l,sessionToken:t}),this.queue.length>=this.batchSize){this.flush();return}this.scheduleFlush()}async flush(e){if(this.disposed||this.queue.length===0)return;this.clearFlushTimer();const t=e?.transport??"default",r=this.queue;this.queue=[];const i=new Map;for(const a of r){const s=i.get(a.sessionToken);s?s.push(a.event):i.set(a.sessionToken,[a.event])}const n=[];for(const[a,s]of i.entries())if(!await this.sendBatch({events:s,sessionToken:a,transport:t}))for(const o of s)n.push({event:o,sessionToken:a});n.length>0&&(this.queue=[...n,...this.queue],this.scheduleFlush())}async sendBatch(e){if(e.events.length===0)return!0;const t=new URL(dVt,`${Zet()}/`).toString(),r={events:e.events.map(i=>{const{conversationId:n,triggerRuleType:a,linkUrl:s,...o}=i;return{...o,...n?{conversationId:n}:{},...a?{triggerRuleType:a}:{},...s?{linkUrl:s}:{}}}),pageUrl:window.location.href,referrer:document.referrer||void 0,sessionToken:e.sessionToken};if(e.transport==="beacon"&&typeof navigator.sendBeacon=="function"){const i=new Blob([JSON.stringify(r)],{type:"application/json"});if(navigator.sendBeacon(t,i))return!0}try{return(await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.sessionToken}`,"Content-Type":"application/json"},body:JSON.stringify(r),credentials:"omit",keepalive:e.transport==="beacon"})).ok}catch{return!1}}scheduleFlush(){this.flushTimer==null&&(this.flushTimer=window.setTimeout(()=>{this.flushTimer=null,this.flush()},this.flushIntervalMs))}clearFlushTimer(){this.flushTimer!=null&&(window.clearTimeout(this.flushTimer),this.flushTimer=null)}hasSessionUniqueScriptLoaded(e){try{return sessionStorage.getItem(`${ttt}${e}`)==="1"}catch{return!1}}setSessionUniqueScriptLoaded(e){try{sessionStorage.setItem(`${ttt}${e}`,"1")}catch{}}handlePageHide=()=>{this.flush({transport:"beacon"})};handleVisibilityChange=()=>{document.visibilityState==="hidden"&&this.flush({transport:"beacon"})};normalizeLinkUrl(e){try{return new URL(e,window.location.href).toString()}catch{return e}}};function mVt(e){return new gVt(e)}var yVt=`
|
|
3473
3473
|
:host {
|
|
3474
3474
|
color-scheme: light;
|
|
3475
3475
|
--tw-border-style: solid;
|
package/package.json
CHANGED