/**
 * Skipped minification because the original files appears to be already minified.
 * Original file: /npm/xzx-chat-kit-vue2@0.1.7/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
"use strict";var e=Object.defineProperty,s=Object.defineProperties,t=Object.getOwnPropertyDescriptors,o=Object.getOwnPropertySymbols,a=Object.prototype.hasOwnProperty,n=Object.prototype.propertyIsEnumerable,r=(s,t,o)=>t in s?e(s,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):s[t]=o,i=(e,s)=>{for(var t in s||(s={}))a.call(s,t)&&r(e,t,s[t]);if(o)for(var t of o(s))n.call(s,t)&&r(e,t,s[t]);return e},l=(e,o)=>s(e,t(o)),h=(e,s,t)=>(r(e,"symbol"!=typeof s?s+"":s,t),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const c=require("vue-demi"),u=c.defineComponent({name:"MessageList",props:{messages:{type:Array,default:()=>[]},showAvatar:{type:Boolean,default:!0},scrollTolerance:{type:Number,default:10}},data:()=>({messagesEnd:null,shouldAutoScroll:!0,previousMessagesLength:0}),mounted(){this.previousMessagesLength=this.messages.length,this.scrollToBottom(),this.setupScrollListener()},updated(){this.shouldAutoScroll&&this.scrollToBottom()},watch:{messages:{handler(e){this.$nextTick((()=>{var s;const t=e.length>this.previousMessagesLength&&!0===(null==(s=e[e.length-1])?void 0:s.isUser);(t||this.shouldAutoScroll)&&(this.scrollToBottom(),t&&(this.shouldAutoScroll=!0)),this.previousMessagesLength=e.length}))},deep:!0}},methods:{scrollToBottom(){this.$nextTick((()=>{const e=this.$refs.messagesEnd;e&&e.scrollIntoView({behavior:"smooth"})}))},setupScrollListener(){this.$nextTick((()=>{const e=this.$el;e&&e.addEventListener("scroll",this.handleScroll)}))},handleScroll(){const e=this.$el;if(e){const{scrollTop:s,scrollHeight:t,clientHeight:o}=e,a=s+o>=t-this.scrollTolerance;this.shouldAutoScroll=a}}},beforeUnmount(){const e=this.$el;e&&e.removeEventListener("scroll",this.handleScroll)},beforeDestroy(){const e=this.$el;e&&e.removeEventListener("scroll",this.handleScroll)},render(){const e=c.isVue2?this.$scopedSlots:this.$slots,s=this.messages.map((s=>c.h("div",{key:s.id,class:["ck-message",s.isUser?"ck-message__user":"ck-message__other"]},[!s.isUser&&this.showAvatar?c.h("div",{class:"ck-message__avatar"},[c.h("div",{class:"ck-message__avatar-placeholder"})]):null,c.h("div",{class:"component"===(null==s?void 0:s.type)?"ck-message__component":"ck-message__content"},[e&&e.message?e.message(s):s.content])].filter(Boolean))));return c.h("div",{class:"ck-messages"},[(null==e?void 0:e["start-here"])&&e["start-here"](),this.messages.length>0?s:(null==e?void 0:e.empty)&&e.empty()||null,c.h("div",{ref:"messagesEnd"})])}}),p=c.defineComponent({name:"MessageInput",props:{placeholder:{type:String,default:"请输入消息..."}},data:()=>({inputValue:""}),methods:{handleInput(e){this.inputValue=e},handleSend(){const e=this.inputValue.trim();e&&(this.$emit("send",e),this.inputValue="")}},render(){const e={value:this.inputValue,onInput:this.handleInput,onSend:this.handleSend,placeholder:this.placeholder},s=c.isVue2?this.$scopedSlots:this.$slots;return(null==s?void 0:s.input)?c.h("div",{class:"ck-input__area"},[s.input(e)]):c.h("div",{class:"ck-input__area"},[c.h("div",{class:"ck-input__wrapper"},[c.h("input",i({class:"ck-input__field"},c.isVue2?{attrs:{placeholder:this.placeholder},domProps:{value:this.inputValue},on:{input:e=>{const s=e.target;this.handleInput(s.value)},keyup:e=>{"Enter"===e.key&&this.handleSend()}}}:{placeholder:this.placeholder,value:this.inputValue,onInput:e=>{const s=e.target;this.handleInput(s.value)},onKeyup:e=>{"Enter"===e.key&&this.handleSend()}})),c.h("button",i({class:"ck-input__button"},c.isVue2?{attrs:{disabled:!this.inputValue.trim()},on:{click:this.handleSend}}:{disabled:!this.inputValue.trim(),onClick:this.handleSend}),"发送")])])}}),d=c.defineComponent({name:"ChatBox",components:{MessageList:u,MessageInput:p},props:{chatCore:{type:Object,required:!0}},setup(e){const s=c.ref([]),t=c.ref("请输入消息..."),o=c.ref(!0),a=c.ref(10),n=c.ref(null);c.onMounted((()=>{e.chatCore.setMessagesChangeCallback((e=>{s.value=e})),e.chatCore.setScrollToBottomCallback((()=>{const e=n.value;e&&e.scrollToBottom&&e.scrollToBottom()}));const r=e.chatCore.getState();s.value=r.messages,t.value=r.placeholder,o.value=r.showAvatar,a.value=e.chatCore.getScrollTolerance()}));return{messages:s,placeholder:t,showAvatar:o,scrollTolerance:a,messageListRef:n,sendMessage:t=>{e.chatCore.sendMessage(t),s.value=e.chatCore.getMessages()}}},render(){const e=c.isVue2?this.$scopedSlots:this.$slots,s={},t={};return(null==e?void 0:e.empty)&&(s.empty=()=>e.empty()),(null==e?void 0:e.message)&&(s.message=s=>e.message(s)),(null==e?void 0:e["start-here"])&&(s["start-here"]=()=>e["start-here"]()),(null==e?void 0:e.input)&&(t.input=s=>e.input(s)),c.h("div",{class:"ck-chat"},[c.h("div",{class:"ck-chat__wrapper"},[c.h(u,i(i({ref:"messageListRef"},c.isVue2?{props:{messages:this.messages,showAvatar:this.showAvatar,scrollTolerance:this.scrollTolerance}}:{messages:this.messages,showAvatar:this.showAvatar,scrollTolerance:this.scrollTolerance}),c.isVue2&&Object.keys(s).length>0?{scopedSlots:s}:{}),c.isVue2?void 0:s),c.h(p,i(i(i({},c.isVue2?{props:{placeholder:this.placeholder}}:{placeholder:this.placeholder}),c.isVue2?{on:{send:this.sendMessage}}:{onSend:this.sendMessage}),c.isVue2&&Object.keys(t).length>0?{scopedSlots:t}:{}),c.isVue2?void 0:t)])])}});function g(e,s={}){const{speed:t=50,delay:o=0,skipHtmlTags:a=!0,onComplete:n,onProgress:r}=s,i=c.ref("");let l=!1,h=!1,u=null;const p=a?function(e){const s=/<[^>]+>/g,t=[];let o,a=0;for(;null!==(o=s.exec(e));){if(o.index>a){const s=e.slice(a,o.index);s&&t.push({type:"text",content:s})}t.push({type:"html",content:o[0]}),a=o.index+o[0].length}if(a<e.length){const s=e.slice(a);s&&t.push({type:"text",content:s})}return t}(e):[{type:"text",content:e}];let d=0,g=0,m=0,v=0;p.forEach((e=>{"text"===e.type&&(m+=e.content.length)}));const f=()=>{if(!l||h||d>=p.length)return;const e=p[d];if("html"===e.type)return i.value+=e.content,d++,g=0,void(d<p.length?u=window.setTimeout(f,0):(l=!1,n&&n()));if(g<e.content.length){if(i.value+=e.content[g],g++,v++,r&&m>0){const e=v/m;r(i.value,e)}u=window.setTimeout(f,t)}else d++,g=0,d<p.length?u=window.setTimeout(f,0):(l=!1,n&&n())},y={start(){l||(l=!0,h=!1,o>0?u=window.setTimeout(f,o):f())},pause(){l&&!h&&(h=!0,u&&(clearTimeout(u),u=null))},resume(){l&&h&&(h=!1,f())},stop(){l=!1,h=!1,u&&(clearTimeout(u),u=null)},reset(){y.stop(),d=0,g=0,v=0,i.value=""},isRunning:()=>l,isPaused:()=>h};return{displayText:i,controller:y}}function m(e,s){const{autoComplete:t,removeExtra:o}=s,a=[],n=[];let r=e;for(let i=0;i<e.length;i++){const s=e[i];if("{"===s||"["===s)a.push({char:s,index:i});else if("}"===s||"]"===s){const e="}"===s?"{":"[";let t=!1;for(let s=a.length-1;s>=0;s--)if(a[s].char===e){if(o)for(let e=s+1;e<a.length;e++)n.push(a[e].index);a.splice(s),t=!0;break}!t&&o&&n.push(i)}}if(t){const e=a.reverse();for(const s of e){r+="{"===s.char?"}":"]"}}else if(o)for(const i of a)n.push(i.index);if(o&&n.length>0){n.sort(((e,s)=>s-e));for(const e of n)r=r.slice(0,e)+r.slice(e+1)}return r}function v(e){e.component("XzxChatBox",d)}const f={install:v,ChatBox:d};"undefined"!=typeof window&&c.install,exports.ChatBox=d,exports.ChatCore=class{constructor(e={}){var s;h(this,"state"),h(this,"options"),h(this,"messageIdCounter",0),h(this,"onMessagesChange"),h(this,"onScrollToBottom"),h(this,"unwatchMessages"),this.options=e;const t=e.messages||[],o=this.deepCloneMessages(t);o.forEach((e=>{this.normalizeMessage(e)})),this.state={messages:o,placeholder:e.placeholder||"请输入消息...",showAvatar:null==(s=e.showAvatar)||s},this.state.messages.length>0&&(this.messageIdCounter=Math.max(...this.state.messages.map((e=>Number(e.id))))),this.setupReactiveMessages(e.messages)}deepCloneMessages(e){return Array.isArray(e)?e.map((e=>{const s=this.unwrapReactive(e);return JSON.parse(JSON.stringify(s))})):[]}unwrapReactive(e){if(e&&"object"==typeof e){if(e.__v_isRef)return e.value;if(e.__v_isReactive)return e;const s={};for(const t in e)e.hasOwnProperty(t)&&(s[t]=this.unwrapReactive(e[t]));return s}return e}setupReactiveMessages(e){this.unwatchMessages&&this.unwatchMessages(),e&&this.isReactive(e)&&this.watchReactiveMessages(e)}isReactive(e){return e&&(e.__v_isReactive||e.__v_isRef||Array.isArray(e)&&e.__v_isReactive)}watchReactiveMessages(e){"vue3"===this.detectVueVersion()?this.setupVue3Watcher(e):"vue2"===this.detectVueVersion()?this.setupVue2Watcher(e):this.setupPollingWatcher(e)}detectVueVersion(){try{if("undefined"!=typeof window){if(window.Vue&&window.Vue.version&&window.Vue.version.startsWith("3"))return"vue3";if(window.Vue&&window.Vue.version&&window.Vue.version.startsWith("2"))return"vue2";if(window.Vue)return"vue2"}if("undefined"!=typeof require)try{const e=require("vue");if(e.version&&e.version.startsWith("3"))return"vue3";if(e.version&&e.version.startsWith("2"))return"vue2"}catch(e){}return"none"}catch(s){return"none"}}setupVue3Watcher(e){try{let t=null;if(window.Vue&&window.Vue.watch)t=window.Vue.watch;else if("undefined"!=typeof require)try{t=require("vue").watch}catch(s){}t?this.unwatchMessages=t(e,(e=>{this.updateMessagesFromReactive(e)}),{deep:!0,immediate:!0}):this.setupPollingWatcher(e)}catch(t){this.setupPollingWatcher(e)}}setupVue2Watcher(e){try{const s=window.Vue;s&&s.observable,this.setupPollingWatcher(e)}catch(s){this.setupPollingWatcher(e)}}setupPollingWatcher(e){let s=JSON.stringify(e);const t=setInterval((()=>{const t=JSON.stringify(e);t!==s&&(s=t,this.updateMessagesFromReactive([...e]))}),500);this.unwatchMessages=()=>clearInterval(t)}updateMessagesFromReactive(e){const s=this.deepCloneMessages(e);s.forEach((e=>{this.normalizeMessage(e)})),this.state.messages=s,this.state.messages.length>0&&(this.messageIdCounter=Math.max(...this.state.messages.map((e=>Number(e.id))))),this.notifyMessagesChange()}normalizeMessage(e){const{fieldMapping:s}=this.options;e.id||(e.id=++this.messageIdCounter),s&&(s.role&&void 0!==e[s.role]&&(e.role=e[s.role]),s.content&&void 0!==e[s.content]&&(e.content=e[s.content]),s.timestamp&&void 0!==e[s.timestamp]&&(e.timestamp=e[s.timestamp]),s.sender&&void 0!==e[s.sender]&&(e.sender=e[s.sender])),!e.sender&&e.role&&(e.sender=e.role),void 0===e.isUser&&("user"===e.role?e.isUser=!0:"assistant"===e.role?e.isUser=!1:e.isUser=e.sender===this.options.currentUser),e.type||(e.type="text"),e.status||(e.status="sent")}getState(){return i({},this.state)}getMessages(){return[...this.state.messages]}getScrollTolerance(){var e;return null!=(e=this.options.scrollTolerance)?e:10}setMessagesChangeCallback(e){this.onMessagesChange=e}setScrollToBottomCallback(e){this.onScrollToBottom=e}notifyMessagesChange(){this.onMessagesChange&&this.onMessagesChange([...this.state.messages])}generateChatHistory(){return this.state.messages.map((e=>{const s={message:(null==e?void 0:e.content)||e.content,isUser:e.isUser,timestamp:e.timestamp,role:e.role};return Object.keys(e).forEach((t=>{["id","isUser","content","timestamp","role"].includes(t)||(s[t]=e[t])})),t=s,JSON.parse(JSON.stringify(t));var t})).filter((e=>!!e.message))}addMessage(e){const s=this.deepCloneMessages([e])[0];this.normalizeMessage(s),this.state.messages.push(s),this.notifyMessagesChange()}sendMessage(e){const s={id:++this.messageIdCounter,sender:this.options.currentUser||"user",role:"user",content:e,isUser:!0,timestamp:Date.now(),type:"text",status:"sending"};this.addMessage(s);const t=this.generateChatHistory();this.options.onSendMessage&&this.options.onSendMessage(e,t),setTimeout((()=>{this.updateMessageStatus(this.messageIdCounter,"sent")}),500)}updateMessageStatus(e,s){const t=this.state.messages.find((s=>s.id===e));t&&(t.status=s,this.notifyMessagesChange(),this.options.onMessageStatusChange&&this.options.onMessageStatusChange(e,s))}clearMessages(){this.state.messages=[],this.messageIdCounter=0,this.notifyMessagesChange()}deleteMessage(e){const s=this.state.messages.findIndex((s=>s.id===e));return-1!==s&&(this.state.messages.splice(s,1),this.notifyMessagesChange(),!0)}scrollToBottom(){this.onScrollToBottom&&this.onScrollToBottom()}addMessages(e){this.deepCloneMessages(e).forEach((e=>{this.normalizeMessage(e),this.state.messages.push(e)})),this.notifyMessagesChange()}findMessages(e){return this.state.messages.filter(e)}updateMessageField(e,s,t){const o=this.state.messages.find((s=>s.id===e));return!!o&&(o[s]=t,this.notifyMessagesChange(),!0)}updateReactiveMessagesSource(e){this.updateMessagesFromReactive(e)}debugReactiveStatus(){this.options.messages}forceRefreshMessages(){this.options.messages&&this.updateMessagesFromReactive([...this.options.messages])}destroy(){this.unwatchMessages&&(this.unwatchMessages(),this.unwatchMessages=void 0)}},exports.analyzeBrackets=function(e){const s={openCurly:0,closeCurly:0,openSquare:0,closeSquare:0};for(const t of e)switch(t){case"{":s.openCurly++;break;case"}":s.closeCurly++;break;case"[":s.openSquare++;break;case"]":s.closeSquare++}return l(i({},s),{curlyBalance:s.openCurly-s.closeCurly,squareBalance:s.openSquare-s.closeSquare,isBalanced:s.openCurly===s.closeCurly&&s.openSquare===s.closeSquare})},exports.createTypewriter=g,exports.default=f,exports.install=v,exports.repairJson=function(e,s){const{allowSingleQuote:t=!1,allowTrailingComma:o=!1,autoCompleteBrackets:a=!0,removeExtraBrackets:n=!0}=s||{};try{return JSON.parse(e)}catch(r){let s=e.trim();t||(s=s.replace(/'([^']+)'/g,'"$1"')),s=s.replace(/([{,]\s*)([a-zA-Z_$][\w$]*)(\s*:)/g,'$1"$2"$3'),s=s.replace(/\/\*.*?\*\/|\/\/.*/g,""),o||(s=s.replace(/,\s*([}\]])/g,"$1")),(a||n)&&(s=m(s,{autoComplete:a,removeExtra:n}));try{return JSON.parse(s)}catch(i){const e=s.match(/\{[\s\S]*?\}|\[[\s\S]*?\]/);if(e)try{return JSON.parse(e[0])}catch(l){return JSON.parse(m(e[0],{autoComplete:!0,removeExtra:!0}))}throw new Error(`无法修复JSON: ${i.message}`)}}},exports.typewriterEffect=function(e,s,t={}){return new Promise((o=>{const{displayText:a,controller:n}=g(e,l(i({},t),{onComplete:()=>{t.onComplete&&t.onComplete(),o()}}));if(s){const e=setInterval((()=>{s.value=a.value,n.isRunning()||clearInterval(e)}),10)}n.start()}))},exports.useTypewriter=function(e,s={}){return g(e,s)};
