UNPKG

@rohitkvs/revrag-web-sdk

Version:

Industry-standard React SDK for Revrag chat functionality with simple script integration. Zero setup required - just include a script tag!

11 lines (10 loc) 14.9 kB
var RevragWidget=function(h,s,N){"use strict";var ue=Object.defineProperty;var he=(h,s,N)=>s in h?ue(h,s,{enumerable:!0,configurable:!0,writable:!0,value:N}):h[s]=N;var W=(h,s,N)=>he(h,typeof s!="symbol"?s+"":s,N);var B,U=N;B=U.createRoot,U.hydrateRoot;var V={exports:{}},T={};/** * @license React * react-jsx-runtime.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var Y=s,G=Symbol.for("react.element"),Q=Symbol.for("react.fragment"),X=Object.prototype.hasOwnProperty,Z=Y.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,q={key:!0,ref:!0,__self:!0,__source:!0};function F(i,t,a){var n,l={},x=null,f=null;a!==void 0&&(x=""+a),t.key!==void 0&&(x=""+t.key),t.ref!==void 0&&(f=t.ref);for(n in t)X.call(t,n)&&!q.hasOwnProperty(n)&&(l[n]=t[n]);if(i&&i.defaultProps)for(n in t=i.defaultProps,t)l[n]===void 0&&(l[n]=t[n]);return{$$typeof:G,type:i,key:x,ref:f,props:l,_owner:Z.current}}T.Fragment=Q,T.jsx=F,T.jsxs=F,V.exports=T;var e=V.exports;class ${constructor(t){W(this,"config");W(this,"isInitialized",!1);this.config={baseUrl:"https://api.revrag.com",debug:!1,...t}}async init(){this.config.debug&&console.log("Initializing Revrag SDK...",this.config);try{await this.validateApiKey(),this.isInitialized=!0,this.config.debug&&console.log("Revrag SDK initialized successfully")}catch(t){throw new Error(`Failed to initialize Revrag SDK: ${t}`)}}async sendMessage(t){if(!this.isInitialized)throw new Error("SDK not initialized. Call init() first.");try{return this.config.debug&&console.log("Sending message:",t),{success:!0,data:await this.makeApiCall("/chat",{method:"POST",body:JSON.stringify({message:t})})}}catch(a){return this.config.debug&&console.error("Error sending message:",a),{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getChatHistory(){if(!this.isInitialized)throw new Error("SDK not initialized. Call init() first.");return[{id:"1",content:"Hello, how can I help you?",timestamp:new Date,type:"assistant"},{id:"2",content:"I need help with my project",timestamp:new Date,type:"user"}]}async clearHistory(){if(!this.isInitialized)throw new Error("SDK not initialized. Call init() first.");try{return await this.makeApiCall("/chat/clear",{method:"DELETE"}),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}getStatus(){return{initialized:this.isInitialized,config:{baseUrl:this.config.baseUrl,debug:this.config.debug,hasApiKey:!!this.config.apiKey}}}async validateApiKey(){if(!this.config.apiKey)throw new Error("API key is required");if(await new Promise(t=>setTimeout(t,500)),this.config.apiKey==="invalid")throw new Error("Invalid API key")}async makeApiCall(t,a){const n=`${this.config.baseUrl}${t}`,l=await fetch(n,{...a,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...a.headers}});if(!l.ok)throw new Error(`API call failed: ${l.statusText}`);return l.json()}}function ee(i){return new $(i)}function te({apiKey:i,config:t}){const[a,n]=s.useState(!1),[l,x]=s.useState(null),[f,R]=s.useState(!1),[C,y]=s.useState(!1),[L,r]=s.useState(null),[u,E]=s.useState([]),[g,v]=s.useState(""),[j,w]=s.useState(!1),S=s.useRef(null);s.useEffect(()=>{n(!0)},[]),s.useEffect(()=>{if(!a||!i)return;(async()=>{try{y(!0),r(null);const c=ee({apiKey:i,debug:(t==null?void 0:t.debug)||!1,...t});await c.init(),x(c),R(!0);const I=await c.getChatHistory();E(I)}catch(c){r(c instanceof Error?c.message:"Failed to initialize SDK"),console.error("SDK initialization error:",c)}finally{y(!1)}})()},[i,t,a]),s.useEffect(()=>{a&&O()},[u,a]);const O=()=>{!a||typeof window>"u"||!S.current||requestAnimationFrame(()=>{S.current&&S.current.scrollIntoView({behavior:"smooth"})})},z=async()=>{if(!l||!g.trim()||j)return;const o={id:Date.now().toString(),content:g,timestamp:new Date,type:"user"};E(c=>[...c,o]),v(""),w(!0);try{const c=await l.sendMessage(g);if(c.success){const I={id:(Date.now()+1).toString(),content:`Echo: ${g}`,timestamp:new Date,type:"assistant"};E(H=>[...H,I])}else r(c.error||"Failed to send message")}catch(c){r(c instanceof Error?c.message:"Error sending message")}finally{w(!1)}},M=async()=>{if(l)try{const o=await l.clearHistory();o.success?E([]):r(o.error||"Failed to clear history")}catch(o){r(o instanceof Error?o.message:"Error clearing history")}},k=o=>{o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),z())};return a?C?e.jsx("div",{className:"revrag-chat-container",children:e.jsxs("div",{className:"revrag-loading",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:"Initializing Revrag SDK..."})]})}):L?e.jsx("div",{className:"revrag-chat-container",children:e.jsxs("div",{className:"revrag-error",children:[e.jsx("h3",{children:"Error"}),e.jsx("p",{children:L}),e.jsx("button",{onClick:()=>window.location.reload(),children:"Retry"})]})}):f?e.jsxs("div",{className:"revrag-chat-container",children:[e.jsxs("div",{className:"revrag-chat-header",children:[e.jsx("h3",{children:"Revrag Chat"}),e.jsxs("div",{className:"revrag-chat-controls",children:[e.jsx("button",{onClick:M,className:"clear-btn",children:"Clear History"}),e.jsxs("div",{className:"status-indicator",children:[e.jsx("span",{className:`status-dot ${f?"connected":"disconnected"}`}),f?"Connected":"Disconnected"]})]})]}),e.jsxs("div",{className:"revrag-messages",children:[u.length===0?e.jsx("div",{className:"empty-state",children:e.jsx("p",{children:"No messages yet. Start a conversation!"})}):u.map(o=>e.jsxs("div",{className:`message ${o.type==="user"?"user-message":"assistant-message"}`,children:[e.jsx("div",{className:"message-content",children:o.content}),e.jsx("div",{className:"message-timestamp",children:o.timestamp.toLocaleTimeString()})]},o.id)),e.jsx("div",{ref:S})]}),e.jsx("div",{className:"revrag-input-area",children:e.jsxs("div",{className:"input-container",children:[e.jsx("textarea",{value:g,onChange:o=>v(o.target.value),onKeyPress:k,placeholder:"Type your message...",disabled:j,rows:1}),e.jsx("button",{onClick:z,disabled:!g.trim()||j,className:"send-btn",children:j?"...":"Send"})]})})]}):e.jsx("div",{className:"revrag-chat-container",children:e.jsx("div",{className:"revrag-error",children:e.jsx("p",{children:"SDK not initialized. Please provide a valid API key."})})}):null}function se({apiKey:i,debug:t=!1,position:a="bottom-right",primaryColor:n="#667eea",size:l="medium",avatarUrl:x="https://via.placeholder.com/40x40/667eea/ffffff?text=AI",onCallStart:f,onCallEnd:R,onInit:C}){const[y,L]=s.useState(!1),[r,u]=s.useState("collapsed"),[E,g]=s.useState(!1),[v,j]=s.useState(!1),[w,S]=s.useState(!1),[O,z]=s.useState(!1),M=s.useRef(null),k=s.useRef(null);s.useEffect(()=>{const b=setTimeout(()=>{L(!0),C==null||C()},0);return()=>clearTimeout(b)},[C]),s.useEffect(()=>{if(!y||typeof window>"u"||typeof document>"u")return;const b=P=>{M.current&&!M.current.contains(P.target)&&(r!=="call"||!v)&&u("collapsed")},_=setTimeout(()=>{document.addEventListener("mousedown",b)},10);return()=>{clearTimeout(_),document.removeEventListener("mousedown",b)}},[r,v,y]),s.useEffect(()=>{if(!y||typeof window>"u"||typeof document>"u")return;const b=P=>{P.key==="Escape"&&(r!=="call"||!v)&&u("collapsed")},_=setTimeout(()=>{document.addEventListener("keydown",b)},10);return()=>{clearTimeout(_),document.removeEventListener("keydown",b)}},[r,v,y]);const o=()=>{g(!0),r==="collapsed"&&(k.current=setTimeout(()=>{z(!0)},500))},c=()=>{g(!1),z(!1),k.current&&clearTimeout(k.current)},I=()=>{r==="collapsed"?(u("expanded"),z(!1)):r==="expanded"&&u("collapsed")},H=()=>{u("chat")},ne=()=>{u("call"),j(!0),f==null||f()},ae=()=>{j(!1),S(!1),u("collapsed"),R==null||R()},re=()=>{S(!w)},oe=()=>{u("collapsed")},le=()=>{switch(l){case"small":return"size-small";case"large":return"size-large";default:return"size-medium"}},ce=()=>`position-${a}`;if(!y)return null;const de={"--primary-color":n};return e.jsxs("div",{ref:M,className:`floating-help-widget ${ce()} ${le()} state-${r}`,style:de,children:[O&&r==="collapsed"&&e.jsxs("div",{className:"help-tooltip",children:[e.jsx("span",{children:"Do you need any help?"}),e.jsx("div",{className:"tooltip-arrow"})]}),(r==="collapsed"||r==="expanded")&&e.jsxs("button",{className:`help-orb ${E?"hovered":""} ${r==="expanded"?"expanded":""}`,onClick:I,onMouseEnter:o,onMouseLeave:c,"aria-label":"Help Assistant",children:[e.jsx("div",{className:"orb-icon",children:r==="expanded"?e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})}):e.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:[e.jsx("path",{d:"M21 6h-2l-1.27-1.27A2.49 2.49 0 0 0 16 4H8c-.69 0-1.3.28-1.73.73L5 6H3a1 1 0 0 0 0 2h1v11a3 3 0 0 0 3 3h10a3 3 0 0 0 3-3V8h1a1 1 0 0 0 0-2zM12 18a4 4 0 1 1 4-4 4 4 0 0 1-4 4z"}),e.jsx("circle",{cx:"12",cy:"14",r:"2"})]})}),e.jsx("div",{className:"orb-pulse"})]}),r==="expanded"&&e.jsxs("div",{className:"help-options",children:[e.jsxs("button",{className:"help-option",onClick:H,children:[e.jsx("div",{className:"option-icon",children:e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M20 2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h4l4 4 4-4h4c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"})})}),e.jsx("span",{children:"Start Chat"})]}),e.jsxs("button",{className:"help-option",onClick:ne,children:[e.jsx("div",{className:"option-icon",children:e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"})})}),e.jsx("span",{children:"Start Call"})]})]}),r==="chat"&&e.jsxs("div",{className:"help-chat-container",children:[e.jsxs("div",{className:"chat-header",children:[e.jsx("h3",{children:"Chat Support"}),e.jsx("button",{className:"close-btn",onClick:oe,"aria-label":"Close chat",children:e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})})})]}),e.jsx("div",{className:"chat-content",children:e.jsx(te,{apiKey:i,config:{debug:t}})})]}),r==="call"&&e.jsxs("div",{className:"help-call-container",children:[e.jsx("div",{className:"call-header",children:e.jsxs("div",{className:"call-status",children:[e.jsx("div",{className:`status-indicator ${v?"active":""}`}),e.jsx("span",{children:v?"Call Active":"Connecting..."})]})}),e.jsxs("div",{className:"call-content",children:[e.jsxs("div",{className:"call-avatar",children:[e.jsx("img",{src:x,alt:"Support Agent"}),e.jsx("div",{className:"avatar-status"})]}),e.jsxs("div",{className:"call-info",children:[e.jsx("h4",{children:"Support Agent"}),e.jsx("p",{children:"Ready to help you"})]})]}),e.jsxs("div",{className:"call-controls",children:[e.jsx("button",{className:`control-btn mute-btn ${w?"active":""}`,onClick:re,"aria-label":w?"Unmute":"Mute",children:e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:w?e.jsx("path",{d:"M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"}):e.jsx("path",{d:"M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"})})}),e.jsx("button",{className:"control-btn end-call-btn",onClick:ae,"aria-label":"End call",children:e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08c-.18-.17-.29-.42-.29-.7 0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.7l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.1-.7-.28-.79-.73-1.68-1.36-2.66-1.85-.33-.16-.56-.5-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"})})})]})]})]})}let p=null,d=null,A=null;function D(i){if(p&&d&&JSON.stringify(A)===JSON.stringify(i)){i.debug&&console.log("RevragWidget already initialized with same config");return}if(p&&K(),document.readyState==="loading"){document.addEventListener("DOMContentLoaded",()=>D(i));return}d=document.createElement("div"),d.id="revrag-widget-container",d.style.position="fixed",d.style.zIndex="999999",d.style.pointerEvents="none",document.body?document.body.appendChild(d):new MutationObserver((a,n)=>{document.body&&(document.body.appendChild(d),n.disconnect())}).observe(document.documentElement,{childList:!0,subtree:!0}),p=B(d),p.render(s.createElement(se,{...i,onInit:()=>{d&&(d.style.pointerEvents="auto")}})),A=i,i.debug&&console.log("RevragWidget initialized successfully",i)}function K(){p&&(p.unmount(),p=null),d&&(d.remove(),d=null),A=null}function ie(){if([()=>{document.readyState!=="loading"&&m()},()=>{document.readyState==="loading"&&document.addEventListener("DOMContentLoaded",m)},()=>{window.addEventListener("load",m)},()=>{setTimeout(m,100),setTimeout(m,500),setTimeout(m,1e3)}].forEach(t=>{try{t()}catch(a){console.warn("RevragWidget init strategy failed:",a)}}),typeof window<"u"){window.addEventListener("popstate",()=>{setTimeout(m,100)});const t=history.pushState,a=history.replaceState;history.pushState=function(...n){t.apply(history,n),setTimeout(m,100)},history.replaceState=function(...n){a.apply(history,n),setTimeout(m,100)}}}function m(){var a;if(p&&d&&document.contains(d))return;let i=null;if(document.querySelectorAll('script[src*="revrag"]').forEach(n=>{const l=n.getAttribute("data-api-key");l&&(i={apiKey:l,debug:n.getAttribute("data-debug")==="true",position:n.getAttribute("data-position")||"bottom-right",primaryColor:n.getAttribute("data-primary-color")||"#667eea",size:n.getAttribute("data-size")||"medium",avatarUrl:n.getAttribute("data-avatar-url")||void 0})}),!i&&((a=window.RevragWidget)!=null&&a.config)&&(i=window.RevragWidget.config),!i&&typeof localStorage<"u")try{const n=localStorage.getItem("revrag-widget-config");n&&(i=JSON.parse(n))}catch{}if(i){if(typeof localStorage<"u")try{localStorage.setItem("revrag-widget-config",JSON.stringify(i))}catch{}D(i)}}const J={init:D,destroy:K};return window.RevragWidget=J,ie(),h.RevragWidget=J,h.destroyWidget=K,h.initializeWidget=D,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"}),h}({},React,ReactDOM); //# sourceMappingURL=revrag-widget.iife.js.map