UNPKG

senangwebs-chatbot

Version:

Lightweight JavaScript library with OpenRouter API integration for AI-powered conversations.

2 lines 48.6 kB
/*! For license information please see swc.js.LICENSE.txt */ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.SWC=e():t.SWC=e()}(this,(()=>(()=>{var t={708:t=>{function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},e(t)}function n(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,r(o.key),o)}}function r(t){var n=function(t){if("object"!=e(t)||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,"string");if("object"!=e(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==e(n)?n:n+""}var o=function(){return t=function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.maxMessages=e.maxMessages||10,this.systemPrompt=e.systemPrompt||"You are a helpful assistant.",this.contextWindow=[],this.totalTokensEstimate=0,this.maxTokens=e.maxTokens||2e3,this.debug=e.debug||!1},e=[{key:"addMessage",value:function(t,e){if(t&&e){var n={role:t,content:e,timestamp:(new Date).toISOString(),tokens:this._estimateTokens(e)};this.contextWindow.push(n),this.totalTokensEstimate+=n.tokens,this.debug&&(console.log("[ContextManager] Added ".concat(t," message (").concat(n.tokens," tokens)")),console.log("[ContextManager] Total messages: ".concat(this.contextWindow.length,", estimated tokens: ").concat(this.totalTokensEstimate))),this._trimContext()}else console.warn("[ContextManager] Invalid message: role and content are required")}},{key:"getContext",value:function(){var t=[];return(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])&&this.systemPrompt&&t.push({role:"system",content:this.systemPrompt}),this.contextWindow.forEach((function(e){t.push({role:e.role,content:e.content})})),this.debug&&console.log("[ContextManager] Returning ".concat(t.length," messages for API")),t}},{key:"getLastMessages",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:5;return this.contextWindow.slice(-t)}},{key:"clear",value:function(){this.contextWindow=[],this.totalTokensEstimate=0,this.debug&&console.log("[ContextManager] Context cleared")}},{key:"setSystemPrompt",value:function(t){this.systemPrompt=t,this.debug&&console.log("[ContextManager] System prompt updated")}},{key:"getStats",value:function(){return{messageCount:this.contextWindow.length,estimatedTokens:this.totalTokensEstimate,maxMessages:this.maxMessages,maxTokens:this.maxTokens,systemPrompt:this.systemPrompt?this.systemPrompt.substring(0,50)+"...":null}}},{key:"_trimContext",value:function(){for(;this.contextWindow.length>this.maxMessages;){var t=this.contextWindow.shift();this.totalTokensEstimate=Math.max(0,this.totalTokensEstimate-t.tokens),this.debug&&console.log("[ContextManager] Removed oldest message (".concat(t.role,"), ").concat(this.contextWindow.length," remaining"))}for(;this.totalTokensEstimate>this.maxTokens&&this.contextWindow.length>2;){var e=this.contextWindow.shift();this.totalTokensEstimate=Math.max(0,this.totalTokensEstimate-e.tokens),this.debug&&console.log("[ContextManager] Removed message to reduce tokens (".concat(e.role,"), ").concat(this.totalTokensEstimate," tokens remaining"))}}},{key:"_estimateTokens",value:function(t){return t?Math.ceil(t.length/4):0}},{key:"summarize",value:function(){if(this.contextWindow.length<3)return"";var t=this.contextWindow.slice(0,Math.floor(this.contextWindow.length/2)).map((function(t){var e=t.content.substring(0,100);return"".concat(t.role,": ").concat(e).concat(t.content.length>100?"...":"")})).join("\n");return"Previous conversation summary:\n".concat(t)}},{key:"export",value:function(){return{version:"1.0",timestamp:(new Date).toISOString(),systemPrompt:this.systemPrompt,maxMessages:this.maxMessages,maxTokens:this.maxTokens,contextWindow:this.contextWindow.map((function(t){return{role:t.role,content:t.content,timestamp:t.timestamp}})),stats:this.getStats()}}},{key:"import",value:function(t){var e=this;try{if(!t||!t.contextWindow||!Array.isArray(t.contextWindow))throw new Error("Invalid context data format");return this.clear(),t.systemPrompt&&(this.systemPrompt=t.systemPrompt),t.maxMessages&&(this.maxMessages=t.maxMessages),t.maxTokens&&(this.maxTokens=t.maxTokens),t.contextWindow.forEach((function(t){e.addMessage(t.role,t.content)})),this.debug&&console.log("[ContextManager] Imported ".concat(this.contextWindow.length," messages")),!0}catch(t){return console.error("[ContextManager] Import failed:",t),!1}}},{key:"injectKnowledge",value:function(t){if(t){var e="".concat(this.systemPrompt,"\n\nRelevant knowledge base information:\n").concat(t);this.setSystemPrompt(e),this.debug&&console.log("[ContextManager] Knowledge injected into system prompt")}}}],e&&n(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e}();t.exports&&(t.exports=o)},74:t=>{function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},e(t)}function n(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return r(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?r(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var o=0,i=function(){};return{s:i,n:function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,c=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){c=!0,a=t},f:function(){try{s||null==n.return||n.return()}finally{if(c)throw a}}}}function r(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function o(){"use strict";o=function(){return n};var t,n={},r=Object.prototype,i=r.hasOwnProperty,a=Object.defineProperty||function(t,e,n){t[e]=n.value},s="function"==typeof Symbol?Symbol:{},c=s.iterator||"@@iterator",l=s.asyncIterator||"@@asyncIterator",u=s.toStringTag||"@@toStringTag";function h(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{h({},"")}catch(t){h=function(t,e,n){return t[e]=n}}function d(t,e,n,r){var o=e&&e.prototype instanceof b?e:b,i=Object.create(o.prototype),s=new O(r||[]);return a(i,"_invoke",{value:T(t,n,s)}),i}function p(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}n.wrap=d;var f="suspendedStart",y="suspendedYield",m="executing",g="completed",v={};function b(){}function w(){}function x(){}var k={};h(k,c,(function(){return this}));var E=Object.getPrototypeOf,C=E&&E(E(N([])));C&&C!==r&&i.call(C,c)&&(k=C);var S=x.prototype=b.prototype=Object.create(k);function I(t){["next","throw","return"].forEach((function(e){h(t,e,(function(t){return this._invoke(e,t)}))}))}function P(t,n){function r(o,a,s,c){var l=p(t[o],t,a);if("throw"!==l.type){var u=l.arg,h=u.value;return h&&"object"==e(h)&&i.call(h,"__await")?n.resolve(h.__await).then((function(t){r("next",t,s,c)}),(function(t){r("throw",t,s,c)})):n.resolve(h).then((function(t){u.value=t,s(u)}),(function(t){return r("throw",t,s,c)}))}c(l.arg)}var o;a(this,"_invoke",{value:function(t,e){function i(){return new n((function(n,o){r(t,e,n,o)}))}return o=o?o.then(i,i):i()}})}function T(e,n,r){var o=f;return function(i,a){if(o===m)throw Error("Generator is already running");if(o===g){if("throw"===i)throw a;return{value:t,done:!0}}for(r.method=i,r.arg=a;;){var s=r.delegate;if(s){var c=A(s,r);if(c){if(c===v)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(o===f)throw o=g,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o=m;var l=p(e,n,r);if("normal"===l.type){if(o=r.done?g:y,l.arg===v)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(o=g,r.method="throw",r.arg=l.arg)}}}function A(e,n){var r=n.method,o=e.iterator[r];if(o===t)return n.delegate=null,"throw"===r&&e.iterator.return&&(n.method="return",n.arg=t,A(e,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),v;var i=p(o,e.iterator,n.arg);if("throw"===i.type)return n.method="throw",n.arg=i.arg,n.delegate=null,v;var a=i.arg;return a?a.done?(n[e.resultName]=a.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,v):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,v)}function M(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function L(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function O(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(M,this),this.reset(!0)}function N(n){if(n||""===n){var r=n[c];if(r)return r.call(n);if("function"==typeof n.next)return n;if(!isNaN(n.length)){var o=-1,a=function e(){for(;++o<n.length;)if(i.call(n,o))return e.value=n[o],e.done=!1,e;return e.value=t,e.done=!0,e};return a.next=a}}throw new TypeError(e(n)+" is not iterable")}return w.prototype=x,a(S,"constructor",{value:x,configurable:!0}),a(x,"constructor",{value:w,configurable:!0}),w.displayName=h(x,u,"GeneratorFunction"),n.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===w||"GeneratorFunction"===(e.displayName||e.name))},n.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,x):(t.__proto__=x,h(t,u,"GeneratorFunction")),t.prototype=Object.create(S),t},n.awrap=function(t){return{__await:t}},I(P.prototype),h(P.prototype,l,(function(){return this})),n.AsyncIterator=P,n.async=function(t,e,r,o,i){void 0===i&&(i=Promise);var a=new P(d(t,e,r,o),i);return n.isGeneratorFunction(e)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},I(S),h(S,u,"Generator"),h(S,c,(function(){return this})),h(S,"toString",(function(){return"[object Generator]"})),n.keys=function(t){var e=Object(t),n=[];for(var r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},n.values=N,O.prototype={constructor:O,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(L),!e)for(var n in this)"t"===n.charAt(0)&&i.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function r(r,o){return s.type="throw",s.arg=e,n.next=r,o&&(n.method="next",n.arg=t),!!o}for(var o=this.tryEntries.length-1;o>=0;--o){var a=this.tryEntries[o],s=a.completion;if("root"===a.tryLoc)return r("end");if(a.tryLoc<=this.prev){var c=i.call(a,"catchLoc"),l=i.call(a,"finallyLoc");if(c&&l){if(this.prev<a.catchLoc)return r(a.catchLoc,!0);if(this.prev<a.finallyLoc)return r(a.finallyLoc)}else if(c){if(this.prev<a.catchLoc)return r(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return r(a.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&i.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var o=r;break}}o&&("break"===t||"continue"===t)&&o.tryLoc<=e&&e<=o.finallyLoc&&(o=null);var a=o?o.completion:{};return a.type=t,a.arg=e,o?(this.method="next",this.next=o.finallyLoc,v):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),v},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),L(n),v}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;L(n)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:N(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),v}},n}function i(t,e,n,r,o,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(r,o)}function a(t){return function(){var e=this,n=arguments;return new Promise((function(r,o){var a=t.apply(e,n);function s(t){i(a,r,o,s,c,"next",t)}function c(t){i(a,r,o,s,c,"throw",t)}s(void 0)}))}}function s(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,c(r.key),r)}}function c(t){var n=function(t){if("object"!=e(t)||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,"string");if("object"!=e(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==e(n)?n:n+""}var l=function(){return t=function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.apiKey=e.apiKey,this.baseURL=e.baseURL||"https://openrouter.ai/api/v1",this.model=e.model||"openai/gpt-3.5-turbo",this.maxTokens=e.maxTokens||500,this.temperature=e.temperature||.7,this.siteName=e.siteName||"SenangWebs Chatbot",this.siteUrl=e.siteUrl||("undefined"!=typeof window?window.location.origin:""),this.timeout=e.timeout||3e4,this.retryAttempts=e.retryAttempts||2,this.retryDelay=e.retryDelay||1e3,this.debug=e.debug||!1,this.abortController=null,this.validateConfig()},e=[{key:"validateConfig",value:function(){if(!this.apiKey||""===this.apiKey.trim())throw new Error("OpenRouter API key is required");if(!this.baseURL||!this.baseURL.startsWith("http"))throw new Error("Invalid base URL");(this.maxTokens<1||this.maxTokens>32768)&&(console.warn("maxTokens should be between 1 and 32768, using default 500"),this.maxTokens=500),(this.temperature<0||this.temperature>2)&&(console.warn("temperature should be between 0 and 2, using default 0.7"),this.temperature=.7)}},{key:"sendMessage",value:(c=a(o().mark((function t(e,n,r,i){var a,s,c,l,u,h;return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:a=0,s=null;case 2:if(!(a<=this.retryAttempts)){t.next=35;break}return t.prev=3,this.debug&&(console.log("[OpenRouterAPI] Attempt ".concat(a+1,"/").concat(this.retryAttempts+1)),console.log("[OpenRouterAPI] Sending messages:",e)),t.next=7,this._makeRequest(e);case 7:if((c=t.sent).ok){t.next=13;break}return t.next=11,c.json().catch((function(){return{}}));case 11:throw l=t.sent,this._handleAPIError(c.status,l);case 13:return t.next=15,this._handleStreamingResponse(c,n);case 15:return u=t.sent,r&&r(u),t.abrupt("return",u);case 20:if(t.prev=20,t.t0=t.catch(3),s=t.t0,this.debug&&console.error("[OpenRouterAPI] Attempt ".concat(a+1," failed:"),t.t0),!this._shouldNotRetry(t.t0)){t.next=27;break}throw i&&i(t.t0),t.t0;case 27:if(!(++a<=this.retryAttempts)){t.next=33;break}return h=this.retryDelay*Math.pow(2,a-1),this.debug&&console.log("[OpenRouterAPI] Retrying in ".concat(h,"ms...")),t.next=33,this._sleep(h);case 33:t.next=2;break;case 35:throw i&&i(s),s;case 37:case"end":return t.stop()}}),t,this,[[3,20]])}))),function(t,e,n,r){return c.apply(this,arguments)})},{key:"_makeRequest",value:(i=a(o().mark((function t(e){var n,r,i=this;return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return this.abortController=new AbortController,n=setTimeout((function(){return i.abortController.abort()}),this.timeout),t.prev=2,t.next=5,fetch("".concat(this.baseURL,"/chat/completions"),{method:"POST",headers:{Authorization:"Bearer ".concat(this.apiKey),"Content-Type":"application/json","HTTP-Referer":this.siteUrl,"X-Title":this.siteName},body:JSON.stringify({model:this.model,messages:e,max_tokens:this.maxTokens,temperature:this.temperature,stream:!0}),signal:this.abortController.signal});case 5:return r=t.sent,clearTimeout(n),t.abrupt("return",r);case 10:throw t.prev=10,t.t0=t.catch(2),clearTimeout(n),t.t0;case 14:return t.prev=14,clearTimeout(n),t.finish(14);case 17:case"end":return t.stop()}}),t,this,[[2,10,14,17]])}))),function(t){return i.apply(this,arguments)})},{key:"_handleStreamingResponse",value:(r=a(o().mark((function t(e,r){var i,a,s,c,l,u,h,d,p,f,y,m,g,v,b,w;return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:i=e.body.getReader(),a=new TextDecoder,s="",c="",t.prev=4;case 5:return t.next=8,i.read();case 8:if(l=t.sent,u=l.done,h=l.value,!u){t.next=13;break}return t.abrupt("break",41);case 13:s+=a.decode(h,{stream:!0}),d=s.split("\n"),s=d.pop()||"",p=n(d),t.prev=17,p.s();case 19:if((f=p.n()).done){t.next=31;break}if(y=f.value,""!==(m=y.trim())){t.next=24;break}return t.abrupt("continue",29);case 24:if("data: [DONE]"!==m){t.next=26;break}return t.abrupt("continue",29);case 26:if(m.startsWith("data: ")){t.next=28;break}return t.abrupt("continue",29);case 28:try{b=JSON.parse(m.substring(6)),(w=null===(g=b.choices)||void 0===g||null===(g=g[0])||void 0===g||null===(g=g.delta)||void 0===g?void 0:g.content)&&(c+=w,r&&r({content:w,fullContent:c,done:!1})),null!==(v=b.choices)&&void 0!==v&&null!==(v=v[0])&&void 0!==v&&v.finish_reason&&this.debug&&console.log("[OpenRouterAPI] Stream finished:",b.choices[0].finish_reason)}catch(t){this.debug&&console.warn("[OpenRouterAPI] Failed to parse SSE data:",m,t)}case 29:t.next=19;break;case 31:t.next=36;break;case 33:t.prev=33,t.t0=t.catch(17),p.e(t.t0);case 36:return t.prev=36,p.f(),t.finish(36);case 39:t.next=5;break;case 41:return t.abrupt("return",{content:c,model:this.model,done:!0});case 44:if(t.prev=44,t.t1=t.catch(4),"AbortError"!==t.t1.name){t.next=48;break}throw new Error("Request cancelled by user");case 48:throw t.t1;case 49:case"end":return t.stop()}}),t,this,[[4,44],[17,33,36,39]])}))),function(t,e){return r.apply(this,arguments)})},{key:"_handleAPIError",value:function(t,e){var n,r=(null===(n=e.error)||void 0===n?void 0:n.message)||"Unknown error occurred";switch(t){case 401:return new Error("Invalid API key. Please check your OpenRouter API key.");case 403:return new Error("Access forbidden. Please check your API key permissions.");case 429:var o=new Error("Rate limit exceeded. Please try again later.");return o.isRateLimit=!0,o;case 500:case 502:case 503:return new Error("OpenRouter service is temporarily unavailable. Please try again.");case 400:return new Error("Bad request: ".concat(r));default:return new Error("API error (".concat(t,"): ").concat(r))}}},{key:"_shouldNotRetry",value:function(t){return!!(t.message.includes("Invalid API key")||t.message.includes("Access forbidden")||t.message.includes("Bad request")||t.message.includes("cancelled by user"))}},{key:"cancel",value:function(){this.abortController&&(this.abortController.abort(),this.debug&&console.log("[OpenRouterAPI] Request cancelled"))}},{key:"getModelInfo",value:function(){return{model:this.model,maxTokens:this.maxTokens,temperature:this.temperature}}},{key:"_sleep",value:function(t){return new Promise((function(e){return setTimeout(e,t)}))}}],e&&s(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,r,i,c}();t.exports&&(t.exports=l)},982:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function o(){o=function(){return e};var t,e={},n=Object.prototype,i=n.hasOwnProperty,a=Object.defineProperty||function(t,e,n){t[e]=n.value},s="function"==typeof Symbol?Symbol:{},c=s.iterator||"@@iterator",l=s.asyncIterator||"@@asyncIterator",u=s.toStringTag||"@@toStringTag";function h(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{h({},"")}catch(t){h=function(t,e,n){return t[e]=n}}function d(t,e,n,r){var o=e&&e.prototype instanceof b?e:b,i=Object.create(o.prototype),s=new O(r||[]);return a(i,"_invoke",{value:T(t,n,s)}),i}function p(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=d;var f="suspendedStart",y="suspendedYield",m="executing",g="completed",v={};function b(){}function w(){}function x(){}var k={};h(k,c,(function(){return this}));var E=Object.getPrototypeOf,C=E&&E(E(N([])));C&&C!==n&&i.call(C,c)&&(k=C);var S=x.prototype=b.prototype=Object.create(k);function I(t){["next","throw","return"].forEach((function(e){h(t,e,(function(t){return this._invoke(e,t)}))}))}function P(t,e){function n(o,a,s,c){var l=p(t[o],t,a);if("throw"!==l.type){var u=l.arg,h=u.value;return h&&"object"==r(h)&&i.call(h,"__await")?e.resolve(h.__await).then((function(t){n("next",t,s,c)}),(function(t){n("throw",t,s,c)})):e.resolve(h).then((function(t){u.value=t,s(u)}),(function(t){return n("throw",t,s,c)}))}c(l.arg)}var o;a(this,"_invoke",{value:function(t,r){function i(){return new e((function(e,o){n(t,r,e,o)}))}return o=o?o.then(i,i):i()}})}function T(e,n,r){var o=f;return function(i,a){if(o===m)throw Error("Generator is already running");if(o===g){if("throw"===i)throw a;return{value:t,done:!0}}for(r.method=i,r.arg=a;;){var s=r.delegate;if(s){var c=A(s,r);if(c){if(c===v)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(o===f)throw o=g,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);o=m;var l=p(e,n,r);if("normal"===l.type){if(o=r.done?g:y,l.arg===v)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(o=g,r.method="throw",r.arg=l.arg)}}}function A(e,n){var r=n.method,o=e.iterator[r];if(o===t)return n.delegate=null,"throw"===r&&e.iterator.return&&(n.method="return",n.arg=t,A(e,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),v;var i=p(o,e.iterator,n.arg);if("throw"===i.type)return n.method="throw",n.arg=i.arg,n.delegate=null,v;var a=i.arg;return a?a.done?(n[e.resultName]=a.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,v):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,v)}function M(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function L(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function O(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(M,this),this.reset(!0)}function N(e){if(e||""===e){var n=e[c];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,a=function n(){for(;++o<e.length;)if(i.call(e,o))return n.value=e[o],n.done=!1,n;return n.value=t,n.done=!0,n};return a.next=a}}throw new TypeError(r(e)+" is not iterable")}return w.prototype=x,a(S,"constructor",{value:x,configurable:!0}),a(x,"constructor",{value:w,configurable:!0}),w.displayName=h(x,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===w||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,x):(t.__proto__=x,h(t,u,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},I(P.prototype),h(P.prototype,l,(function(){return this})),e.AsyncIterator=P,e.async=function(t,n,r,o,i){void 0===i&&(i=Promise);var a=new P(d(t,n,r,o),i);return e.isGeneratorFunction(n)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},I(S),h(S,u,"Generator"),h(S,c,(function(){return this})),h(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),n=[];for(var r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},e.values=N,O.prototype={constructor:O,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(L),!e)for(var n in this)"t"===n.charAt(0)&&i.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function r(r,o){return s.type="throw",s.arg=e,n.next=r,o&&(n.method="next",n.arg=t),!!o}for(var o=this.tryEntries.length-1;o>=0;--o){var a=this.tryEntries[o],s=a.completion;if("root"===a.tryLoc)return r("end");if(a.tryLoc<=this.prev){var c=i.call(a,"catchLoc"),l=i.call(a,"finallyLoc");if(c&&l){if(this.prev<a.catchLoc)return r(a.catchLoc,!0);if(this.prev<a.finallyLoc)return r(a.finallyLoc)}else if(c){if(this.prev<a.catchLoc)return r(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return r(a.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&i.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var o=r;break}}o&&("break"===t||"continue"===t)&&o.tryLoc<=e&&e<=o.finallyLoc&&(o=null);var a=o?o.completion:{};return a.type=t,a.arg=e,o?(this.method="next",this.next=o.finallyLoc,v):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),v},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),L(n),v}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;L(n)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:N(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),v}},e}function i(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,o,i,a,s=[],c=!0,l=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=i.call(n)).done)&&(s.push(r.value),s.length!==e);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw o}}return s}}(t,e)||function(t,e){if(t){if("string"==typeof t)return a(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?a(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function a(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function s(t,e,n,r,o,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(r,o)}function c(t){return function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function a(t){s(i,r,o,a,c,"next",t)}function c(t){s(i,r,o,a,c,"throw",t)}a(void 0)}))}}function l(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,u(r.key),r)}}function u(t){var e=function(t){if("object"!=r(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=r(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==r(e)?e:e+""}var h,d;try{h=n(74),d=n(708)}catch(t){}"undefined"!=typeof window&&(window.OpenRouterAPI||void 0===h||(window.OpenRouterAPI=h),window.ContextManager||void 0===d||(window.ContextManager=d),h=window.OpenRouterAPI||h,d=window.ContextManager||d);var p=function(){return t=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;if(function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.knowledgeBase=e,this.currentNode=null,this.chatHistory=[],this.botMetadata={botName:n.botName||"Bot",themeColor:n.themeColor||"#007bff",timestamp:(new Date).toISOString()},this.apiConfig=r,this.mode=(null==r?void 0:r.mode)||"keyword-only",this.streamingEnabled=!1!==(null==r?void 0:r.streaming),this.aiResponseInProgress=!1,this.hybridThreshold=(null==r?void 0:r.hybridThreshold)||.3,r&&r.apiKey)try{void 0!==h?this.apiClient=new h(r):(console.error("[SWC] OpenRouterAPI class not found. Please include openrouter-client.js"),this.apiClient=null),void 0!==d?this.contextManager=new d({systemPrompt:r.systemPrompt||"You are a helpful assistant.",maxMessages:r.contextMaxMessages||10,maxTokens:r.contextMaxTokens||2e3,debug:r.debug||!1}):(console.error("[SWC] ContextManager class not found. Please include context-manager.js"),this.contextManager=null)}catch(t){console.error("[SWC] Error initializing API components:",t),this.apiClient=null,this.contextManager=null}else this.apiClient=null,this.contextManager=null},e=[{key:"init",value:function(){this.currentNode=this.knowledgeBase.find((function(t){return"welcome"===t.id}))||this.knowledgeBase[0];var t={reply:this.currentNode.reply,options:this.currentNode.options};return this.addToHistory("bot",this.currentNode.reply,this.currentNode.id,this.currentNode.options),t}},{key:"addToHistory",value:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"keyword",i=arguments.length>5&&void 0!==arguments[5]?arguments[5]:null,a={id:"msg-".concat(Date.now(),"-").concat(Math.random().toString(36).substring(2,11)),timestamp:(new Date).toISOString(),type:t,content:e,source:o};"bot"===t&&(a.nodeId=n,r&&r.length>0&&(a.options=r),i&&(a.model=i.model)),this.chatHistory.push(a)}},{key:"handleInput",value:(r=c(o().mark((function t(e){var n,r,a,s,c,l,u,h,d=this,p=arguments;return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=p.length>1&&void 0!==p[1]?p[1]:{},r=e.toLowerCase(),a=r.split(/\s+/),this.addToHistory("user",e),this.contextManager&&this.contextManager.addMessage("user",e),s={},this.knowledgeBase.forEach((function(t){s[t.id]=0,t.keyword.forEach((function(e){var n=e.toLowerCase();a.forEach((function(e){(e.includes(n)||n.includes(e))&&s[t.id]++}))}))})),c=null,l=0,Object.entries(s).forEach((function(t){var e=i(t,2),n=e[0],r=e[1];r>l&&(l=r,c=d.knowledgeBase.find((function(t){return t.id===n})))})),u=0,l>0&&(u=Math.min(.5+.1*(l-1),1)),"hybrid"===this.mode&&console.log("[SWC Hybrid Debug]",{input:e,bestMatch:c?c.id:null,maxScore:l,confidence:u,threshold:this.hybridThreshold,willUseAI:!c||u<this.hybridThreshold}),"ai-only"!==this.mode||!this.apiClient){t.next=19;break}return t.next=16,this.handleAIResponse(e,n);case 16:return t.abrupt("return",t.sent);case 19:if("hybrid"!==this.mode||!this.apiClient){t.next=26;break}if(c&&!(u<this.hybridThreshold)){t.next=24;break}return t.next=23,this.handleAIResponse(e,n);case 23:return t.abrupt("return",t.sent);case 24:t.next=27;break;case 26:"keyword-only"===this.mode||this.apiClient;case 27:if(!c){t.next=34;break}return this.currentNode=c,this.addToHistory("bot",c.reply,c.id,c.options,"keyword"),this.contextManager&&this.contextManager.addMessage("assistant",c.reply),t.abrupt("return",{reply:c.reply,options:c.options,source:"keyword",confidence:u});case 34:if("hybrid"!==this.mode||!this.apiClient){t.next=38;break}return t.next=37,this.handleAIResponse(e,n);case 37:return t.abrupt("return",t.sent);case 38:return h="I'm sorry, I didn't understand that. Can you please rephrase?",this.addToHistory("bot",h,null,null,"fallback"),t.abrupt("return",{reply:h,options:null,source:"fallback"});case 41:case"end":return t.stop()}}),t,this)}))),function(t){return r.apply(this,arguments)})},{key:"handleAIResponse",value:(n=c(o().mark((function t(e){var n,r,i,a,s,c=this,l=arguments;return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=l.length>1&&void 0!==l[1]?l[1]:{},this.apiClient){t.next=4;break}return console.error("[SWC] API client not initialized"),t.abrupt("return",{reply:"AI features are not configured properly.",options:null,source:"error"});case 4:if(!this.aiResponseInProgress){t.next=7;break}return console.warn("[SWC] AI response already in progress"),t.abrupt("return",{reply:"Please wait for the current response to complete.",options:null,source:"error"});case 7:if(this.aiResponseInProgress=!0,t.prev=8,this.contextManager){t.next=11;break}throw new Error("Context manager not initialized");case 11:return r=this.contextManager.getContext(!0),i=!1,t.next=16,this.apiClient.sendMessage(r,(function(t){!i&&n.onStart&&(n.onStart(),i=!0),t.fullContent,n.onChunk&&n.onChunk(t)}),(function(t){var e=c.apiClient.getModelInfo();c.addToHistory("bot",t.content,null,null,"api",e),c.contextManager&&c.contextManager.addMessage("assistant",t.content),n.onComplete&&n.onComplete(t)}),(function(t){console.error("[SWC] AI response error:",t),n.onError&&n.onError(t)}));case 16:return a=t.sent,this.aiResponseInProgress=!1,t.abrupt("return",{reply:a.content,options:null,source:"api",model:a.model});case 21:return t.prev=21,t.t0=t.catch(8),this.aiResponseInProgress=!1,console.error("[SWC] Error in handleAIResponse:",t.t0),s=this._getErrorMessage(t.t0),this.addToHistory("bot",s,null,null,"error"),n.onError&&n.onError(t.t0),t.abrupt("return",{reply:s,options:null,source:"error"});case 29:case"end":return t.stop()}}),t,this,[[8,21]])}))),function(t){return n.apply(this,arguments)})},{key:"cancelAIResponse",value:function(){return!(!this.apiClient||!this.aiResponseInProgress||(this.apiClient.cancel(),this.aiResponseInProgress=!1,0))}},{key:"_getErrorMessage",value:function(t){return t.message.includes("Invalid API key")?"⚠️ API authentication failed. Please check your API key configuration.":t.message.includes("Rate limit")?"⚠️ Too many requests. Please wait a moment and try again.":t.message.includes("cancelled")?"Response cancelled.":t.message.includes("service is temporarily unavailable")?"⚠️ The AI service is temporarily unavailable. Please try again later.":"⚠️ An error occurred: ".concat(t.message)}},{key:"_enhancePromptWithKnowledge",value:function(t){var e=[],n=t.toLowerCase();if(this.knowledgeBase.forEach((function(t){t.keyword.forEach((function(r){n.includes(r.toLowerCase())&&e.push(t)}))})),e.length>0){var r=e.map((function(t){return"Topic: ".concat(t.id,"\nInformation: ").concat(t.reply)})).join("\n\n");this.contextManager.injectKnowledge(r)}}},{key:"getAPIStatus",value:function(){return{enabled:!!this.apiClient,mode:this.mode,streaming:this.streamingEnabled,model:this.apiClient?this.apiClient.getModelInfo():null,contextStats:this.contextManager?this.contextManager.getStats():null,responseInProgress:this.aiResponseInProgress}}},{key:"handleOptionSelection",value:function(t){var e=this.knowledgeBase.find((function(e){return e.id===t}));if(e)return this.currentNode=e,this.addToHistory("bot",e.reply,e.id,e.options),{reply:e.reply,options:e.options};var n="I'm sorry, I couldn't find the appropriate response. How else can I assist you?";return this.addToHistory("bot",n,null,null),{reply:n,options:null}}},{key:"exportHistory",value:function(){var t={version:"2.0",timestamp:(new Date).toISOString(),botName:this.botMetadata.botName,themeColor:this.botMetadata.themeColor,messages:this.chatHistory,currentNodeId:this.currentNode?this.currentNode.id:null,mode:this.mode,apiEnabled:!!this.apiClient,apiConfig:this.apiClient?{model:this.apiClient.model,lastUsed:(new Date).toISOString()}:null};return JSON.stringify(t,null,2)}},{key:"getCurrentState",value:function(){return{currentNodeId:this.currentNode?this.currentNode.id:null,messageCount:this.chatHistory.length,lastMessageTimestamp:this.chatHistory.length>0?this.chatHistory[this.chatHistory.length-1].timestamp:null}}},{key:"loadHistory",value:function(t){var e=this;try{var n="string"==typeof t?JSON.parse(t):t;if(!n.version||!n.messages||!Array.isArray(n.messages))throw new Error("Invalid history format: missing required fields");if(n.version.startsWith("1.")||n.version.startsWith("2.")||console.warn("History version ".concat(n.version," may not be fully compatible")),n.botName&&(this.botMetadata.botName=n.botName),n.themeColor&&(this.botMetadata.themeColor=n.themeColor),this.chatHistory=n.messages,n.currentNodeId){var r=this.knowledgeBase.find((function(t){return t.id===n.currentNodeId}));r&&(this.currentNode=r)}return this.contextManager&&n.messages&&(this.contextManager.clear(),n.messages.forEach((function(t){"user"===t.type?e.contextManager.addMessage("user",t.content):"bot"===t.type&&e.contextManager.addMessage("assistant",t.content)}))),{success:!0,messageCount:this.chatHistory.length,messages:this.chatHistory}}catch(t){return console.error("Error loading history:",t),{success:!1,error:t.message,messages:[]}}}},{key:"clearHistory",value:function(){return this.chatHistory=[],this.currentNode=this.knowledgeBase.find((function(t){return"welcome"===t.id}))||this.knowledgeBase[0],this.currentNode&&this.addToHistory("bot",this.currentNode.reply,this.currentNode.id,this.currentNode.options),{reply:this.currentNode?this.currentNode.reply:"",options:this.currentNode?this.currentNode.options:null}}},{key:"getHistory",value:function(){return{version:"2.0",timestamp:(new Date).toISOString(),botName:this.botMetadata.botName,themeColor:this.botMetadata.themeColor,messages:this.chatHistory,currentNodeId:this.currentNode?this.currentNode.id:null,mode:this.mode,apiEnabled:!!this.apiClient}}}],e&&l(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,n,r}(),f=[{id:"welcome",keyword:["hello","hi","hey"],reply:'Welcome! How can I assist you <b>today?</b> <a href="https://senangwebs.com">senangwebs.com</a>',options:[{label:"Get Help",reply_id:"help"},{label:"End Chat",reply_id:"goodbye"}]},{id:"help",keyword:["help","support","assist"],reply:"Sure, I can help! What do you need assistance with?",options:[{label:"Product Information",reply_id:"product"},{label:"Billing",reply_id:"billing"},{label:"Technical Support",reply_id:"tech_support"}]},{id:"product",keyword:["product","information"],reply:"Our product is designed to make your life easier. Would you like to know more about its features or pricing?",options:[{label:"Features",reply_id:"features"},{label:"Pricing",reply_id:"pricing"}]},{id:"billing",keyword:["billing","payment","invoice"],reply:"For billing inquiries, please visit our billing portal or contact our finance department at billing@example.com.",options:[{label:"Back to Help",reply_id:"help"},{label:"End Chat",reply_id:"goodbye"}]},{id:"tech_support",keyword:["technical","support","issue"],reply:"For technical support, please describe your issue in detail and well do our best to assist you."},{id:"features",keyword:["features","functionality"],reply:"Our product offers cutting-edge features including AI-powered analytics, real-time collaboration, and seamless integration with popular tools.",options:[{label:"Back to Product Info",reply_id:"product"},{label:"End Chat",reply_id:"goodbye"}]},{id:"pricing",keyword:["pricing","cost","plans"],reply:"We offer flexible pricing plans starting at $9.99/month. For detailed pricing information, please visit our website or contact our sales team.",options:[{label:"Back to Product Info",reply_id:"product"},{label:"End Chat",reply_id:"goodbye"}]},{id:"goodbye",keyword:["bye","goodbye","end"],reply:"Thank you for chatting with us. Have a great day!",options:[{label:"Restart Chat",reply_id:"welcome"}]}];function y(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;document.querySelectorAll("[data-swc]").forEach((function(e){if(!e.chatbotInstance&&(t||!e.hasAttribute("data-swc-manual-init"))){var n=e.getAttribute("data-swc-theme-color")||"#007bff",r=e.getAttribute("data-swc-bot-name")||"Bot",i=e.getAttribute("data-swc-chat-display")||"classic",a=parseInt(e.getAttribute("data-swc-reply-duration"))||0,s=e.getAttribute("data-swc-load"),l=e.getAttribute("data-swc-api-mode"),u=e.getAttribute("data-swc-api-key"),h=e.getAttribute("data-swc-api-model"),d=e.getAttribute("data-swc-api-streaming"),y=e.getAttribute("data-swc-api-max-tokens"),m=e.getAttribute("data-swc-api-temperature"),g=e.getAttribute("data-swc-system-prompt"),v=e.getAttribute("data-swc-context-max-messages"),b=e.getAttribute("data-swc-api-base-url"),w=e.getAttribute("data-swc-hybrid-threshold"),x=null;(u||b)&&"keyword-only"!==l&&(x={apiKey:u||"proxy-mode",mode:l||"hybrid",model:h||"openai/gpt-3.5-turbo",streaming:"false"!==d,maxTokens:parseInt(y)||500,temperature:parseFloat(m)||.7,systemPrompt:g||"You are a helpful assistant.",contextMaxMessages:parseInt(v)||10,baseURL:b,hybridThreshold:parseFloat(w)||.3,siteName:r,siteUrl:window.location.origin},!u||b&&!b.includes("openrouter.ai")||console.warn("[SWC] ⚠️ API key is exposed in client-side code. For production, use a server-side proxy."));var k=new p(t||f,{botName:r,themeColor:n},x);e.chatbotInstance=k;var E=function(t,e,n,r){var o=document.createElement("div");o.className="swc-chat-display ".concat("modern"===r?"swc-modern":"swc-classic");var i=document.createElement("div");i.className="swc-input-container";var a=document.createElement("input");a.type="text",a.className="swc-user-input",a.placeholder="Type your message...";var s=document.createElement("button");s.className="swc-send-button",s.textContent="Send";var c=document.createElement("div");c.className="swc-options-container",i.appendChild(a),i.appendChild(s);var l=document.createElement("div");return l.className="swc-typing-indicator",l.innerHTML="<span></span><span></span><span></span>",t.appendChild(o),t.appendChild(c),t.appendChild(i),t.style.setProperty("--swc-theme-color",e),t.style.setProperty("--swc-bot-name",'"'.concat(n,'"')),{chatDisplay:o,userInput:a,sendButton:s,optionsContainer:c,typingIndicator:l,inputContainer:i}}(e,n,r,i),C=E.chatDisplay,S=E.userInput,I=E.sendButton,P=E.optionsContainer,T=E.typingIndicator,A=E.inputContainer;I.addEventListener("click",B),S.addEventListener("keypress",(function(t){"Enter"===t.key&&B()}));var M=k.clearHistory.bind(k);k.clearHistory=function(){var t=M();return H(),W(t.reply,t.options),e.dispatchEvent(new CustomEvent("swc:history-cleared",{detail:{timestamp:(new Date).toISOString()}})),t};var L=k.exportHistory.bind(k);k.exportHistory=function(){var t=L();return e.dispatchEvent(new CustomEvent("swc:history-exported",{detail:{messageCount:k.chatHistory.length,historyJSON:t,timestamp:(new Date).toISOString()}})),t};var O=k.loadHistory.bind(k);if(k.loadHistory=function(t){var n=O(t);if(n.success){if(H(),n.messages.forEach((function(t){var e,n;e=t,(n=document.createElement("div")).className="swc-message swc-".concat(e.type,"-message"),"user"===e.type?n.textContent=e.content:R(e.content)?n.innerHTML=e.content:n.textContent=e.content,C.appendChild(n)})),n.messages.length>0){var r=n.messages[n.messages.length-1];r.options&&r.options.length>0&&(P.style.display="flex",r.options.forEach((function(t){var e=document.createElement("button");e.textContent=t.label,e.onclick=function(){return D(t.reply_id)},P.appendChild(e)})))}J(C),e.dispatchEvent(new CustomEvent("swc:history-loaded",{detail:{messageCount:n.messageCount,timestamp:(new Date).toISOString()}}))}else console.error("Failed to load history:",n.error);return n},s)if(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("./")||s.startsWith("../")||s.endsWith(".json"))fetch(s).then((function(t){if(!t.ok)throw new Error("HTTP error! status: ".concat(t.status));return t.json()})).then((function(t){k.loadHistory(t)})).catch((function(t){console.error("Error loading history from file:",t);var e=k.init();W(e.reply,e.options)}));else try{var N=JSON.parse(s);k.loadHistory(N)}catch(t){console.error("Error parsing inline history JSON:",t);var _=k.init();W(_.reply,_.options)}else{var j=k.init();W(j.reply,j.options)}}function R(t){return!/<script|javascript:|on\w+\s*=/i.test(t)}function H(){C.innerHTML="",P.innerHTML="",P.style.display="none"}function W(t,e){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"keyword";K();var o=document.createElement("div");return o.className="swc-message swc-bot-message ".concat(n?"swc-streaming":""," ").concat("api"===r?"swc-ai-message":""),"api"!==r&&R(t)?o.innerHTML=t:o.textContent=t,o.setAttribute("data-message-id","msg-".concat(Date.now())),C.appendChild(o),J(C),P.innerHTML="",e&&e.length>0?(P.style.display="flex",e.forEach((function(t){var e=document.createElement("button");e.textContent=t.label,e.onclick=function(){return D(t.reply_id)},P.appendChild(e)}))):P.style.display="none",o}function B(){return F.apply(this,arguments)}function F(){return(F=c(o().mark((function t(){var e,n;return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:(e=S.value.trim())&&((n=document.createElement("div")).className="swc-message swc-user-message",n.textContent=e,C.appendChild(n),J(C),S.value="",G(),q(),"keyword-only"!==k.mode&&k.apiClient&&0===a?setTimeout(c(o().mark((function t(){var n,r,i;return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=null,r=null,t.next=4,k.handleInput(e,{onStart:function(){var t;K(),n=W("",null,!0,"api"),k.streamingEnabled&&((t=document.createElement("button")).className="swc-stop-button",t.innerHTML="Stop",t.onclick=function(){k.cancelAIResponse(),t.remove(),U()},r=t,A.insertBefore(r,A.firstChild))},onChunk:function(t){n&&requestAnimationFrame((function(){n.textContent=t.fullContent,J(C)}))},onComplete:function(t){n&&n.classList.remove("swc-streaming"),r&&r.remove(),U()},onError:function(t){r&&r.remove(),n&&(n.classList.remove("swc-streaming"),n.classList.add("swc-error-message")),U()}});case 4:i=t.sent,n||(W(i.reply,i.options,!1,i.source),U());case 6:case"end":return t.stop()}}),t)}))),500):setTimeout(c(o().mark((function t(){var n;return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,k.handleInput(e);case 2:W((n=t.sent).reply,n.options,!1,n.source),U();case 5:case"end":return t.stop()}}),t)}))),a));case 2:case"end":return t.stop()}}),t)})))).apply(this,arguments)}function D(t){G(),q();var e=Math.max(a,500);setTimeout((function(){var e=k.handleOptionSelection(t);W(e.reply,e.options),U()}),e)}function G(){S.disabled=!0,I.disabled=!0}function U(){S.disabled=!1,I.disabled=!1}function q(){K(),C.appendChild(T),J(C)}function K(){T.parentNode===C&&C.removeChild(T)}function J(t){var e=t.scrollHeight-t.clientHeight,n=t.scrollTop,r=e-n,o=null;window.requestAnimationFrame((function e(i){o||(o=i);var a,s,c,l=i-o;t.scrollTop=(a=l,s=n,c=r,(a/=150)<1?c/2*a*a*a+s:c/2*((a-=2)*a*a+2)+s),l<300&&window.requestAnimationFrame(e)}))}}))}"undefined"!=typeof window&&(window.initializeChatbot=y,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(function(){y()})):y())},542:(t,e,n)=>{"use strict";n.r(e)}},e={};function n(r){var o=e[r];if(void 0!==o)return o.exports;var i=e[r]={exports:{}};return t[r](i,i.exports,n),i.exports}return n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n(74),n(708),n(982),n(542)})()));