@klever-one/web-sdk
Version:
Web SDK for integrating real-time room management and streaming functionality into web applications
2 lines (1 loc) • 15.8 kB
JavaScript
"use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require('../react-lib.css');const c=require("react"),L=require("../index-Civ8iu_p.cjs");function ie(e){if(e&&typeof e=="object"&&"default"in e)return e;const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:()=>e[r]})}}return n.default=e,Object.freeze(n)}const m=ie(c);let H=0;function K(e){const{apiKey:n,container:r,callbacks:i,conversation:a,...l}=e,o=c.useRef(i);o.current=i;const t=c.useRef(null),[g,f]=c.useState({connection:"disconnected",recording:"idle",isStreaming:!1,isStreamingReady:!1,isConversationReady:!1,lastUpdated:new Date}),[h,x]=c.useState({reconnectAttempts:0,messagesSent:0,messagesReceived:0,recordingSessions:0,errorCount:0}),[b,C]=c.useState({messages:[],isStreaming:!1,isCompleted:!1}),[E,S]=c.useState([]);c.useEffect(()=>{try{const u=new L.KleverOneClient({apiKey:n,container:r,conversation:a,...l,callbacks:{...o.current,onConnectionStatusChange:d=>{f(p=>({...p,connection:d})),o.current?.onConnectionStatusChange?.(d)},onRecordingStatusChange:d=>{f(p=>({...p,recording:d})),o.current?.onRecordingStatusChange?.(d)},onStreamingStatusChange:d=>{f(p=>({...p,isStreaming:d})),o.current?.onStreamingStatusChange?.(d)},onMessageReceived:d=>{S(p=>{const P=p.findIndex(I=>I.id===d.id);if(P>=0){const I=[...p];return I[P]=d,I}else return[...p,d]}),o.current?.onMessageReceived?.(d)},onReady:()=>{f(d=>({...d,isStreamingReady:!0,isConversationReady:!0})),o.current?.onReady?.()},onDisconnect:()=>{f({connection:"disconnected",recording:"idle",isStreaming:!1,isStreamingReady:!1,isConversationReady:!1,lastUpdated:new Date}),S([]),o.current?.onDisconnect?.()},onError:d=>{x(p=>({...p,errorCount:p.errorCount+1,lastErrorTime:new Date})),o.current?.onError?.(d)},onRoomInfoUpdated:d=>{o.current?.onRoomInfoUpdated?.(d)},onLog:d=>{o.current?.onLog?.(d)}}});t.current=u,H++,f(u.getState()),x(u.getMetrics()),C(u.getConversationState()),S(u.getMessages())}catch{}return()=>{H--,H===0&&t.current&&t.current.getState().connection!=="disconnected"&&t.current.disconnect()}},[n,r]),c.useEffect(()=>{if(!t.current)return;const d=setInterval(()=>{t.current&&t.current.getState().connection!=="disconnected"&&(f(t.current.getState()),x(t.current.getMetrics()),C(t.current.getConversationState()),S(t.current.getMessages()))},1e3);return()=>clearInterval(d)},[]);const y=c.useCallback(async()=>{if(t.current)return t.current.connect();throw new Error("KleverOneClient not initialized")},[]),N=c.useCallback(()=>{t.current&&t.current.disconnect()},[]),w=c.useCallback(async()=>{if(t.current)return t.current.reconnect();throw new Error("KleverOneClient not initialized")},[]),v=c.useCallback(async u=>{if(t.current)return t.current.sendText(u);throw new Error("KleverOneClient not initialized")},[]),M=c.useCallback(async()=>{if(t.current)return t.current.startRecording();throw new Error("KleverOneClient not initialized")},[]),T=c.useCallback(async()=>{if(t.current)return t.current.stopRecording();throw new Error("KleverOneClient not initialized")},[]),j=c.useCallback(()=>t.current?t.current.isReady():!1,[]),O=c.useCallback(()=>t.current?t.current.isRecording():!1,[]),Z=c.useCallback((u,d)=>{t.current&&t.current.resize(u,d)},[]),Q=c.useCallback(u=>{t.current&&t.current.sendAvatarNum(u)},[]),ee=c.useCallback(u=>{t.current&&t.current.sendAvatarAppearanceChange(u)},[]),te=c.useCallback(u=>{t.current&&t.current.sendPlaceBackgroundChange(u)},[]),ne=c.useCallback(u=>{t.current&&t.current.sendVoiceSetting(u)},[]),re=c.useCallback(u=>{t.current&&t.current.sendMessage(u)},[]),oe=c.useCallback(async u=>{if(t.current)return t.current.sendDataInChunks(u);throw new Error("KleverOneClient not initialized")},[]),se=c.useCallback((u=>{t.current&&(Array.isArray(u),t.current.speak(u))}),[]);return{client:t.current,state:g,metrics:h,conversationState:b,messages:E,connect:y,disconnect:N,reconnect:w,sendText:v,speak:se,startRecording:M,stopRecording:T,isReady:j,isRecording:O,resize:Z,sendAvatarNum:Q,sendAvatarAppearanceChange:ee,sendPlaceBackgroundChange:te,sendVoiceSetting:ne,sendMessage:re,sendDataInChunks:oe}}var A={exports:{}},z={};var W;function ae(){if(W)return z;W=1;var e=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function r(i,a,l){var o=null;if(l!==void 0&&(o=""+l),a.key!==void 0&&(o=""+a.key),"key"in a){l={};for(var t in a)t!=="key"&&(l[t]=a[t])}else l=a;return a=l.ref,{$$typeof:e,type:i,key:o,ref:a!==void 0?a:null,props:l}}return z.Fragment=n,z.jsx=r,z.jsxs=r,z}var $;function ce(){return $||($=1,A.exports=ae()),A.exports}var s=ce();const R=({size:e=24,color:n="currentColor",stroke:r=2,className:i="",style:a,children:l,name:o})=>s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:r,strokeLinecap:"round",strokeLinejoin:"round",className:i,style:a,role:"img","aria-label":o,children:l}),le=e=>s.jsxs(R,{name:"Send",...e,children:[s.jsx("path",{d:"M10 14l11 -11"}),s.jsx("path",{d:"M21 3l-6.5 18a.55 .55 0 0 1 -1 0l-3.5 -7l-7 -3.5a.55 .55 0 0 1 0 -1l18 -6.5"})]}),ue=e=>s.jsxs(R,{name:"Microphone",...e,children:[s.jsx("path",{d:"M9 2m0 3a3 3 0 0 1 3 -3h0a3 3 0 0 1 3 3v5a3 3 0 0 1 -3 3h0a3 3 0 0 1 -3 -3z"}),s.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),s.jsx("path",{d:"M8 21l8 0"}),s.jsx("path",{d:"M12 17l0 4"})]}),de=e=>s.jsx(R,{name:"PlayerStop",...e,children:s.jsx("path",{d:"M5 5m0 2a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2z"})}),fe=e=>s.jsxs(R,{name:"PhoneCall",...e,children:[s.jsx("path",{d:"M5 4h4l2 5l-2.5 1.5a11 11 0 0 0 5 5l1.5 -2.5l5 2v4a2 2 0 0 1 -2 2a16 16 0 0 1 -15 -15a2 2 0 0 1 2 -2"}),s.jsx("path",{d:"M15 7a2 2 0 0 1 2 2"}),s.jsx("path",{d:"M15 3a6 6 0 0 1 6 6"})]}),ge=e=>s.jsxs(R,{name:"PhoneOff",...e,children:[s.jsx("path",{d:"M3 21l18 -18"}),s.jsx("path",{d:"M5.831 14.161a15.946 15.946 0 0 1 -2.831 -8.161a2 2 0 0 1 2 -2h4l2 5l-2.5 1.5c.108 .22 .223 .435 .345 .645m1.751 2.277c.843 .84 1.822 1.544 2.904 2.078l1.5 -2.5l5 2v4a2 2 0 0 1 -2 2a15.963 15.963 0 0 1 -10.344 -4.657"})]}),he=e=>s.jsxs(R,{name:"Wifi",...e,children:[s.jsx("path",{d:"M12 18l.01 0"}),s.jsx("path",{d:"M9.172 15.172a4 4 0 0 1 5.656 0"}),s.jsx("path",{d:"M6.343 12.343a8 8 0 0 1 11.314 0"}),s.jsx("path",{d:"M3.515 9.515c4.686 -4.687 12.284 -4.687 17 0"})]}),ke=e=>s.jsxs(R,{name:"WifiOff",...e,children:[s.jsx("path",{d:"M12 18l.01 0"}),s.jsx("path",{d:"M9.172 15.172a4 4 0 0 1 5.656 0"}),s.jsx("path",{d:"M6.343 12.343a7.963 7.963 0 0 1 3.864 -2.14m4.163 .155a7.965 7.965 0 0 1 3.287 2"}),s.jsx("path",{d:"M3.515 9.515a12 12 0 0 1 3.544 -2.455m3.101 -.92a12 12 0 0 1 10.325 3.374"}),s.jsx("path",{d:"M3 3l18 18"})]}),J=({state:e})=>{const n=e.connection==="connected",r=e.connection==="connecting",i=n?"kos:text-green-400":r?"kos:text-yellow-400":"kos:text-red-400",a=n?"연결됨":r?"연결 중...":"연결 안됨",l=n||r?he:ke;return s.jsxs("div",{className:`kos:flex kos:items-center kos:gap-2 kos:px-3 kos:py-1 kos:bg-black kos:bg-opacity-50 kos:rounded-full kos:text-white kos:text-xs ${i}`,children:[s.jsx(l,{className:`kos:w-4 kos:h-4 ${r?"kos:animate-pulse":""}`}),s.jsx("span",{children:a}),e.isStreaming&&s.jsx("span",{className:"kos:text-sm kos:text-blue-400",children:"응답 생성 중..."})]})},Y=({state:e,connect:n,disconnect:r})=>{const i=e.connection==="connected",a=e.connection==="connecting",l=()=>{i||a?r():n()};return s.jsx("button",{onClick:l,disabled:a,className:`kos:p-3 kos:rounded-full kos:transition-colors ${i?"kos:bg-red-500 kos:hover:bg-red-600 kos:text-white kos:cursor-pointer":a?"kos:bg-yellow-500 kos:text-white kos:animate-pulse kos:cursor-not-allowed":"kos:bg-green-500 kos:hover:bg-green-600 kos:text-white kos:cursor-pointer"}`,children:i||a?s.jsx(ge,{size:20}):s.jsx(fe,{size:20})})};var pe=c.useLayoutEffect,xe=function(n){var r=m.default.useRef(n);return pe(function(){r.current=n}),r},_=function(n,r){if(typeof n=="function"){n(r);return}n.current=r},ve=function(n,r){var i=m.default.useRef();return m.default.useCallback(function(a){n.current=a,i.current&&_(i.current,null),i.current=r,r&&_(r,a)},[r])},B={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},me=function(n){Object.keys(B).forEach(function(r){n.style.setProperty(r,B[r],"important")})},D=me,k=null,U=function(n,r){var i=n.scrollHeight;return r.sizingStyle.boxSizing==="border-box"?i+r.borderSize:i-r.paddingSize};function be(e,n,r,i){r===void 0&&(r=1),i===void 0&&(i=1/0),k||(k=document.createElement("textarea"),k.setAttribute("tabindex","-1"),k.setAttribute("aria-hidden","true"),D(k)),k.parentNode===null&&document.body.appendChild(k);var a=e.paddingSize,l=e.borderSize,o=e.sizingStyle,t=o.boxSizing;Object.keys(o).forEach(function(b){var C=b;k.style[C]=o[C]}),D(k),k.value=n;var g=U(k,e);k.value=n,g=U(k,e),k.value="x";var f=k.scrollHeight-a,h=f*r;t==="border-box"&&(h=h+a+l),g=Math.max(h,g);var x=f*i;return t==="border-box"&&(x=x+a+l),g=Math.min(x,g),[g,f]}var q=function(){},Se=function(n,r){return n.reduce(function(i,a){return i[a]=r[a],i},{})},Ce=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],ye=!!document.documentElement.currentStyle,Re=function(n){var r=window.getComputedStyle(n);if(r===null)return null;var i=Se(Ce,r),a=i.boxSizing;if(a==="")return null;ye&&a==="border-box"&&(i.width=parseFloat(i.width)+parseFloat(i.borderRightWidth)+parseFloat(i.borderLeftWidth)+parseFloat(i.paddingRight)+parseFloat(i.paddingLeft)+"px");var l=parseFloat(i.paddingBottom)+parseFloat(i.paddingTop),o=parseFloat(i.borderBottomWidth)+parseFloat(i.borderTopWidth);return{sizingStyle:i,paddingSize:l,borderSize:o}},je=Re;function F(e,n,r){var i=xe(r);m.useLayoutEffect(function(){var a=function(o){return i.current(o)};if(e)return e.addEventListener(n,a),function(){return e.removeEventListener(n,a)}},[])}var we=function(n,r){F(document.body,"reset",function(i){n.current.form===i.target&&r(i)})},Me=function(n){F(window,"resize",n)},ze=function(n){F(document.fonts,"loadingdone",n)},Ee=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],Te=function(n,r){var i=n.cacheMeasurements,a=n.maxRows,l=n.minRows,o=n.onChange,t=o===void 0?q:o,g=n.onHeightChange,f=g===void 0?q:g,h=L._objectWithoutPropertiesLoose(n,Ee),x=h.value!==void 0,b=m.useRef(null),C=ve(b,r),E=m.useRef(0),S=m.useRef(),y=function(){var v=b.current,M=i&&S.current?S.current:je(v);if(M){S.current=M;var T=be(M,v.value||v.placeholder||"x",l,a),j=T[0],O=T[1];E.current!==j&&(E.current=j,v.style.setProperty("height",j+"px","important"),f(j,{rowHeight:O}))}},N=function(v){x||y(),t(v)};return m.useLayoutEffect(y),we(b,function(){if(!x){var w=b.current.value;requestAnimationFrame(function(){var v=b.current;v&&w!==v.value&&y()})}}),Me(y),ze(y),m.createElement("textarea",L._extends({},h,{onChange:N,ref:C}))},Ie=m.forwardRef(Te);const G=({state:e,isReady:n,sendText:r,startRecording:i,stopRecording:a})=>{const l=c.useRef(null),[o,t]=c.useState(""),g=async h=>{if(h.preventDefault(),!(!o.trim()||e.isStreaming))try{await r(o),t("")}catch{}},f=async()=>{try{e.recording==="recording"?await a():await i()}catch{}};return s.jsxs("form",{onSubmit:g,className:"kos:flex-1 kos:flex kos:items-center kos:gap-4",children:[s.jsx(Ie,{ref:l,className:"kos:flex-1 kos:bg-gray-700 kos:text-white kos:p-3 kos:rounded-lg kos:resize-none kos:outline-none focus:kos:ring-2 focus:kos:ring-blue-500 kos:transition-all",placeholder:"메시지를 입력하세요...",value:o,onChange:h=>t(h.target.value),disabled:e.isStreaming,maxRows:5,minRows:1,onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),g(h))}}),s.jsxs("div",{className:"kos:flex kos:items-center kos:gap-2",children:[s.jsx("button",{type:"button",onClick:f,disabled:e.isStreaming||!n(),className:`kos:p-3 kos:rounded-full kos:transition-colors ${e.recording==="recording"?"kos:bg-red-500 kos:text-white kos:animate-pulse kos:cursor-pointer":"kos:bg-gray-700 kos:hover:bg-gray-600 kos:text-white kos:cursor-pointer"} kos:disabled:opacity-50 kos:disabled:cursor-not-allowed! kos:disabled:hover:bg-gray-700`,children:e.recording==="recording"?s.jsx(de,{size:20}):s.jsx(ue,{size:20})}),s.jsx("button",{type:"submit",disabled:!o.trim()||e.isStreaming||!n(),className:"kos:p-3 kos:bg-blue-500 kos:text-white kos:rounded-full kos:cursor-pointer kos:hover:bg-blue-600 kos:disabled:opacity-50 kos:disabled:cursor-not-allowed! kos:disabled:hover:bg-blue-500 kos:transition-colors",children:s.jsx(le,{size:20})})]})]})},V=({messages:e})=>{const n=c.useRef(null),[r,i]=c.useState(!1),a=c.useMemo(()=>{const o=new Map;return e.forEach(t=>{t.id?o.set(t.id,t):o.set(Symbol("unique-msg"),t)}),Array.from(o.values())},[e]);c.useEffect(()=>{n.current&&!r&&(n.current.scrollTop=n.current.scrollHeight)},[a,r]);const l=()=>{if(n.current){const{scrollTop:o,scrollHeight:t,clientHeight:g}=n.current,f=t-o-g<10;i(!f)}};return s.jsx("div",{ref:n,onScroll:l,className:"kos:flex-1 kos:overflow-y-auto kos:space-y-4 kos:pr-2 kos:scroll-smooth",children:a.map((o,t)=>s.jsx("div",{className:`kos:flex kos:items-end kos:gap-2 ${o.role==="user"?"kos:justify-end":"kos:justify-start"}`,children:s.jsx("div",{className:`kos:px-4 kos:py-2 kos:rounded-2xl kos:max-w-md ${o.role==="user"?"kos:bg-blue-600 kos:text-white kos:rounded-br-none":"kos:bg-gray-700 kos:text-white kos:rounded-bl-none"}`,children:s.jsx("span",{className:"kos:text-sm",children:o.fullContent||o.content})})},o.id||`msg-${t}`))})},X=({apiKey:e,width:n=800,className:r=""})=>{const i=c.useRef(null),a=c.useMemo(()=>document.createElement("div"),[]),l=c.useMemo(()=>({onReady:()=>console.log("디지털 휴먼 준비 완료!"),onMessageReceived:f=>console.log("받은 메시지:",f),onError:f=>console.error("오류:",f)}),[]),o=K({apiKey:e,container:i.current||a,callbacks:l});c.useEffect(()=>()=>{o.client&&o.disconnect()},[o.client]);const t=async()=>{if(i.current&&o.client)try{await o.connect()}catch{}},g=()=>{o.client&&o.disconnect()};return s.jsxs("div",{className:`kos:relative kos:w-full kos:flex kos:gap-4 ${r}`,children:[s.jsxs("div",{className:"kos:relative kos:flex-1",children:[s.jsx("div",{ref:i,className:"kos:w-full kos:h-96 kos:bg-black kos:rounded-lg",style:{width:`${n}px`,height:"400px"}}),s.jsxs("div",{className:"kos:absolute kos:top-0 kos:left-0 kos:w-full kos:h-full kos:p-4 kos:flex kos:flex-col kos:justify-between kos:z-10 pointer-events-none",children:[s.jsxs("div",{className:"kos:flex kos:justify-between kos:items-start",children:[s.jsx(J,{state:o.state}),s.jsx(Y,{state:o.state,connect:t,disconnect:g})]}),s.jsx("div",{className:"pointer-events-auto",children:s.jsx(G,{state:o.state,isReady:o.isReady,sendText:o.sendText,startRecording:o.startRecording,stopRecording:o.stopRecording})})]})]}),s.jsx("div",{className:"kos:w-80 kos:h-96 kos:bg-gray-100 kos:rounded-lg kos:p-4 kos:flex kos:flex-col",children:s.jsx(V,{messages:o.messages})})]})},Le=({apiKey:e})=>{const[n,r]=c.useState(!1);return s.jsx("div",{className:"kos:p-4",children:s.jsx(X,{apiKey:e,width:800,isFullscreen:n,onToggleFullscreen:()=>r(!n),className:"kos:max-w-4xl kos:mx-auto"})})};exports.KleverOneClient=L.KleverOneClient;exports.ConnectionStatusIndicator=J;exports.ConnectionToggleButton=Y;exports.MessageInput=G;exports.MessageList=V;exports.UnifiedConversation=X;exports.UnifiedConversationExample=Le;exports.useKleverOneClient=K;