advocate-widget 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Economic Data Sciences
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,51 @@
1
+ # advocate-widget
2
+
3
+ A lightweight chat widget that helps your website visitors decide to buy. AI-powered, conversion-focused.
4
+
5
+ - Under 5kb gzipped
6
+ - No dependencies
7
+ - Shadow DOM isolates styles from your site
8
+ - TypeScript types included
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ npm install advocate-widget
14
+ ```
15
+
16
+ ## Usage
17
+
18
+ ```javascript
19
+ import { init } from 'advocate-widget';
20
+
21
+ const advocate = init({
22
+ siteKey: 'pk_live_xxxxx',
23
+ position: 'bottom-right',
24
+ global: false,
25
+ });
26
+
27
+ // Track conversions
28
+ advocate.trackConversion({ type: 'signup', value: 9.99 });
29
+ ```
30
+
31
+ ## Options
32
+
33
+ | Option | Type | Default | Description |
34
+ |--------|------|---------|-------------|
35
+ | `siteKey` | string | — | Your publishable API key (required) |
36
+ | `position` | `'bottom-right'` \| `'bottom-left'` | `'bottom-right'` | Widget position |
37
+ | `delay` | number | `0` | Milliseconds before widget appears |
38
+ | `greeting` | string | — | Header greeting text (fetched from config if omitted) |
39
+ | `global` | boolean | `true` | Attach instance to `window.Advocate` |
40
+ | `cta.text` | string | — | Call-to-action button text |
41
+ | `cta.url` | string | — | Call-to-action URL |
42
+
43
+ ## Global vs Scoped
44
+
45
+ By default, the widget attaches to `window.Advocate`. Set `global: false` to get a scoped reference instead — useful in bundled apps where globals are discouraged.
46
+
47
+ See the [full documentation](https://github.com/economicdatasciences/advocate-widget#readme) for details.
48
+
49
+ ## License
50
+
51
+ MIT
@@ -0,0 +1,29 @@
1
+ export interface AdvocateConfig {
2
+ siteKey: string;
3
+ position?: 'bottom-right' | 'bottom-left';
4
+ delay?: number;
5
+ greeting?: string;
6
+ global?: boolean;
7
+ context?: AdvocateContext;
8
+ cta?: {
9
+ text: string;
10
+ url: string;
11
+ };
12
+ }
13
+
14
+ export interface AdvocateContext {
15
+ page?: string;
16
+ [key: string]: string | undefined;
17
+ }
18
+
19
+ export interface AdvocateInstance {
20
+ trackConversion(event: ConversionEvent): void;
21
+ setContext(context: AdvocateContext): void;
22
+ }
23
+
24
+ export interface ConversionEvent {
25
+ type: string;
26
+ value?: number;
27
+ }
28
+
29
+ export declare function init(config: AdvocateConfig): AdvocateInstance | undefined;
package/dist/index.js ADDED
@@ -0,0 +1,277 @@
1
+ "use strict";var h=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var y=(i,e)=>{for(var a in e)h(i,a,{get:e[a],enumerable:!0})},w=(i,e,a,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of b(e))!x.call(i,n)&&n!==a&&h(i,n,{get:()=>e[n],enumerable:!(t=v(e,n))||t.enumerable});return i};var C=i=>w(h({},"__esModule",{value:!0}),i);var S={};y(S,{init:()=>m});module.exports=C(S);var u=`:host {
2
+ all: initial;
3
+ position: fixed;
4
+ z-index: 2147483647;
5
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
6
+ }
7
+
8
+ :host([data-position="bottom-right"]) { bottom: 20px; right: 20px; }
9
+ :host([data-position="bottom-left"]) { bottom: 20px; left: 20px; }
10
+
11
+ .advocate-trigger {
12
+ width: 56px;
13
+ height: 56px;
14
+ border-radius: 50%;
15
+ background: #2563eb;
16
+ border: none;
17
+ cursor: pointer;
18
+ display: flex;
19
+ align-items: center;
20
+ justify-content: center;
21
+ box-shadow: 0 4px 12px rgba(0,0,0,0.15);
22
+ transition: transform 0.2s;
23
+ }
24
+
25
+ .advocate-trigger:hover { transform: scale(1.05); }
26
+
27
+ .advocate-panel {
28
+ display: flex;
29
+ flex-direction: column;
30
+ position: absolute;
31
+ bottom: 72px;
32
+ right: 0;
33
+ width: min(360px, calc(100vw - 40px));
34
+ max-height: 500px;
35
+ border-radius: 12px;
36
+ background: #fff;
37
+ box-shadow: 0 8px 32px rgba(0,0,0,0.12);
38
+ overflow: hidden;
39
+ opacity: 0;
40
+ transform: translateY(8px);
41
+ pointer-events: none;
42
+ transition: opacity 0.2s ease, transform 0.2s ease;
43
+ }
44
+
45
+ .advocate-panel.open {
46
+ opacity: 1;
47
+ transform: translateY(0);
48
+ pointer-events: auto;
49
+ }
50
+
51
+ .advocate-header {
52
+ padding: 16px;
53
+ background: #2563eb;
54
+ color: #fff;
55
+ font-size: 14px;
56
+ font-weight: 600;
57
+ }
58
+
59
+ .advocate-messages {
60
+ flex: 1;
61
+ overflow-y: auto;
62
+ padding: 16px;
63
+ display: flex;
64
+ flex-direction: column;
65
+ gap: 8px;
66
+ }
67
+
68
+ .advocate-bubble {
69
+ max-width: 75%;
70
+ padding: 10px 14px;
71
+ border-radius: 12px;
72
+ font-size: 14px;
73
+ line-height: 1.4;
74
+ word-break: break-word;
75
+ }
76
+
77
+ .advocate-bubble--user {
78
+ align-self: flex-end;
79
+ background: #2563eb;
80
+ color: #fff;
81
+ border-bottom-right-radius: 4px;
82
+ }
83
+
84
+ .advocate-bubble--assistant {
85
+ align-self: flex-start;
86
+ background: #f1f5f9;
87
+ color: #1e293b;
88
+ border-bottom-left-radius: 4px;
89
+ }
90
+
91
+ .advocate-footer {
92
+ padding: 8px 16px;
93
+ text-align: center;
94
+ font-size: 11px;
95
+ color: #94a3b8;
96
+ border-top: 1px solid #f1f5f9;
97
+ }
98
+
99
+ .advocate-footer a {
100
+ color: #2563eb;
101
+ text-decoration: none;
102
+ }
103
+
104
+ .advocate-input {
105
+ display: flex;
106
+ border-top: 1px solid #e5e7eb;
107
+ padding: 12px;
108
+ }
109
+
110
+ .advocate-input input {
111
+ flex: 1;
112
+ border: 1px solid #e5e7eb;
113
+ border-radius: 8px;
114
+ padding: 8px 12px;
115
+ font-size: 14px;
116
+ outline: none;
117
+ }
118
+
119
+ .advocate-input button {
120
+ margin-left: 8px;
121
+ background: #2563eb;
122
+ color: #fff;
123
+ border: none;
124
+ border-radius: 8px;
125
+ padding: 8px 12px;
126
+ cursor: pointer;
127
+ font-size: 14px;
128
+ transition: opacity 0.15s;
129
+ }
130
+
131
+ .advocate-input input:disabled,
132
+ .advocate-input button:disabled {
133
+ opacity: 0.5;
134
+ cursor: not-allowed;
135
+ }
136
+
137
+ @media (max-width: 767px) {
138
+ :host {
139
+ bottom: 0 !important;
140
+ right: 0 !important;
141
+ left: 0 !important;
142
+ top: 0 !important;
143
+ width: 100% !important;
144
+ height: 100% !important;
145
+ position: fixed !important;
146
+ }
147
+
148
+ .advocate-trigger {
149
+ position: fixed;
150
+ bottom: 20px;
151
+ right: 20px;
152
+ }
153
+
154
+ .advocate-panel {
155
+ position: fixed;
156
+ inset: 0;
157
+ width: 100%;
158
+ height: 100%;
159
+ max-height: 100%;
160
+ border-radius: 0;
161
+ transition: none;
162
+ transform: none;
163
+ clip-path: polygon(92% 96%, 100% 96%, 100% 100%, 92% 100%);
164
+ opacity: 0;
165
+ pointer-events: none;
166
+ }
167
+
168
+ .advocate-panel.open {
169
+ animation: advocate-genie-open 0.45s cubic-bezier(0.2, 0.8, 0.3, 1) forwards;
170
+ opacity: 1;
171
+ pointer-events: auto;
172
+ transform: none;
173
+ }
174
+
175
+ .advocate-panel.closing {
176
+ animation: advocate-genie-close 0.35s cubic-bezier(0.7, 0, 0.8, 0.2) forwards;
177
+ pointer-events: none;
178
+ }
179
+
180
+ .advocate-messages {
181
+ flex: 1;
182
+ overflow-y: auto;
183
+ -webkit-overflow-scrolling: touch;
184
+ }
185
+
186
+ .advocate-input {
187
+ position: sticky;
188
+ bottom: 0;
189
+ background: #fff;
190
+ }
191
+
192
+ .advocate-header {
193
+ display: flex;
194
+ align-items: center;
195
+ justify-content: space-between;
196
+ }
197
+
198
+ .advocate-close {
199
+ background: none;
200
+ border: none;
201
+ color: #fff;
202
+ font-size: 22px;
203
+ line-height: 1;
204
+ cursor: pointer;
205
+ padding: 0 4px;
206
+ opacity: 0.85;
207
+ }
208
+
209
+ .advocate-close:hover { opacity: 1; }
210
+ }
211
+
212
+ @keyframes advocate-genie-open {
213
+ 0% { clip-path: polygon(92% 96%, 100% 96%, 100% 100%, 92% 100%); opacity: 1; }
214
+ 35% { clip-path: polygon(25% 35%, 100% 15%, 100% 100%, 0% 100%); }
215
+ 65% { clip-path: polygon(0% 3%, 100% 0%, 100% 100%, 0% 100%); }
216
+ 100% { clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%); }
217
+ }
218
+
219
+ @keyframes advocate-genie-close {
220
+ 0% { clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%); opacity: 1; }
221
+ 35% { clip-path: polygon(0% 3%, 100% 0%, 100% 100%, 0% 100%); }
222
+ 65% { clip-path: polygon(25% 35%, 100% 15%, 100% 100%, 0% 100%); }
223
+ 100% { clip-path: polygon(92% 96%, 100% 96%, 100% 100%, 92% 100%); opacity: 0; }
224
+ }
225
+
226
+ @media (min-width: 768px) {
227
+ .advocate-close { display: none; }
228
+ }
229
+
230
+ .advocate-bubble--assistant p { margin: 0 0 4px; }
231
+ .advocate-bubble--assistant p:last-child { margin-bottom: 0; }
232
+ .advocate-bubble--assistant ul { margin: 4px 0; padding-left: 18px; }
233
+ .advocate-bubble--assistant li { margin-bottom: 2px; }
234
+ .advocate-bubble--assistant a { color: #2563eb; text-decoration: underline; }
235
+ .advocate-bubble--assistant strong { font-weight: 600; }
236
+
237
+ .advocate-typing {
238
+ display: flex;
239
+ align-items: center;
240
+ gap: 4px;
241
+ padding: 10px 14px;
242
+ }
243
+
244
+ .advocate-typing span {
245
+ width: 6px;
246
+ height: 6px;
247
+ border-radius: 50%;
248
+ background: #94a3b8;
249
+ animation: advocate-bounce 1.2s infinite;
250
+ }
251
+
252
+ .advocate-typing span:nth-child(2) { animation-delay: 0.2s; }
253
+ .advocate-typing span:nth-child(3) { animation-delay: 0.4s; }
254
+
255
+ .advocate-cta {
256
+ display: inline-block;
257
+ align-self: flex-start;
258
+ margin-top: 2px;
259
+ padding: 8px 14px;
260
+ background: #2563eb;
261
+ color: #fff;
262
+ border-radius: 8px;
263
+ font-size: 13px;
264
+ font-weight: 600;
265
+ text-decoration: none;
266
+ transition: opacity 0.15s;
267
+ }
268
+
269
+ .advocate-cta:hover { opacity: 0.88; }
270
+
271
+ @keyframes advocate-bounce {
272
+ 0%, 60%, 100% { transform: translateY(0); }
273
+ 30% { transform: translateY(-6px); }
274
+ }
275
+ `;function E(){let i=[],e=document.title?.trim();e&&i.push(`Title: ${e}`);let a=document.querySelector('meta[name="description"]')?.content?.trim()||document.querySelector('meta[property="og:description"]')?.content?.trim();a&&i.push(`Description: ${a}`);let t=Array.from(document.querySelectorAll("h1, h2, h3")).slice(0,5).map(n=>n.textContent?.trim()).filter(Boolean);return t.length&&i.push(`Headings: ${t.map(n=>n.slice(0,80)).join(" | ")}`),i.length?i.join(`
276
+ `).slice(0,400):null}function M(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function f(i){return M(i).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener">$1</a>')}function T(i){let e=i.split(`
277
+ `),a=[],t=!1;for(let n of e){let s=n.match(/^[-*]\s+(.+)/);s?(t||(a.push("<ul>"),t=!0),a.push(`<li>${f(s[1])}</li>`)):(t&&(a.push("</ul>"),t=!1),n.trim()&&a.push(`<p>${f(n)}</p>`))}return t&&a.push("</ul>"),a.join("")}var d=class d{constructor(e){this.open=!1;this.sessionId=null;this.greeting="Hi! How can I help?";this.branding=!0;this.ctaText=null;this.ctaUrl=null;this.pageContextValue=null;this.context={};this.config=e,this.apiBase=e.apiBase??"https://api.advocatewidget.com",this.context=e.context??{},this.host=document.createElement("advocate-widget"),this.host.setAttribute("data-position",e.position??"bottom-right"),this.shadow=this.host.attachShadow({mode:"closed"}),this.init()}async init(){try{let e=await fetch(`${this.apiBase}/api/v1/sites/config`,{headers:{"X-Site-Key":this.config.siteKey}});if(e.status===401){console.error("[Advocate] Invalid site key \u2014 widget will not render.");return}let t=(await e.json()).data?.config??{};!this.config.greeting||this.config.greeting==="auto"?t.greeting?this.greeting=t.greeting:t.product_name&&(this.greeting=`Hi! Ask me anything about ${t.product_name.trim()}.`):this.greeting=this.config.greeting,typeof t.branding=="boolean"&&(this.branding=t.branding),t.cta?.text&&t.cta?.url&&(this.ctaText=t.cta.text,this.ctaUrl=t.cta.url),this.config.pageContext&&(this.pageContextValue=E())}catch{console.error("[Advocate] Failed to reach API \u2014 widget will not render.");return}this.sessionId=this.readCookie(),this.render(),document.body.appendChild(this.host),this.sessionId&&this.restoreHistory()}async restoreHistory(){try{let e=await fetch(`${this.apiBase}/api/v1/sessions/${this.sessionId}`,{headers:{"X-Site-Key":this.config.siteKey}});if(e.status===404){this.sessionId=null,this.clearCookie();return}if(!e.ok)return;let t=(await e.json()).data?.messages??[];for(let n of t)this.addMessage(n.role,n.content)}catch{}}render(){let e=document.createElement("style");e.textContent=u,this.shadow.appendChild(e);let a=document.createElement("button");a.className="advocate-trigger",a.innerHTML='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/></svg>',a.addEventListener("click",()=>this.toggle()),this.shadow.appendChild(a);let t=document.createElement("div");t.className="advocate-panel";let n=document.createElement("div");n.className="advocate-header";let s=document.createElement("span");s.textContent=this.greeting;let o=document.createElement("button");o.className="advocate-close",o.innerHTML="&times;",o.setAttribute("aria-label","Close"),o.addEventListener("click",()=>this.toggle()),n.appendChild(s),n.appendChild(o);let g=document.createElement("div");g.className="advocate-messages";let p=document.createElement("div");if(p.className="advocate-input",this.input=document.createElement("input"),this.input.type="text",this.input.placeholder="Type a message...",this.sendBtn=document.createElement("button"),this.sendBtn.textContent="Send",this.sendBtn.addEventListener("click",()=>this.send()),this.input.addEventListener("keydown",c=>{c.key==="Enter"&&this.send()}),p.appendChild(this.input),p.appendChild(this.sendBtn),t.appendChild(n),t.appendChild(g),t.appendChild(p),this.branding){let c=document.createElement("div");c.className="advocate-footer",c.innerHTML='Powered by <a href="https://advocatewidget.com" target="_blank" rel="noopener">Advocate</a>',t.appendChild(c)}this.shadow.appendChild(t)}async send(){let e=this.input.value.trim();if(!e)return;this.addMessage("user",e),this.input.value="",this.input.disabled=!0,this.sendBtn.disabled=!0,this.showTyping();let a=!1;try{let t=await this.sendMessage(e,this.sessionId);if(t==="session_expired"){this.sessionId=null,this.clearCookie();let n=await this.sendMessage(e,null);(n==="session_expired"||n==="error"||n==="paused")&&(this.addMessage("assistant","Something went wrong. Please try again."),n==="paused"&&(a=!0));return}t==="paused"&&(a=!0)}catch{this.addMessage("assistant","Unable to reach the server. Please check your connection and try again.")}finally{this.hideTyping(),a||(this.input.disabled=!1,this.sendBtn.disabled=!1,this.input.focus())}}async sendMessage(e,a){let t={message:e};a&&(t.session_id=a),t.page=this.context.page??window.location.pathname,this.pageContextValue&&(t.page_context=this.pageContextValue);let n=await fetch(`${this.apiBase}/api/v1/chat`,{method:"POST",headers:{"Content-Type":"application/json","X-Site-Key":this.config.siteKey},body:JSON.stringify(t)});if(n.status===402)return this.addMessage("assistant","Upgrade to continue chatting."),"paused";if(n.status===404||n.status===400)return"session_expired";let s=await n.json();if(!n.ok){let o=n.status===429?"Service unavailable right now, please try again later.":n.status===401?"Widget configuration error. Please contact support.":"Something went wrong. Please try again.";return this.addMessage("assistant",o),"error"}return this.sessionId=s.data.session_id??null,this.sessionId&&this.writeCookie(this.sessionId),this.addMessage("assistant",s.data.content),"ok"}addMessage(e,a){let t=this.shadow.querySelector(".advocate-messages"),n=document.createElement("div");if(n.className=`advocate-bubble advocate-bubble--${e}`,e==="assistant"?n.innerHTML=T(a):n.textContent=a,t.appendChild(n),e==="assistant"&&this.ctaText&&this.ctaUrl){let s=document.createElement("a");s.className="advocate-cta",s.href=this.ctaUrl,s.target="_blank",s.rel="noopener",s.textContent=this.ctaText,t.appendChild(s)}t.scrollTop=t.scrollHeight}showTyping(){let e=this.shadow.querySelector(".advocate-messages"),a=document.createElement("div");a.className="advocate-bubble advocate-bubble--assistant advocate-typing",a.id="advocate-typing",a.innerHTML="<span></span><span></span><span></span>",e.appendChild(a),e.scrollTop=e.scrollHeight}hideTyping(){this.shadow.querySelector("#advocate-typing")?.remove()}toggle(){let e=this.shadow.querySelector(".advocate-panel");e&&(this.open?(this.open=!1,window.matchMedia("(max-width: 767px)").matches?(e.classList.remove("open"),e.classList.add("closing"),e.addEventListener("animationend",()=>{e.classList.remove("closing")},{once:!0})):e.classList.remove("open")):(this.open=!0,e.classList.remove("closing"),e.classList.add("open")))}trackConversion(e){try{let a=this.sessionId??this.readCookie();if(!a)return;let t={session_id:a,type:e.type};e.value!==void 0&&(t.value=e.value),fetch(`${this.apiBase}/api/v1/conversion`,{method:"POST",headers:{"Content-Type":"application/json","X-Site-Key":this.config.siteKey},body:JSON.stringify(t)}).catch(()=>{})}catch{}}setContext(e){this.context={...this.context,...e}}readCookie(){try{let e=document.cookie.match(new RegExp(`(?:^|; )${d.COOKIE_NAME}=([^;]*)`));return e?decodeURIComponent(e[1]):null}catch{return null}}writeCookie(e){try{let a=new Date(Date.now()+d.COOKIE_DAYS*864e5).toUTCString();document.cookie=`${d.COOKIE_NAME}=${encodeURIComponent(e)}; expires=${a}; path=/; SameSite=Lax`}catch{}}clearCookie(){try{document.cookie=`${d.COOKIE_NAME}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; SameSite=Lax`}catch{}}};d.COOKIE_NAME="advocate_session",d.COOKIE_DAYS=7;var l=d;function m(i){if(!i.siteKey){console.error("[Advocate] Missing siteKey \u2014 widget will not render.");return}let e,a=i.delay??0;if(a>0){setTimeout(()=>{e=new l(i),i.global!==!1&&(window.Advocate=e)},a);let t=[],n={},s={trackConversion(o){e?e.trackConversion(o):t.push(o)},setContext(o){e?e.setContext(o):n={...n,...o}}};return i.global!==!1&&(window.Advocate=s),s}else return e=new l(i),i.global!==!1&&(window.Advocate=e),e}var r=document.currentScript??window.__advocateScript;r?.dataset.siteKey&&m({siteKey:r.dataset.siteKey,apiBase:r.dataset.apiBase,position:r.dataset.position??"bottom-right",delay:r.dataset.delay?Number(r.dataset.delay):void 0,greeting:r.dataset.greeting,pageContext:r.dataset.pageContext==="true"});
package/dist/index.mjs ADDED
@@ -0,0 +1,277 @@
1
+ var g=`:host {
2
+ all: initial;
3
+ position: fixed;
4
+ z-index: 2147483647;
5
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
6
+ }
7
+
8
+ :host([data-position="bottom-right"]) { bottom: 20px; right: 20px; }
9
+ :host([data-position="bottom-left"]) { bottom: 20px; left: 20px; }
10
+
11
+ .advocate-trigger {
12
+ width: 56px;
13
+ height: 56px;
14
+ border-radius: 50%;
15
+ background: #2563eb;
16
+ border: none;
17
+ cursor: pointer;
18
+ display: flex;
19
+ align-items: center;
20
+ justify-content: center;
21
+ box-shadow: 0 4px 12px rgba(0,0,0,0.15);
22
+ transition: transform 0.2s;
23
+ }
24
+
25
+ .advocate-trigger:hover { transform: scale(1.05); }
26
+
27
+ .advocate-panel {
28
+ display: flex;
29
+ flex-direction: column;
30
+ position: absolute;
31
+ bottom: 72px;
32
+ right: 0;
33
+ width: min(360px, calc(100vw - 40px));
34
+ max-height: 500px;
35
+ border-radius: 12px;
36
+ background: #fff;
37
+ box-shadow: 0 8px 32px rgba(0,0,0,0.12);
38
+ overflow: hidden;
39
+ opacity: 0;
40
+ transform: translateY(8px);
41
+ pointer-events: none;
42
+ transition: opacity 0.2s ease, transform 0.2s ease;
43
+ }
44
+
45
+ .advocate-panel.open {
46
+ opacity: 1;
47
+ transform: translateY(0);
48
+ pointer-events: auto;
49
+ }
50
+
51
+ .advocate-header {
52
+ padding: 16px;
53
+ background: #2563eb;
54
+ color: #fff;
55
+ font-size: 14px;
56
+ font-weight: 600;
57
+ }
58
+
59
+ .advocate-messages {
60
+ flex: 1;
61
+ overflow-y: auto;
62
+ padding: 16px;
63
+ display: flex;
64
+ flex-direction: column;
65
+ gap: 8px;
66
+ }
67
+
68
+ .advocate-bubble {
69
+ max-width: 75%;
70
+ padding: 10px 14px;
71
+ border-radius: 12px;
72
+ font-size: 14px;
73
+ line-height: 1.4;
74
+ word-break: break-word;
75
+ }
76
+
77
+ .advocate-bubble--user {
78
+ align-self: flex-end;
79
+ background: #2563eb;
80
+ color: #fff;
81
+ border-bottom-right-radius: 4px;
82
+ }
83
+
84
+ .advocate-bubble--assistant {
85
+ align-self: flex-start;
86
+ background: #f1f5f9;
87
+ color: #1e293b;
88
+ border-bottom-left-radius: 4px;
89
+ }
90
+
91
+ .advocate-footer {
92
+ padding: 8px 16px;
93
+ text-align: center;
94
+ font-size: 11px;
95
+ color: #94a3b8;
96
+ border-top: 1px solid #f1f5f9;
97
+ }
98
+
99
+ .advocate-footer a {
100
+ color: #2563eb;
101
+ text-decoration: none;
102
+ }
103
+
104
+ .advocate-input {
105
+ display: flex;
106
+ border-top: 1px solid #e5e7eb;
107
+ padding: 12px;
108
+ }
109
+
110
+ .advocate-input input {
111
+ flex: 1;
112
+ border: 1px solid #e5e7eb;
113
+ border-radius: 8px;
114
+ padding: 8px 12px;
115
+ font-size: 14px;
116
+ outline: none;
117
+ }
118
+
119
+ .advocate-input button {
120
+ margin-left: 8px;
121
+ background: #2563eb;
122
+ color: #fff;
123
+ border: none;
124
+ border-radius: 8px;
125
+ padding: 8px 12px;
126
+ cursor: pointer;
127
+ font-size: 14px;
128
+ transition: opacity 0.15s;
129
+ }
130
+
131
+ .advocate-input input:disabled,
132
+ .advocate-input button:disabled {
133
+ opacity: 0.5;
134
+ cursor: not-allowed;
135
+ }
136
+
137
+ @media (max-width: 767px) {
138
+ :host {
139
+ bottom: 0 !important;
140
+ right: 0 !important;
141
+ left: 0 !important;
142
+ top: 0 !important;
143
+ width: 100% !important;
144
+ height: 100% !important;
145
+ position: fixed !important;
146
+ }
147
+
148
+ .advocate-trigger {
149
+ position: fixed;
150
+ bottom: 20px;
151
+ right: 20px;
152
+ }
153
+
154
+ .advocate-panel {
155
+ position: fixed;
156
+ inset: 0;
157
+ width: 100%;
158
+ height: 100%;
159
+ max-height: 100%;
160
+ border-radius: 0;
161
+ transition: none;
162
+ transform: none;
163
+ clip-path: polygon(92% 96%, 100% 96%, 100% 100%, 92% 100%);
164
+ opacity: 0;
165
+ pointer-events: none;
166
+ }
167
+
168
+ .advocate-panel.open {
169
+ animation: advocate-genie-open 0.45s cubic-bezier(0.2, 0.8, 0.3, 1) forwards;
170
+ opacity: 1;
171
+ pointer-events: auto;
172
+ transform: none;
173
+ }
174
+
175
+ .advocate-panel.closing {
176
+ animation: advocate-genie-close 0.35s cubic-bezier(0.7, 0, 0.8, 0.2) forwards;
177
+ pointer-events: none;
178
+ }
179
+
180
+ .advocate-messages {
181
+ flex: 1;
182
+ overflow-y: auto;
183
+ -webkit-overflow-scrolling: touch;
184
+ }
185
+
186
+ .advocate-input {
187
+ position: sticky;
188
+ bottom: 0;
189
+ background: #fff;
190
+ }
191
+
192
+ .advocate-header {
193
+ display: flex;
194
+ align-items: center;
195
+ justify-content: space-between;
196
+ }
197
+
198
+ .advocate-close {
199
+ background: none;
200
+ border: none;
201
+ color: #fff;
202
+ font-size: 22px;
203
+ line-height: 1;
204
+ cursor: pointer;
205
+ padding: 0 4px;
206
+ opacity: 0.85;
207
+ }
208
+
209
+ .advocate-close:hover { opacity: 1; }
210
+ }
211
+
212
+ @keyframes advocate-genie-open {
213
+ 0% { clip-path: polygon(92% 96%, 100% 96%, 100% 100%, 92% 100%); opacity: 1; }
214
+ 35% { clip-path: polygon(25% 35%, 100% 15%, 100% 100%, 0% 100%); }
215
+ 65% { clip-path: polygon(0% 3%, 100% 0%, 100% 100%, 0% 100%); }
216
+ 100% { clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%); }
217
+ }
218
+
219
+ @keyframes advocate-genie-close {
220
+ 0% { clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%); opacity: 1; }
221
+ 35% { clip-path: polygon(0% 3%, 100% 0%, 100% 100%, 0% 100%); }
222
+ 65% { clip-path: polygon(25% 35%, 100% 15%, 100% 100%, 0% 100%); }
223
+ 100% { clip-path: polygon(92% 96%, 100% 96%, 100% 100%, 92% 100%); opacity: 0; }
224
+ }
225
+
226
+ @media (min-width: 768px) {
227
+ .advocate-close { display: none; }
228
+ }
229
+
230
+ .advocate-bubble--assistant p { margin: 0 0 4px; }
231
+ .advocate-bubble--assistant p:last-child { margin-bottom: 0; }
232
+ .advocate-bubble--assistant ul { margin: 4px 0; padding-left: 18px; }
233
+ .advocate-bubble--assistant li { margin-bottom: 2px; }
234
+ .advocate-bubble--assistant a { color: #2563eb; text-decoration: underline; }
235
+ .advocate-bubble--assistant strong { font-weight: 600; }
236
+
237
+ .advocate-typing {
238
+ display: flex;
239
+ align-items: center;
240
+ gap: 4px;
241
+ padding: 10px 14px;
242
+ }
243
+
244
+ .advocate-typing span {
245
+ width: 6px;
246
+ height: 6px;
247
+ border-radius: 50%;
248
+ background: #94a3b8;
249
+ animation: advocate-bounce 1.2s infinite;
250
+ }
251
+
252
+ .advocate-typing span:nth-child(2) { animation-delay: 0.2s; }
253
+ .advocate-typing span:nth-child(3) { animation-delay: 0.4s; }
254
+
255
+ .advocate-cta {
256
+ display: inline-block;
257
+ align-self: flex-start;
258
+ margin-top: 2px;
259
+ padding: 8px 14px;
260
+ background: #2563eb;
261
+ color: #fff;
262
+ border-radius: 8px;
263
+ font-size: 13px;
264
+ font-weight: 600;
265
+ text-decoration: none;
266
+ transition: opacity 0.15s;
267
+ }
268
+
269
+ .advocate-cta:hover { opacity: 0.88; }
270
+
271
+ @keyframes advocate-bounce {
272
+ 0%, 60%, 100% { transform: translateY(0); }
273
+ 30% { transform: translateY(-6px); }
274
+ }
275
+ `;function m(){let i=[],e=document.title?.trim();e&&i.push(`Title: ${e}`);let a=document.querySelector('meta[name="description"]')?.content?.trim()||document.querySelector('meta[property="og:description"]')?.content?.trim();a&&i.push(`Description: ${a}`);let t=Array.from(document.querySelectorAll("h1, h2, h3")).slice(0,5).map(n=>n.textContent?.trim()).filter(Boolean);return t.length&&i.push(`Headings: ${t.map(n=>n.slice(0,80)).join(" | ")}`),i.length?i.join(`
276
+ `).slice(0,400):null}function v(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function u(i){return v(i).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener">$1</a>')}function b(i){let e=i.split(`
277
+ `),a=[],t=!1;for(let n of e){let s=n.match(/^[-*]\s+(.+)/);s?(t||(a.push("<ul>"),t=!0),a.push(`<li>${u(s[1])}</li>`)):(t&&(a.push("</ul>"),t=!1),n.trim()&&a.push(`<p>${u(n)}</p>`))}return t&&a.push("</ul>"),a.join("")}var d=class d{constructor(e){this.open=!1;this.sessionId=null;this.greeting="Hi! How can I help?";this.branding=!0;this.ctaText=null;this.ctaUrl=null;this.pageContextValue=null;this.context={};this.config=e,this.apiBase=e.apiBase??"https://api.advocatewidget.com",this.context=e.context??{},this.host=document.createElement("advocate-widget"),this.host.setAttribute("data-position",e.position??"bottom-right"),this.shadow=this.host.attachShadow({mode:"closed"}),this.init()}async init(){try{let e=await fetch(`${this.apiBase}/api/v1/sites/config`,{headers:{"X-Site-Key":this.config.siteKey}});if(e.status===401){console.error("[Advocate] Invalid site key \u2014 widget will not render.");return}let t=(await e.json()).data?.config??{};!this.config.greeting||this.config.greeting==="auto"?t.greeting?this.greeting=t.greeting:t.product_name&&(this.greeting=`Hi! Ask me anything about ${t.product_name.trim()}.`):this.greeting=this.config.greeting,typeof t.branding=="boolean"&&(this.branding=t.branding),t.cta?.text&&t.cta?.url&&(this.ctaText=t.cta.text,this.ctaUrl=t.cta.url),this.config.pageContext&&(this.pageContextValue=m())}catch{console.error("[Advocate] Failed to reach API \u2014 widget will not render.");return}this.sessionId=this.readCookie(),this.render(),document.body.appendChild(this.host),this.sessionId&&this.restoreHistory()}async restoreHistory(){try{let e=await fetch(`${this.apiBase}/api/v1/sessions/${this.sessionId}`,{headers:{"X-Site-Key":this.config.siteKey}});if(e.status===404){this.sessionId=null,this.clearCookie();return}if(!e.ok)return;let t=(await e.json()).data?.messages??[];for(let n of t)this.addMessage(n.role,n.content)}catch{}}render(){let e=document.createElement("style");e.textContent=g,this.shadow.appendChild(e);let a=document.createElement("button");a.className="advocate-trigger",a.innerHTML='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/></svg>',a.addEventListener("click",()=>this.toggle()),this.shadow.appendChild(a);let t=document.createElement("div");t.className="advocate-panel";let n=document.createElement("div");n.className="advocate-header";let s=document.createElement("span");s.textContent=this.greeting;let o=document.createElement("button");o.className="advocate-close",o.innerHTML="&times;",o.setAttribute("aria-label","Close"),o.addEventListener("click",()=>this.toggle()),n.appendChild(s),n.appendChild(o);let h=document.createElement("div");h.className="advocate-messages";let p=document.createElement("div");if(p.className="advocate-input",this.input=document.createElement("input"),this.input.type="text",this.input.placeholder="Type a message...",this.sendBtn=document.createElement("button"),this.sendBtn.textContent="Send",this.sendBtn.addEventListener("click",()=>this.send()),this.input.addEventListener("keydown",c=>{c.key==="Enter"&&this.send()}),p.appendChild(this.input),p.appendChild(this.sendBtn),t.appendChild(n),t.appendChild(h),t.appendChild(p),this.branding){let c=document.createElement("div");c.className="advocate-footer",c.innerHTML='Powered by <a href="https://advocatewidget.com" target="_blank" rel="noopener">Advocate</a>',t.appendChild(c)}this.shadow.appendChild(t)}async send(){let e=this.input.value.trim();if(!e)return;this.addMessage("user",e),this.input.value="",this.input.disabled=!0,this.sendBtn.disabled=!0,this.showTyping();let a=!1;try{let t=await this.sendMessage(e,this.sessionId);if(t==="session_expired"){this.sessionId=null,this.clearCookie();let n=await this.sendMessage(e,null);(n==="session_expired"||n==="error"||n==="paused")&&(this.addMessage("assistant","Something went wrong. Please try again."),n==="paused"&&(a=!0));return}t==="paused"&&(a=!0)}catch{this.addMessage("assistant","Unable to reach the server. Please check your connection and try again.")}finally{this.hideTyping(),a||(this.input.disabled=!1,this.sendBtn.disabled=!1,this.input.focus())}}async sendMessage(e,a){let t={message:e};a&&(t.session_id=a),t.page=this.context.page??window.location.pathname,this.pageContextValue&&(t.page_context=this.pageContextValue);let n=await fetch(`${this.apiBase}/api/v1/chat`,{method:"POST",headers:{"Content-Type":"application/json","X-Site-Key":this.config.siteKey},body:JSON.stringify(t)});if(n.status===402)return this.addMessage("assistant","Upgrade to continue chatting."),"paused";if(n.status===404||n.status===400)return"session_expired";let s=await n.json();if(!n.ok){let o=n.status===429?"Service unavailable right now, please try again later.":n.status===401?"Widget configuration error. Please contact support.":"Something went wrong. Please try again.";return this.addMessage("assistant",o),"error"}return this.sessionId=s.data.session_id??null,this.sessionId&&this.writeCookie(this.sessionId),this.addMessage("assistant",s.data.content),"ok"}addMessage(e,a){let t=this.shadow.querySelector(".advocate-messages"),n=document.createElement("div");if(n.className=`advocate-bubble advocate-bubble--${e}`,e==="assistant"?n.innerHTML=b(a):n.textContent=a,t.appendChild(n),e==="assistant"&&this.ctaText&&this.ctaUrl){let s=document.createElement("a");s.className="advocate-cta",s.href=this.ctaUrl,s.target="_blank",s.rel="noopener",s.textContent=this.ctaText,t.appendChild(s)}t.scrollTop=t.scrollHeight}showTyping(){let e=this.shadow.querySelector(".advocate-messages"),a=document.createElement("div");a.className="advocate-bubble advocate-bubble--assistant advocate-typing",a.id="advocate-typing",a.innerHTML="<span></span><span></span><span></span>",e.appendChild(a),e.scrollTop=e.scrollHeight}hideTyping(){this.shadow.querySelector("#advocate-typing")?.remove()}toggle(){let e=this.shadow.querySelector(".advocate-panel");e&&(this.open?(this.open=!1,window.matchMedia("(max-width: 767px)").matches?(e.classList.remove("open"),e.classList.add("closing"),e.addEventListener("animationend",()=>{e.classList.remove("closing")},{once:!0})):e.classList.remove("open")):(this.open=!0,e.classList.remove("closing"),e.classList.add("open")))}trackConversion(e){try{let a=this.sessionId??this.readCookie();if(!a)return;let t={session_id:a,type:e.type};e.value!==void 0&&(t.value=e.value),fetch(`${this.apiBase}/api/v1/conversion`,{method:"POST",headers:{"Content-Type":"application/json","X-Site-Key":this.config.siteKey},body:JSON.stringify(t)}).catch(()=>{})}catch{}}setContext(e){this.context={...this.context,...e}}readCookie(){try{let e=document.cookie.match(new RegExp(`(?:^|; )${d.COOKIE_NAME}=([^;]*)`));return e?decodeURIComponent(e[1]):null}catch{return null}}writeCookie(e){try{let a=new Date(Date.now()+d.COOKIE_DAYS*864e5).toUTCString();document.cookie=`${d.COOKIE_NAME}=${encodeURIComponent(e)}; expires=${a}; path=/; SameSite=Lax`}catch{}}clearCookie(){try{document.cookie=`${d.COOKIE_NAME}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; SameSite=Lax`}catch{}}};d.COOKIE_NAME="advocate_session",d.COOKIE_DAYS=7;var l=d;function x(i){if(!i.siteKey){console.error("[Advocate] Missing siteKey \u2014 widget will not render.");return}let e,a=i.delay??0;if(a>0){setTimeout(()=>{e=new l(i),i.global!==!1&&(window.Advocate=e)},a);let t=[],n={},s={trackConversion(o){e?e.trackConversion(o):t.push(o)},setContext(o){e?e.setContext(o):n={...n,...o}}};return i.global!==!1&&(window.Advocate=s),s}else return e=new l(i),i.global!==!1&&(window.Advocate=e),e}var r=document.currentScript??window.__advocateScript;r?.dataset.siteKey&&x({siteKey:r.dataset.siteKey,apiBase:r.dataset.apiBase,position:r.dataset.position??"bottom-right",delay:r.dataset.delay?Number(r.dataset.delay):void 0,greeting:r.dataset.greeting,pageContext:r.dataset.pageContext==="true"});export{x as init};
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "advocate-widget",
3
+ "version": "0.1.0",
4
+ "description": "A lightweight chat widget that helps your website visitors decide to buy.",
5
+ "license": "MIT",
6
+ "main": "dist/index.js",
7
+ "module": "dist/index.mjs",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js",
13
+ "types": "./dist/index.d.ts"
14
+ }
15
+ },
16
+ "files": ["dist"],
17
+ "keywords": ["chat", "widget", "conversion", "sales", "ai"],
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/economicdatasciences/advocate-widget.git",
21
+ "directory": "packages/npm"
22
+ },
23
+ "scripts": {
24
+ "build": "node build.mjs"
25
+ },
26
+ "dependencies": {
27
+ "@advocate/widget": "workspace:*"
28
+ },
29
+ "devDependencies": {
30
+ "esbuild": "^0.21.0",
31
+ "typescript": "^5.4.0"
32
+ }
33
+ }