@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!
12 lines (11 loc) • 32.5 kB
JavaScript
;var e=Object.defineProperty,t=(t,r,s)=>((t,r,s)=>r in t?e(t,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[r]=s)(t,"symbol"!=typeof r?r+"":r,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react");class s{constructor(e){t(this,"config"),t(this,"isInitialized",!1),this.config={baseUrl:"https://api.revrag.com",debug:!1,...e}}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(e){throw new Error(`Failed to initialize Revrag SDK: ${e}`)}}async sendMessage(e){if(!this.isInitialized)throw new Error("SDK not initialized. Call init() first.");try{this.config.debug&&console.log("Sending message:",e);return{success:!0,data:await this.makeApiCall("/chat",{method:"POST",body:JSON.stringify({message:e})})}}catch(t){return this.config.debug&&console.error("Error sending message:",t),{success:!1,error:t instanceof Error?t.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(e){return{success:!1,error:e instanceof Error?e.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(e=>setTimeout(e,500)),"invalid"===this.config.apiKey)throw new Error("Invalid API key")}async makeApiCall(e,t){const r=`${this.config.baseUrl}${e}`,s=await fetch(r,{...t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...t.headers}});if(!s.ok)throw new Error(`API call failed: ${s.statusText}`);return s.json()}}function n(e){return new s(e)}const i={INVALID_API_KEY:"INVALID_API_KEY",NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",RATE_LIMIT_ERROR:"RATE_LIMIT_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",SERVICE_UNAVAILABLE:"SERVICE_UNAVAILABLE",UNKNOWN_ERROR:"UNKNOWN_ERROR"};class a extends Error{constructor(e,r,s,n){super(r),t(this,"code"),t(this,"details"),t(this,"timestamp"),t(this,"requestId"),this.name="RevragError",this.code=e,this.details=s,this.timestamp=new Date,this.requestId=n;const i=Error;i.captureStackTrace&&i.captureStackTrace(this,a)}toJSON(){return{code:this.code,message:this.message,details:this.details,stack:this.stack}}is(e){return this.code===e}static fromError(e,t=i.UNKNOWN_ERROR){return e instanceof a?e:e instanceof Error?new a(t,e.message,{originalError:e.message}):new a(t,String(e))}static invalidApiKey(e="Invalid API key provided"){return new a(i.INVALID_API_KEY,e)}static networkError(e="Network request failed",t){return new a(i.NETWORK_ERROR,e,t)}static timeoutError(e="Request timed out",t){return new a(i.TIMEOUT_ERROR,e,{timeout:t})}static rateLimitError(e="Rate limit exceeded",t){return new a(i.RATE_LIMIT_ERROR,e,{retryAfter:t})}static validationError(e,t){return new a(i.VALIDATION_ERROR,e,{field:t})}static serviceUnavailable(e="Service temporarily unavailable"){return new a(i.SERVICE_UNAVAILABLE,e)}}var o,c={exports:{}},l={};var u,d={};
/**
* @license React
* react-jsx-runtime.development.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.
*/"production"===process.env.NODE_ENV?c.exports=function(){if(o)return l;o=1;var e=r,t=Symbol.for("react.element"),s=Symbol.for("react.fragment"),n=Object.prototype.hasOwnProperty,i=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,a={key:!0,ref:!0,__self:!0,__source:!0};function c(e,r,s){var o,c={},l=null,u=null;for(o in void 0!==s&&(l=""+s),void 0!==r.key&&(l=""+r.key),void 0!==r.ref&&(u=r.ref),r)n.call(r,o)&&!a.hasOwnProperty(o)&&(c[o]=r[o]);if(e&&e.defaultProps)for(o in r=e.defaultProps)void 0===c[o]&&(c[o]=r[o]);return{$$typeof:t,type:e,key:l,ref:u,props:c,_owner:i.current}}return l.Fragment=s,l.jsx=c,l.jsxs=c,l}():c.exports=(u||(u=1,"production"!==process.env.NODE_ENV&&function(){var e,t=r,s=Symbol.for("react.element"),n=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),c=Symbol.for("react.provider"),l=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),p=Symbol.for("react.suspense"),f=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),y=Symbol.for("react.offscreen"),g=Symbol.iterator,v=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function b(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),s=1;s<t;s++)r[s-1]=arguments[s];!function(e,t,r){var s=v.ReactDebugCurrentFrame.getStackAddendum();""!==s&&(t+="%s",r=r.concat([s]));var n=r.map(function(e){return String(e)});n.unshift("Warning: "+t),Function.prototype.apply.call(console[e],console,n)}("error",e,r)}function w(e){return e.displayName||"Context"}function x(e){if(null==e)return null;if("number"==typeof e.tag&&b("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),"function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case i:return"Fragment";case n:return"Portal";case o:return"Profiler";case a:return"StrictMode";case p:return"Suspense";case f:return"SuspenseList"}if("object"==typeof e)switch(e.$$typeof){case l:return w(e)+".Consumer";case c:return w(e._context)+".Provider";case u:return function(e,t,r){var s=e.displayName;if(s)return s;var n=t.displayName||t.name||"";return""!==n?r+"("+n+")":r}(e,e.render,"ForwardRef");case h:var t=e.displayName||null;return null!==t?t:x(e.type)||"Memo";case m:var r=e,s=r._payload,d=r._init;try{return x(d(s))}catch(y){return null}}return null}e=Symbol.for("react.module.reference");var E,R,j,I,S,N,_,k=Object.assign,L=0;function O(){}O.__reactDisabledLog=!0;var A,T=v.ReactCurrentDispatcher;function C(e,t,r){if(void 0===A)try{throw Error()}catch(n){var s=n.stack.trim().match(/\n( *(at )?)/);A=s&&s[1]||""}return"\n"+A+e}var P,D=!1,z="function"==typeof WeakMap?WeakMap:Map;function $(e,t){if(!e||D)return"";var r,s=P.get(e);if(void 0!==s)return s;D=!0;var n,i=Error.prepareStackTrace;Error.prepareStackTrace=void 0,n=T.current,T.current=null,function(){if(0===L){E=console.log,R=console.info,j=console.warn,I=console.error,S=console.group,N=console.groupCollapsed,_=console.groupEnd;var e={configurable:!0,enumerable:!0,value:O,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}L++}();try{if(t){var a=function(){throw Error()};if(Object.defineProperty(a.prototype,"props",{set:function(){throw Error()}}),"object"==typeof Reflect&&Reflect.construct){try{Reflect.construct(a,[])}catch(h){r=h}Reflect.construct(e,[],a)}else{try{a.call()}catch(h){r=h}e.call(a.prototype)}}else{try{throw Error()}catch(h){r=h}e()}}catch(m){if(m&&r&&"string"==typeof m.stack){for(var o=m.stack.split("\n"),c=r.stack.split("\n"),l=o.length-1,u=c.length-1;l>=1&&u>=0&&o[l]!==c[u];)u--;for(;l>=1&&u>=0;l--,u--)if(o[l]!==c[u]){if(1!==l||1!==u)do{if(l--,--u<0||o[l]!==c[u]){var d="\n"+o[l].replace(" at new "," at ");return e.displayName&&d.includes("<anonymous>")&&(d=d.replace("<anonymous>",e.displayName)),"function"==typeof e&&P.set(e,d),d}}while(l>=1&&u>=0);break}}}finally{D=!1,T.current=n,function(){if(0===--L){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:k({},e,{value:E}),info:k({},e,{value:R}),warn:k({},e,{value:j}),error:k({},e,{value:I}),group:k({},e,{value:S}),groupCollapsed:k({},e,{value:N}),groupEnd:k({},e,{value:_})})}L<0&&b("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}(),Error.prepareStackTrace=i}var p=e?e.displayName||e.name:"",f=p?C(p):"";return"function"==typeof e&&P.set(e,f),f}function U(e,t,r){if(null==e)return"";if("function"==typeof e)return $(e,!(!(s=e.prototype)||!s.isReactComponent));var s;if("string"==typeof e)return C(e);switch(e){case p:return C("Suspense");case f:return C("SuspenseList")}if("object"==typeof e)switch(e.$$typeof){case u:return $(e.render,!1);case h:return U(e.type,t,r);case m:var n=e,i=n._payload,a=n._init;try{return U(a(i),t,r)}catch(o){}}return""}P=new z;var K=Object.prototype.hasOwnProperty,M={},q=v.ReactDebugCurrentFrame;function F(e){if(e){var t=e._owner,r=U(e.type,e._source,t?t.type:null);q.setExtraStackFrame(r)}else q.setExtraStackFrame(null)}var V=Array.isArray;function H(e){return V(e)}function W(e){return""+e}function B(e){if(function(e){try{return W(e),!1}catch(t){return!0}}(e))return b("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",function(e){return"function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object"}(e)),W(e)}var Y,J,G=v.ReactCurrentOwner,X={key:!0,ref:!0,__self:!0,__source:!0};function Z(e,t,r,n,i){var a,o={},c=null,l=null;for(a in void 0!==r&&(B(r),c=""+r),function(e){if(K.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}(t)&&(B(t.key),c=""+t.key),function(e){if(K.call(e,"ref")){var t=Object.getOwnPropertyDescriptor(e,"ref").get;if(t&&t.isReactWarning)return!1}return void 0!==e.ref}(t)&&(l=t.ref,function(e){"string"==typeof e.ref&&G.current}(t)),t)K.call(t,a)&&!X.hasOwnProperty(a)&&(o[a]=t[a]);if(e&&e.defaultProps){var u=e.defaultProps;for(a in u)void 0===o[a]&&(o[a]=u[a])}if(c||l){var d="function"==typeof e?e.displayName||e.name||"Unknown":e;c&&function(e,t){var r=function(){Y||(Y=!0,b("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",t))};r.isReactWarning=!0,Object.defineProperty(e,"key",{get:r,configurable:!0})}(o,d),l&&function(e,t){var r=function(){J||(J=!0,b("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",t))};r.isReactWarning=!0,Object.defineProperty(e,"ref",{get:r,configurable:!0})}(o,d)}return function(e,t,r,n,i,a,o){var c={$$typeof:s,type:e,key:t,ref:r,props:o,_owner:a,_store:{}};return Object.defineProperty(c._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(c,"_self",{configurable:!1,enumerable:!1,writable:!1,value:n}),Object.defineProperty(c,"_source",{configurable:!1,enumerable:!1,writable:!1,value:i}),Object.freeze&&(Object.freeze(c.props),Object.freeze(c)),c}(e,c,l,i,n,G.current,o)}var Q,ee=v.ReactCurrentOwner,te=v.ReactDebugCurrentFrame;function re(e){if(e){var t=e._owner,r=U(e.type,e._source,t?t.type:null);te.setExtraStackFrame(r)}else te.setExtraStackFrame(null)}function se(e){return"object"==typeof e&&null!==e&&e.$$typeof===s}function ne(){if(ee.current){var e=x(ee.current.type);if(e)return"\n\nCheck the render method of `"+e+"`."}return""}Q=!1;var ie={};function ae(e,t){if(e._store&&!e._store.validated&&null==e.key){e._store.validated=!0;var r=function(e){var t=ne();if(!t){var r="string"==typeof e?e:e.displayName||e.name;r&&(t="\n\nCheck the top-level render call using <"+r+">.")}return t}(t);if(!ie[r]){ie[r]=!0;var s="";e&&e._owner&&e._owner!==ee.current&&(s=" It was passed a child from "+x(e._owner.type)+"."),re(e),b('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',r,s),re(null)}}}function oe(e,t){if("object"==typeof e)if(H(e))for(var r=0;r<e.length;r++){var s=e[r];se(s)&&ae(s,t)}else if(se(e))e._store&&(e._store.validated=!0);else if(e){var n=function(e){if(null===e||"object"!=typeof e)return null;var t=g&&e[g]||e["@@iterator"];return"function"==typeof t?t:null}(e);if("function"==typeof n&&n!==e.entries)for(var i,a=n.call(e);!(i=a.next()).done;)se(i.value)&&ae(i.value,t)}}function ce(e){var t,r=e.type;if(null!=r&&"string"!=typeof r){if("function"==typeof r)t=r.propTypes;else{if("object"!=typeof r||r.$$typeof!==u&&r.$$typeof!==h)return;t=r.propTypes}if(t){var s=x(r);!function(e,t,r,s,n){var i=Function.call.bind(K);for(var a in e)if(i(e,a)){var o=void 0;try{if("function"!=typeof e[a]){var c=Error((s||"React class")+": "+r+" type `"+a+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[a]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw c.name="Invariant Violation",c}o=e[a](t,a,s,r,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(l){o=l}!o||o instanceof Error||(F(n),b("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",s||"React class",r,a,typeof o),F(null)),o instanceof Error&&!(o.message in M)&&(M[o.message]=!0,F(n),b("Failed %s type: %s",r,o.message),F(null))}}(t,e.props,"prop",s,e)}else void 0===r.PropTypes||Q||(Q=!0,b("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",x(r)||"Unknown"));"function"!=typeof r.getDefaultProps||r.getDefaultProps.isReactClassApproved||b("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}var le={};function ue(t,r,n,d,g,v){var w=function(t){return"string"==typeof t||"function"==typeof t||t===i||t===o||t===a||t===p||t===f||t===y||"object"==typeof t&&null!==t&&(t.$$typeof===m||t.$$typeof===h||t.$$typeof===c||t.$$typeof===l||t.$$typeof===u||t.$$typeof===e||void 0!==t.getModuleId)}(t);if(!w){var E,R="";(void 0===t||"object"==typeof t&&null!==t&&0===Object.keys(t).length)&&(R+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."),R+=ne(),null===t?E="null":H(t)?E="array":void 0!==t&&t.$$typeof===s?(E="<"+(x(t.type)||"Unknown")+" />",R=" Did you accidentally export a JSX literal instead of a component?"):E=typeof t,b("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",E,R)}var j=Z(t,r,n,g,v);if(null==j)return j;if(w){var I=r.children;if(void 0!==I)if(d)if(H(I)){for(var S=0;S<I.length;S++)oe(I[S],t);Object.freeze&&Object.freeze(I)}else b("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else oe(I,t)}if(K.call(r,"key")){var N=x(t),_=Object.keys(r).filter(function(e){return"key"!==e}),k=_.length>0?"{key: someKey, "+_.join(": ..., ")+": ...}":"{key: someKey}";le[N+k]||(b('A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />',k,N,_.length>0?"{"+_.join(": ..., ")+": ...}":"{}",N),le[N+k]=!0)}return t===i?function(e){for(var t=Object.keys(e.props),r=0;r<t.length;r++){var s=t[r];if("children"!==s&&"key"!==s){re(e),b("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",s),re(null);break}}null!==e.ref&&(re(e),b("Invalid attribute `ref` supplied to `React.Fragment`."),re(null))}(j):ce(j),j}var de=function(e,t,r){return ue(e,t,r,!1)},pe=function(e,t,r){return ue(e,t,r,!0)};d.Fragment=i,d.jsx=de,d.jsxs=pe}()),d);var p=c.exports;function f({apiKey:e,config:t}){const[s,i]=r.useState(!1),[a,o]=r.useState(null),[c,l]=r.useState(!1),[u,d]=r.useState(!1),[f,h]=r.useState(null),[m,y]=r.useState([]),[g,v]=r.useState(""),[b,w]=r.useState(!1),x=r.useRef(null);r.useEffect(()=>{i(!0)},[]),r.useEffect(()=>{if(!s||!e)return;(async()=>{try{d(!0),h(null);const r=n({apiKey:e,debug:(null==t?void 0:t.debug)||!1,...t});await r.init(),o(r),l(!0);const s=await r.getChatHistory();y(s)}catch(r){h(r instanceof Error?r.message:"Failed to initialize SDK"),console.error("SDK initialization error:",r)}finally{d(!1)}})()},[e,t,s]),r.useEffect(()=>{s&&E()},[m,s]);const E=()=>{s&&"undefined"!=typeof window&&x.current&&requestAnimationFrame(()=>{x.current&&x.current.scrollIntoView({behavior:"smooth"})})},R=async()=>{if(!a||!g.trim()||b)return;const e={id:Date.now().toString(),content:g,timestamp:new Date,type:"user"};y(t=>[...t,e]),v(""),w(!0);try{const e=await a.sendMessage(g);if(e.success){const e={id:(Date.now()+1).toString(),content:`Echo: ${g}`,timestamp:new Date,type:"assistant"};y(t=>[...t,e])}else h(e.error||"Failed to send message")}catch(t){h(t instanceof Error?t.message:"Error sending message")}finally{w(!1)}};return s?u?p.jsx("div",{className:"revrag-chat-container",children:p.jsxs("div",{className:"revrag-loading",children:[p.jsx("div",{className:"spinner"}),p.jsx("p",{children:"Initializing Revrag SDK..."})]})}):f?p.jsx("div",{className:"revrag-chat-container",children:p.jsxs("div",{className:"revrag-error",children:[p.jsx("h3",{children:"Error"}),p.jsx("p",{children:f}),p.jsx("button",{onClick:()=>window.location.reload(),children:"Retry"})]})}):c?p.jsxs("div",{className:"revrag-chat-container",children:[p.jsxs("div",{className:"revrag-chat-header",children:[p.jsx("h3",{children:"Revrag Chat"}),p.jsxs("div",{className:"revrag-chat-controls",children:[p.jsx("button",{onClick:async()=>{if(a)try{const e=await a.clearHistory();e.success?y([]):h(e.error||"Failed to clear history")}catch(e){h(e instanceof Error?e.message:"Error clearing history")}},className:"clear-btn",children:"Clear History"}),p.jsxs("div",{className:"status-indicator",children:[p.jsx("span",{className:"status-dot "+(c?"connected":"disconnected")}),c?"Connected":"Disconnected"]})]})]}),p.jsxs("div",{className:"revrag-messages",children:[0===m.length?p.jsx("div",{className:"empty-state",children:p.jsx("p",{children:"No messages yet. Start a conversation!"})}):m.map(e=>p.jsxs("div",{className:"message "+("user"===e.type?"user-message":"assistant-message"),children:[p.jsx("div",{className:"message-content",children:e.content}),p.jsx("div",{className:"message-timestamp",children:e.timestamp.toLocaleTimeString()})]},e.id)),p.jsx("div",{ref:x})]}),p.jsx("div",{className:"revrag-input-area",children:p.jsxs("div",{className:"input-container",children:[p.jsx("textarea",{value:g,onChange:e=>v(e.target.value),onKeyPress:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),R())},placeholder:"Type your message...",disabled:b,rows:1}),p.jsx("button",{onClick:R,disabled:!g.trim()||b,className:"send-btn",children:b?"...":"Send"})]})})]}):p.jsx("div",{className:"revrag-chat-container",children:p.jsx("div",{className:"revrag-error",children:p.jsx("p",{children:"SDK not initialized. Please provide a valid API key."})})}):null}exports.FloatingHelpWidget=function({apiKey:e,debug:t=!1,position:s="bottom-right",primaryColor:n="#667eea",size:i="medium",avatarUrl:a="https://via.placeholder.com/40x40/667eea/ffffff?text=AI",onCallStart:o,onCallEnd:c,onInit:l}){const[u,d]=r.useState(!1),[h,m]=r.useState("collapsed"),[y,g]=r.useState(!1),[v,b]=r.useState(!1),[w,x]=r.useState(!1),[E,R]=r.useState(!1),j=r.useRef(null),I=r.useRef(null);if(r.useEffect(()=>{const e=setTimeout(()=>{d(!0),null==l||l()},0);return()=>clearTimeout(e)},[l]),r.useEffect(()=>{if(!u)return;if("undefined"==typeof window||"undefined"==typeof document)return;const e=e=>{j.current&&!j.current.contains(e.target)&&("call"===h&&v||m("collapsed"))},t=setTimeout(()=>{document.addEventListener("mousedown",e)},10);return()=>{clearTimeout(t),document.removeEventListener("mousedown",e)}},[h,v,u]),r.useEffect(()=>{if(!u)return;if("undefined"==typeof window||"undefined"==typeof document)return;const e=e=>{"Escape"===e.key&&("call"===h&&v||m("collapsed"))},t=setTimeout(()=>{document.addEventListener("keydown",e)},10);return()=>{clearTimeout(t),document.removeEventListener("keydown",e)}},[h,v,u]),!u)return null;const S={"--primary-color":n};return p.jsxs("div",{ref:j,className:`floating-help-widget position-${s} ${(()=>{switch(i){case"small":return"size-small";case"large":return"size-large";default:return"size-medium"}})()} state-${h}`,style:S,children:[E&&"collapsed"===h&&p.jsxs("div",{className:"help-tooltip",children:[p.jsx("span",{children:"Do you need any help?"}),p.jsx("div",{className:"tooltip-arrow"})]}),("collapsed"===h||"expanded"===h)&&p.jsxs("button",{className:`help-orb ${y?"hovered":""} ${"expanded"===h?"expanded":""}`,onClick:()=>{"collapsed"===h?(m("expanded"),R(!1)):"expanded"===h&&m("collapsed")},onMouseEnter:()=>{g(!0),"collapsed"===h&&(I.current=setTimeout(()=>{R(!0)},500))},onMouseLeave:()=>{g(!1),R(!1),I.current&&clearTimeout(I.current)},"aria-label":"Help Assistant",children:[p.jsx("div",{className:"orb-icon",children:"expanded"===h?p.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:p.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"})}):p.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:[p.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"}),p.jsx("circle",{cx:"12",cy:"14",r:"2"})]})}),p.jsx("div",{className:"orb-pulse"})]}),"expanded"===h&&p.jsxs("div",{className:"help-options",children:[p.jsxs("button",{className:"help-option",onClick:()=>{m("chat")},children:[p.jsx("div",{className:"option-icon",children:p.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:p.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"})})}),p.jsx("span",{children:"Start Chat"})]}),p.jsxs("button",{className:"help-option",onClick:()=>{m("call"),b(!0),null==o||o()},children:[p.jsx("div",{className:"option-icon",children:p.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:p.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"})})}),p.jsx("span",{children:"Start Call"})]})]}),"chat"===h&&p.jsxs("div",{className:"help-chat-container",children:[p.jsxs("div",{className:"chat-header",children:[p.jsx("h3",{children:"Chat Support"}),p.jsx("button",{className:"close-btn",onClick:()=>{m("collapsed")},"aria-label":"Close chat",children:p.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:p.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"})})})]}),p.jsx("div",{className:"chat-content",children:p.jsx(f,{apiKey:e,config:{debug:t}})})]}),"call"===h&&p.jsxs("div",{className:"help-call-container",children:[p.jsx("div",{className:"call-header",children:p.jsxs("div",{className:"call-status",children:[p.jsx("div",{className:"status-indicator "+(v?"active":"")}),p.jsx("span",{children:v?"Call Active":"Connecting..."})]})}),p.jsxs("div",{className:"call-content",children:[p.jsxs("div",{className:"call-avatar",children:[p.jsx("img",{src:a,alt:"Support Agent"}),p.jsx("div",{className:"avatar-status"})]}),p.jsxs("div",{className:"call-info",children:[p.jsx("h4",{children:"Support Agent"}),p.jsx("p",{children:"Ready to help you"})]})]}),p.jsxs("div",{className:"call-controls",children:[p.jsx("button",{className:"control-btn mute-btn "+(w?"active":""),onClick:()=>{x(!w)},"aria-label":w?"Unmute":"Mute",children:p.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:w?p.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"}):p.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"})})}),p.jsx("button",{className:"control-btn end-call-btn",onClick:()=>{b(!1),x(!1),m("collapsed"),null==c||c()},"aria-label":"End call",children:p.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:p.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"})})})]})]})]})},exports.PluginManager=class{constructor(){t(this,"plugins",new Map),t(this,"sdk",null)}setSdk(e){this.sdk=e}async registerPlugin(e){if(this.validatePlugin(e),this.plugins.has(e.name))throw new a("PLUGIN_ALREADY_EXISTS",`Plugin "${e.name}" is already registered`);try{e.initialize&&this.sdk&&await e.initialize(this.sdk),this.plugins.set(e.name,e),this.sdk&&this.sdk.emit("plugin:registered",e)}catch(t){throw new a("PLUGIN_INITIALIZATION_FAILED",`Failed to initialize plugin "${e.name}": ${t instanceof Error?t.message:String(t)}`)}}async unregisterPlugin(e){const t=this.plugins.get(e);if(!t)throw new a("PLUGIN_NOT_FOUND",`Plugin "${e}" is not registered`);try{t.destroy&&await t.destroy(),this.plugins.delete(e),this.sdk&&this.sdk.emit("plugin:unregistered",e)}catch(r){throw new a("PLUGIN_DESTRUCTION_FAILED",`Failed to destroy plugin "${e}": ${r instanceof Error?r.message:String(r)}`)}}getPlugin(e){return this.plugins.get(e)}listPlugins(){return Array.from(this.plugins.values())}validatePlugin(e){if(!e.name||"string"!=typeof e.name)throw new a("INVALID_PLUGIN","Plugin must have a valid name");if(!e.version||"string"!=typeof e.version)throw new a("INVALID_PLUGIN","Plugin must have a valid version")}},exports.RevragApiService=class{constructor(e){var r,s;t(this,"baseUrl"),t(this,"defaultHeaders"),t(this,"timeout"),t(this,"retryAttempts"),t(this,"requestInterceptors",[]),t(this,"responseInterceptors",[]),this.baseUrl=e.baseUrl||"https://api.revrag.com",this.timeout=e.timeout||3e4,this.retryAttempts=e.retryAttempts||3,this.defaultHeaders={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`,"User-Agent":"Revrag-SDK/1.0.0"},(null==(r=e.interceptors)?void 0:r.request)&&this.requestInterceptors.push(...e.interceptors.request),(null==(s=e.interceptors)?void 0:s.response)&&this.responseInterceptors.push(...e.interceptors.response)}async request(e,t={}){const r=this.buildUrl(e),s=this.generateRequestId();try{const e=await this.applyRequestInterceptors({...t,headers:{...this.defaultHeaders,...t.headers},timeout:t.timeout||this.timeout,retries:t.retries||this.retryAttempts,metadata:{...t.metadata,requestId:s,timestamp:new Date}}),n=await this.executeWithRetry(r,e);return await this.applyResponseInterceptors(n)}catch(n){return{success:!1,error:a.fromError(n).toJSON(),metadata:{timestamp:new Date,requestId:s}}}}async get(e,t){return this.request(e,{...t,method:"GET"})}async post(e,t,r){return this.request(e,{...r,method:"POST",body:t?JSON.stringify(t):void 0})}async put(e,t,r){return this.request(e,{...r,method:"PUT",body:t?JSON.stringify(t):void 0})}async delete(e,t){return this.request(e,{...t,method:"DELETE"})}addRequestInterceptor(e){this.requestInterceptors.push(e)}addResponseInterceptor(e){this.responseInterceptors.push(e)}removeRequestInterceptor(e){const t=this.requestInterceptors.indexOf(e);t>-1&&this.requestInterceptors.splice(t,1)}removeResponseInterceptor(e){const t=this.responseInterceptors.indexOf(e);t>-1&&this.responseInterceptors.splice(t,1)}updateConfig(e){e.baseUrl&&(this.baseUrl=e.baseUrl),void 0!==e.timeout&&(this.timeout=e.timeout),void 0!==e.retryAttempts&&(this.retryAttempts=e.retryAttempts),e.apiKey&&(this.defaultHeaders.Authorization=`Bearer ${e.apiKey}`)}buildUrl(e){return e.startsWith("http")?e:`${this.baseUrl.replace(/\/$/,"")}/${e.replace(/^\//,"")}`}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}async applyRequestInterceptors(e){let t=e;for(const r of this.requestInterceptors)t=await r(t);return t}async applyResponseInterceptors(e){let t=e;for(const r of this.responseInterceptors)t=await r(t);return t}async executeWithRetry(e,t){const r=t.retries||0;let s=null;for(let i=0;i<=r;i++)try{if(i>0){const e=Math.min(1e3*Math.pow(2,i-1),1e4);await this.delay(e)}return await this.executeRequest(e,t)}catch(n){if(s=n instanceof Error?n:new Error(String(n)),this.shouldNotRetry(s)||i===r)throw s}throw s}async executeRequest(e,t){var r;const s=new AbortController,n=setTimeout(()=>s.abort(),t.timeout||this.timeout);try{const i=await fetch(e,{...t,signal:s.signal});if(clearTimeout(n),!i.ok)throw await this.createHttpError(i);return{success:!0,data:await i.json(),metadata:{timestamp:new Date,requestId:null==(r=t.metadata)?void 0:r.requestId}}}catch(i){if(clearTimeout(n),i instanceof Error&&"AbortError"===i.name)throw a.timeoutError("Request timed out",t.timeout||this.timeout);throw i}}async createHttpError(e){let t;try{t=await e.json()}catch{t=await e.text()}const r=e.status,s=e.statusText;switch(r){case 401:return a.invalidApiKey(`Authentication failed: ${s}`);case 429:{const t=e.headers.get("Retry-After");return a.rateLimitError(`Rate limit exceeded: ${s}`,t?parseInt(t,10):void 0)}case 503:return a.serviceUnavailable(`Service unavailable: ${s}`);default:return a.networkError(`HTTP ${r}: ${s}`,{statusCode:r,statusText:s,data:t})}}shouldNotRetry(e){return e instanceof a&&(e.code===i.INVALID_API_KEY||e.code===i.VALIDATION_ERROR)}delay(e){return new Promise(t=>setTimeout(t,e))}},exports.RevragChat=f,exports.RevragError=a,exports.RevragErrorCode=i,exports.RevragEventEmitter=class{constructor(e=100){t(this,"regularListeners",new Map),t(this,"onceListeners",new Map),t(this,"maxListeners"),this.maxListeners=e}on(e,t){this.addListener(e,t,!1)}off(e,t){this.removeListener(e,t)}emit(e,...t){const r=this.regularListeners.get(e);r&&r.size>0&&r.forEach(e=>{try{e(...t)}catch(r){setTimeout(()=>{this.emit("error",r)},0)}});const s=this.onceListeners.get(e);if(s&&s.size>0){const e=Array.from(s);s.clear(),e.forEach(e=>{try{e(...t)}catch(r){setTimeout(()=>{this.emit("error",r)},0)}})}}once(e,t){this.addListener(e,t,!0)}removeAllListeners(e){e?(this.regularListeners.delete(e),this.onceListeners.delete(e)):(this.regularListeners.clear(),this.onceListeners.clear())}listenerCount(e){var t,r;return((null==(t=this.regularListeners.get(e))?void 0:t.size)||0)+((null==(r=this.onceListeners.get(e))?void 0:r.size)||0)}eventNames(){const e=Array.from(this.regularListeners.keys()),t=Array.from(this.onceListeners.keys());return[...new Set([...e,...t])]}listeners(e){return[...Array.from(this.regularListeners.get(e)||[]),...Array.from(this.onceListeners.get(e)||[])]}setMaxListeners(e){return this.maxListeners=e,this}getMaxListeners(){return this.maxListeners}addListener(e,t,r){const s=r?this.onceListeners:this.regularListeners;s.has(e)||s.set(e,new Set);const n=s.get(e);n.size>=this.maxListeners&&console.warn(`Warning: Possible EventEmitter memory leak detected. ${n.size+1} listeners added for event "${e}". Use setMaxListeners() to increase limit.`),n.add(t)}removeListener(e,t){const r=this.regularListeners.get(e);r&&(r.delete(t),0===r.size&&this.regularListeners.delete(e));const s=this.onceListeners.get(e);s&&(s.delete(t),0===s.size&&this.onceListeners.delete(e))}},exports.RevragSDKLegacy=s,exports.VERSION="2.0.0",exports.createRevragSDKLegacy=n;
//# sourceMappingURL=revrag-sdk.cjs.js.map