translation-chat-sdk 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,10 @@
1
+ import React from 'react';
2
+ import { ChatWidgetHandle } from '../types';
1
3
  import '../styles/chat.css';
2
4
  type Props = {
3
5
  title?: string;
4
6
  placeholder?: string;
5
7
  height?: string;
6
8
  };
7
- export declare function ChatWidget({ title, placeholder, height }: Props): import("react/jsx-runtime").JSX.Element;
9
+ export declare const ChatWidget: React.ForwardRefExoticComponent<Props & React.RefAttributes<ChatWidgetHandle>>;
8
10
  export {};
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type { ChatSDKConfig, ChatMessage, PatchOfferEventDetail, PageTranslationResponseEventDetail, BulkTranslationResponseEventDetail, ConnectionState, InstructionContext, HighlightedRegion, ChatContextValue, ChatState, ChatActions, ContextProvider, TokenProvider, PatchData, HistoryMessage, } from './types';
1
+ export type { ChatSDKConfig, ChatMessage, PatchOfferEventDetail, PageTranslationResponseEventDetail, BulkTranslationResponseEventDetail, ConnectionState, InstructionContext, HighlightedRegion, ChatContextValue, ChatState, ChatActions, ContextProvider, TokenProvider, PatchData, HistoryMessage, SelectedContext, ChatWidgetHandle, } from './types';
2
2
  export { ChatProvider } from './provider/ChatProvider';
3
3
  export { useChat } from './hooks/useChat';
4
4
  export { ChatWidget } from './components/ChatWidget';
package/dist/style.css CHANGED
@@ -1 +1 @@
1
- .chat-sdk{--radius-full: 999px;--radius-large: 20px;--radius-medium: 12px;--spacing-1: 8px;--spacing-2: 16px;--space-20: 20px;--space-12: 12px;--background-primary: #ffffff;--background-secondary: #f5f5f5;--background-tertiary: #f0f0f0;--surface-secondary: #ffffff;--content-primary: #141414;--content-secondary: #666666;--content-tertiary: #999999;--border-secondary: #e6e6e6;--background-brand1-primary: #e8effc;--content-brand1-secondary: #212191;--background-black: #141414;display:flex;flex-direction:column;background:var(--background-primary);border:1px solid var(--border-secondary);border-radius:var(--radius-large);box-shadow:0 8px 30px #0000000f;font-family:Matter,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;overflow:hidden}.chat-sdk__header{padding:var(--spacing-2) var(--spacing-1);display:flex;align-items:center;justify-content:space-between;background:var(--surface-secondary)}.chat-sdk__title{font-weight:570;font-size:18px;color:var(--content-primary)}.chat-sdk__status{display:flex;align-items:center;gap:6px;color:var(--content-tertiary);font-size:12px}.chat-sdk__status-dot{width:8px;height:8px;border-radius:50%;background:#ef4444}.chat-sdk__status-dot.connected{background:#10b981}.chat-sdk__messages{flex:1;padding:var(--space-20);display:flex;flex-direction:column;gap:20px;overflow-y:auto;min-height:160px}.chat-sdk__empty{text-align:center;color:var(--content-secondary);font-size:15px;padding:16px}.chat-sdk__user-container{display:flex;flex-direction:column;align-items:flex-end;gap:12px}.chat-sdk__user-context{display:flex;justify-content:flex-end}.chat-sdk__context-chip{display:flex;align-items:center;gap:8px;background:var(--background-tertiary);padding:8px 12px;border-radius:var(--radius-full);height:36px;min-height:36px}.chat-sdk__context-chip--display{background:var(--background-secondary)}.chat-sdk__context-text{font-size:15px;line-height:1.45;color:var(--content-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.chat-sdk__context-remove{display:flex;align-items:center;justify-content:center;width:16px;height:16px;padding:0;border:none;background:transparent;color:var(--content-secondary);cursor:pointer;flex-shrink:0}.chat-sdk__context-remove:hover{color:var(--content-primary)}.chat-sdk__bubble.user{background:var(--background-brand1-primary);padding:var(--space-20);border-radius:var(--space-12);max-width:320px;border:none}.chat-sdk__bubble.user .chat-sdk__bubble-body{color:var(--content-brand1-secondary);font-size:15px;line-height:1.45;white-space:pre-wrap}.chat-sdk__ai-container{display:flex;flex-direction:column;align-items:flex-start}.chat-sdk__ai-response{display:flex;flex-direction:column;gap:8px;width:100%}.chat-sdk__ai-title{font-size:16px;font-weight:500;line-height:1.5;color:var(--content-primary)}.chat-sdk__ai-body{font-size:16px;font-weight:400;line-height:1.5;color:var(--content-secondary);white-space:pre-wrap}.chat-sdk__patch,.chat-sdk__patch-content{display:flex;flex-direction:column;gap:8px}.chat-sdk__patch-label{font-size:12px;color:var(--content-tertiary);font-weight:600}.chat-sdk__patch-block{background:#f3f4f6;border-radius:10px;padding:10px;border:1px solid #e5e7eb;font-size:15px;line-height:1.45;color:var(--content-secondary)}.chat-sdk__composer{padding:var(--spacing-1);background:var(--background-primary)}.chat-sdk__input-bar{display:flex;flex-direction:column;gap:var(--spacing-1);background:var(--surface-secondary);border:1px solid var(--border-secondary);border-radius:var(--radius-large);padding:var(--spacing-1);overflow:hidden}.chat-sdk__input-context{padding:4px 8px 0}.chat-sdk__form{display:flex;flex-direction:column;gap:var(--spacing-1);width:100%}.chat-sdk__input-wrapper{padding:4px 12px;max-height:240px;overflow-y:auto}.chat-sdk__input{width:100%;border:none;background:transparent;resize:none;min-height:24px;font-size:15px;font-family:inherit;color:var(--content-primary);outline:none;line-height:1.45}.chat-sdk__input::placeholder{color:var(--content-tertiary)}.chat-sdk__actions{display:flex;align-items:center;justify-content:space-between}.chat-sdk__add-btn{display:flex;align-items:center;justify-content:center;width:36px;height:36px;min-width:36px;min-height:36px;border:none;background:transparent;border-radius:var(--radius-full);color:var(--content-secondary);cursor:pointer}.chat-sdk__add-btn:hover{background:var(--background-tertiary);color:var(--content-primary)}.chat-sdk__send{display:flex;align-items:center;justify-content:center;width:36px;height:36px;min-width:36px;min-height:36px;background:var(--background-black);color:#fff;border:none;border-radius:var(--radius-full);cursor:pointer}.chat-sdk__send:disabled{opacity:.4;cursor:not-allowed}.chat-sdk__send:not(:disabled):hover{background:#2a2a2a}.chat-sdk__error{margin-top:8px;padding:0 8px;font-size:13px;color:#b91c1c}.chat-sdk__stream{display:inline-flex;gap:4px;margin-left:8px}.chat-sdk__stream span{width:6px;height:6px;background:#9ca3af;border-radius:999px;animation:chat-sdk-pulse 1.2s infinite ease-in-out}.chat-sdk__stream span:nth-child(2){animation-delay:.15s}.chat-sdk__stream span:nth-child(3){animation-delay:.3s}@keyframes chat-sdk-pulse{0%,80%,to{transform:scale(.6);opacity:.6}40%{transform:scale(1);opacity:1}}
1
+ .chat-sdk{--radius-full: 999px;--radius-large: 20px;--radius-medium: 12px;--spacing-1: 8px;--spacing-2: 16px;--space-20: 20px;--space-12: 12px;--background-primary: #ffffff;--background-secondary: #f5f5f5;--background-tertiary: #f0f0f0;--surface-secondary: #ffffff;--content-primary: #141414;--content-secondary: #666666;--content-tertiary: #999999;--border-secondary: #e6e6e6;--background-brand1-primary: #e8effc;--content-brand1-secondary: #212191;--background-black: #141414;display:flex;flex-direction:column;background:var(--background-primary);border:1px solid var(--border-secondary);border-radius:var(--radius-large);box-shadow:0 8px 30px #0000000f;font-family:Matter,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;overflow:hidden}.chat-sdk__header{padding:var(--spacing-2) var(--space-20);display:flex;align-items:center;justify-content:space-between;background:var(--surface-secondary);border-bottom:1px solid var(--border-secondary)}.chat-sdk__title{font-weight:570;font-size:18px;color:var(--content-primary)}.chat-sdk__status{display:flex;align-items:center;gap:6px;color:var(--content-tertiary);font-size:12px}.chat-sdk__status-dot{width:8px;height:8px;border-radius:50%;background:#ef4444}.chat-sdk__status-dot.connected{background:#10b981}.chat-sdk__messages{flex:1;padding:var(--space-20);display:flex;flex-direction:column;gap:20px;overflow-y:auto;min-height:160px}.chat-sdk__empty{text-align:center;color:var(--content-secondary);font-size:15px;padding:16px}.chat-sdk__user-container{display:flex;flex-direction:column;align-items:flex-end;gap:12px}.chat-sdk__user-context{display:flex;justify-content:flex-end}.chat-sdk__context-chip{display:flex;align-items:center;gap:8px;background:var(--background-tertiary);padding:8px 12px;border-radius:var(--radius-full);height:36px;min-height:36px}.chat-sdk__context-chip--display{background:var(--background-secondary)}.chat-sdk__context-text{font-size:13px;line-height:1.45;color:var(--content-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.chat-sdk__context-remove{display:flex;align-items:center;justify-content:center;width:16px;height:16px;padding:0;border:none;background:transparent;color:var(--content-secondary);cursor:pointer;flex-shrink:0}.chat-sdk__context-remove:hover{color:var(--content-primary)}.chat-sdk__bubble.user{background:var(--background-brand1-primary);padding:var(--space-20);border-radius:var(--space-12);max-width:320px;border:none}.chat-sdk__bubble.user .chat-sdk__bubble-body{color:var(--content-brand1-secondary);font-size:14px;line-height:1.45;white-space:pre-wrap}.chat-sdk__ai-container{display:flex;flex-direction:column;align-items:flex-start}.chat-sdk__ai-response{display:flex;flex-direction:column;gap:8px;width:100%}.chat-sdk__ai-title{font-size:14px;font-weight:500;line-height:1.5;color:var(--content-primary)}.chat-sdk__ai-body{font-size:14px;font-weight:400;line-height:1.5;color:var(--content-secondary);white-space:pre-wrap}.chat-sdk__patch,.chat-sdk__patch-content{display:flex;flex-direction:column;gap:8px}.chat-sdk__patch-label{font-size:12px;color:var(--content-tertiary);font-weight:600}.chat-sdk__patch-block{background:#f3f4f6;border-radius:10px;padding:10px;border:1px solid #e5e7eb;font-size:14px;line-height:1.45;color:var(--content-secondary)}.chat-sdk__composer{padding:var(--spacing-1);background:var(--background-primary)}.chat-sdk__input-bar{display:flex;flex-direction:column;gap:var(--spacing-1);background:var(--surface-secondary);border:1px solid var(--border-secondary);border-radius:var(--radius-large);padding:var(--spacing-1);overflow:hidden}.chat-sdk__input-context{padding:4px 8px 0}.chat-sdk__form{display:flex;flex-direction:column;gap:var(--spacing-1);width:100%}.chat-sdk__input-wrapper{padding:4px 12px;max-height:240px;overflow-y:auto}.chat-sdk__input{width:100%;border:none;background:transparent;resize:none;min-height:72px;max-height:240px;font-size:15px;font-family:inherit;color:var(--content-primary);outline:none;line-height:1.45}.chat-sdk__input::placeholder{color:var(--content-tertiary)}.chat-sdk__actions{display:flex;align-items:center;justify-content:space-between}.chat-sdk__add-btn{display:flex;align-items:center;justify-content:center;width:36px;height:36px;min-width:36px;min-height:36px;border:none;background:transparent;border-radius:var(--radius-full);color:var(--content-secondary);cursor:pointer}.chat-sdk__add-btn:hover{background:var(--background-tertiary);color:var(--content-primary)}.chat-sdk__send{display:flex;align-items:center;justify-content:center;width:36px;height:36px;min-width:36px;min-height:36px;background:var(--background-black);color:#fff;border:none;border-radius:var(--radius-full);cursor:pointer}.chat-sdk__send:disabled{opacity:.4;cursor:not-allowed}.chat-sdk__send:not(:disabled):hover{background:#2a2a2a}.chat-sdk__error{margin-top:8px;padding:0 8px;font-size:13px;color:#b91c1c}.chat-sdk__stream{display:inline-flex;gap:4px;margin-left:8px}.chat-sdk__stream span{width:6px;height:6px;background:#9ca3af;border-radius:999px;animation:chat-sdk-pulse 1.2s infinite ease-in-out}.chat-sdk__stream span:nth-child(2){animation-delay:.15s}.chat-sdk__stream span:nth-child(3){animation-delay:.3s}@keyframes chat-sdk-pulse{0%,80%,to{transform:scale(.6);opacity:.6}40%{transform:scale(1);opacity:1}}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("react/jsx-runtime"),k=require("react"),T=Object.create(null);T.open="0";T.close="1";T.ping="2";T.pong="3";T.message="4";T.upgrade="5";T.noop="6";const M=Object.create(null);Object.keys(T).forEach(n=>{M[T[n]]=n});const X={type:"error",data:"parser error"},de=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",pe=typeof ArrayBuffer=="function",ge=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,ne=({type:n,data:e},t,s)=>de&&e instanceof Blob?t?s(e):he(e,s):pe&&(e instanceof ArrayBuffer||ge(e))?t?s(e):he(new Blob([e]),s):s(T[n]+(e||"")),he=(n,e)=>{const t=new FileReader;return t.onload=function(){const s=t.result.split(",")[1];e("b"+(s||""))},t.readAsDataURL(n)};function ue(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let Y;function Oe(n,e){if(de&&n.data instanceof Blob)return n.data.arrayBuffer().then(ue).then(e);if(pe&&(n.data instanceof ArrayBuffer||ge(n.data)))return e(ue(n.data));ne(n,!1,t=>{Y||(Y=new TextEncoder),e(Y.encode(t))})}const le="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",D=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<le.length;n++)D[le.charCodeAt(n)]=n;const Be=n=>{let e=n.length*.75,t=n.length,s,i=0,r,o,h,f;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);const u=new ArrayBuffer(e),p=new Uint8Array(u);for(s=0;s<t;s+=4)r=D[n.charCodeAt(s)],o=D[n.charCodeAt(s+1)],h=D[n.charCodeAt(s+2)],f=D[n.charCodeAt(s+3)],p[i++]=r<<2|o>>4,p[i++]=(o&15)<<4|h>>2,p[i++]=(h&3)<<6|f&63;return u},Pe=typeof ArrayBuffer=="function",ie=(n,e)=>{if(typeof n!="string")return{type:"message",data:me(n,e)};const t=n.charAt(0);return t==="b"?{type:"message",data:Le(n.substring(1),e)}:M[t]?n.length>1?{type:M[t],data:n.substring(1)}:{type:M[t]}:X},Le=(n,e)=>{if(Pe){const t=Be(n);return me(t,e)}else return{base64:!0,data:n}},me=(n,e)=>{switch(e){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},_e="",De=(n,e)=>{const t=n.length,s=new Array(t);let i=0;n.forEach((r,o)=>{ne(r,!1,h=>{s[o]=h,++i===t&&e(s.join(_e))})})},Ie=(n,e)=>{const t=n.split(_e),s=[];for(let i=0;i<t.length;i++){const r=ie(t[i],e);if(s.push(r),r.type==="error")break}return s};function qe(){return new TransformStream({transform(n,e){Oe(n,t=>{const s=t.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const r=new DataView(i.buffer);r.setUint8(0,126),r.setUint16(1,s)}else{i=new Uint8Array(9);const r=new DataView(i.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(s))}n.data&&typeof n.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(t)})}})}let z;function I(n){return n.reduce((e,t)=>e+t.length,0)}function q(n,e){if(n[0].length===e)return n.shift();const t=new Uint8Array(e);let s=0;for(let i=0;i<e;i++)t[i]=n[0][s++],s===n[0].length&&(n.shift(),s=0);return n.length&&s<n[0].length&&(n[0]=n[0].slice(s)),t}function Me(n,e){z||(z=new TextDecoder);const t=[];let s=0,i=-1,r=!1;return new TransformStream({transform(o,h){for(t.push(o);;){if(s===0){if(I(t)<1)break;const f=q(t,1);r=(f[0]&128)===128,i=f[0]&127,i<126?s=3:i===126?s=1:s=2}else if(s===1){if(I(t)<2)break;const f=q(t,2);i=new DataView(f.buffer,f.byteOffset,f.length).getUint16(0),s=3}else if(s===2){if(I(t)<8)break;const f=q(t,8),u=new DataView(f.buffer,f.byteOffset,f.length),p=u.getUint32(0);if(p>Math.pow(2,21)-1){h.enqueue(X);break}i=p*Math.pow(2,32)+u.getUint32(4),s=3}else{if(I(t)<i)break;const f=q(t,i);h.enqueue(ie(r?f:z.decode(f),e)),s=0}if(i===0||i>n){h.enqueue(X);break}}}})}const ye=4;function m(n){if(n)return Ue(n)}function Ue(n){for(var e in m.prototype)n[e]=m.prototype[e];return n}m.prototype.on=m.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};m.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};m.prototype.off=m.prototype.removeListener=m.prototype.removeAllListeners=m.prototype.removeEventListener=function(n,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+n];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var s,i=0;i<t.length;i++)if(s=t[i],s===e||s.fn===e){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+n],this};m.prototype.emit=function(n){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+n],s=1;s<arguments.length;s++)e[s-1]=arguments[s];if(t){t=t.slice(0);for(var s=0,i=t.length;s<i;++s)t[s].apply(this,e)}return this};m.prototype.emitReserved=m.prototype.emit;m.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};m.prototype.hasListeners=function(n){return!!this.listeners(n).length};const H=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),v=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),je="arraybuffer";function we(n,...e){return e.reduce((t,s)=>(n.hasOwnProperty(s)&&(t[s]=n[s]),t),{})}const Ve=v.setTimeout,Fe=v.clearTimeout;function K(n,e){e.useNativeTimers?(n.setTimeoutFn=Ve.bind(v),n.clearTimeoutFn=Fe.bind(v)):(n.setTimeoutFn=v.setTimeout.bind(v),n.clearTimeoutFn=v.clearTimeout.bind(v))}const He=1.33;function Ke(n){return typeof n=="string"?$e(n):Math.ceil((n.byteLength||n.size)*He)}function $e(n){let e=0,t=0;for(let s=0,i=n.length;s<i;s++)e=n.charCodeAt(s),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(s++,t+=4);return t}function ke(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function We(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function Ye(n){let e={},t=n.split("&");for(let s=0,i=t.length;s<i;s++){let r=t[s].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e}class ze extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class re extends m{constructor(e){super(),this.writable=!1,K(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,s){return super.emitReserved("error",new ze(e,t,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=ie(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const t=We(e);return t.length?"?"+t:""}}class Je extends re{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||t()})),this.writable||(s++,this.once("drain",function(){--s||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const t=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};Ie(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,De(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=ke()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let be=!1;try{be=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Qe=be;function Xe(){}class Ge extends Je{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let s=location.port;s||(s=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||s!==e.port}}doWrite(e,t){const s=this.request({method:"POST",data:e});s.on("success",t),s.on("error",(i,r)=>{this.onError("xhr post error",i,r)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,s)=>{this.onError("xhr poll error",t,s)}),this.pollXhr=e}}class x extends m{constructor(e,t,s){super(),this.createRequest=e,K(this,s),this._opts=s,this._method=s.method||"GET",this._uri=t,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var e;const t=we(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(t);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&s.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var i;s.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=x.requestsCount++,x.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Xe,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete x.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}x.requestsCount=0;x.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",fe);else if(typeof addEventListener=="function"){const n="onpagehide"in v?"pagehide":"unload";addEventListener(n,fe,!1)}}function fe(){for(let n in x.requests)x.requests.hasOwnProperty(n)&&x.requests[n].abort()}const Ze=function(){const n=ve({xdomain:!1});return n&&n.responseType!==null}();class et extends Ge{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Ze&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new x(ve,this.uri(),e)}}function ve(n){const e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Qe))return new XMLHttpRequest}catch{}if(!e)try{return new v[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Ee=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class tt extends re{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=Ee?{}:we(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,s)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],i=t===e.length-1;ne(s,this.supportsBinary,r=>{try{this.doWrite(s,r)}catch{}i&&H(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=ke()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const J=v.WebSocket||v.MozWebSocket;class st extends tt{createSocket(e,t,s){return Ee?new J(e,t,s):t?new J(e,t):new J(e)}doWrite(e,t){this.ws.send(t)}}class nt extends re{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=Me(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),i=qe();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const r=()=>{s.read().then(({done:h,value:f})=>{h||(this.onPacket(f),r())}).catch(h=>{})};r();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],i=t===e.length-1;this._writer.write(s).then(()=>{i&&H(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const it={websocket:st,webtransport:nt,polling:et},rt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ot=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function G(n){if(n.length>8e3)throw"URI too long";const e=n,t=n.indexOf("["),s=n.indexOf("]");t!=-1&&s!=-1&&(n=n.substring(0,t)+n.substring(t,s).replace(/:/g,";")+n.substring(s,n.length));let i=rt.exec(n||""),r={},o=14;for(;o--;)r[ot[o]]=i[o]||"";return t!=-1&&s!=-1&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=ct(r,r.path),r.queryKey=at(r,r.query),r}function ct(n,e){const t=/\/{2,9}/g,s=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&s.splice(0,1),e.slice(-1)=="/"&&s.splice(s.length-1,1),s}function at(n,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,i,r){i&&(t[i]=r)}),t}const Z=typeof addEventListener=="function"&&typeof removeEventListener=="function",U=[];Z&&addEventListener("offline",()=>{U.forEach(n=>n())},!1);class A extends m{constructor(e,t){if(super(),this.binaryType=je,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const s=G(e);t.hostname=s.host,t.secure=s.protocol==="https"||s.protocol==="wss",t.port=s.port,s.query&&(t.query=s.query)}else t.host&&(t.hostname=G(t.host).host);K(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(s=>{const i=s.prototype.name;this.transports.push(i),this._transportsByName[i]=s}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Ye(this.opts.query)),Z&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},U.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=ye,t.transport=e,this.id&&(t.sid=this.id);const s=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&A.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",A.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s<this.writeBuffer.length;s++){const i=this.writeBuffer[s].data;if(i&&(t+=Ke(i)),s>0&&t>this._maxPayload)return this.writeBuffer.slice(0,s);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,H(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,s){return this._sendPacket("message",e,t,s),this}send(e,t,s){return this._sendPacket("message",e,t,s),this}_sendPacket(e,t,s,i){if(typeof t=="function"&&(i=t,t=void 0),typeof s=="function"&&(i=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const r={type:e,data:t,options:s};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},s=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():e()}):this.upgrading?s():e()),this}_onError(e){if(A.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Z&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=U.indexOf(this._offlineEventListener);s!==-1&&U.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}A.protocol=ye;class ht extends A{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),s=!1;A.priorWebsocketSuccess=!1;const i=()=>{s||(t.send([{type:"ping",data:"probe"}]),t.once("packet",g=>{if(!s)if(g.type==="pong"&&g.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;A.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(p(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const _=new Error("probe error");_.transport=t.name,this.emitReserved("upgradeError",_)}}))};function r(){s||(s=!0,p(),t.close(),t=null)}const o=g=>{const _=new Error("probe error: "+g);_.transport=t.name,r(),this.emitReserved("upgradeError",_)};function h(){o("transport closed")}function f(){o("socket closed")}function u(g){t&&g.name!==t.name&&r()}const p=()=>{t.removeListener("open",i),t.removeListener("error",o),t.removeListener("close",h),this.off("close",f),this.off("upgrading",u)};t.once("open",i),t.once("error",o),t.once("close",h),this.once("close",f),this.once("upgrading",u),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{s||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let s=0;s<e.length;s++)~this.transports.indexOf(e[s])&&t.push(e[s]);return t}}let ut=class extends ht{constructor(e,t={}){const s=typeof e=="object"?e:t;(!s.transports||s.transports&&typeof s.transports[0]=="string")&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(i=>it[i]).filter(i=>!!i)),super(e,s)}};function lt(n,e="",t){let s=n;t=t||typeof location<"u"&&location,n==null&&(n=t.protocol+"//"+t.host),typeof n=="string"&&(n.charAt(0)==="/"&&(n.charAt(1)==="/"?n=t.protocol+n:n=t.host+n),/^(https?|wss?):\/\//.test(n)||(typeof t<"u"?n=t.protocol+"//"+n:n="https://"+n),s=G(n)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const r=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+r+":"+s.port+e,s.href=s.protocol+"://"+r+(t&&t.port===s.port?"":":"+s.port),s}const ft=typeof ArrayBuffer=="function",dt=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,xe=Object.prototype.toString,pt=typeof Blob=="function"||typeof Blob<"u"&&xe.call(Blob)==="[object BlobConstructor]",gt=typeof File=="function"||typeof File<"u"&&xe.call(File)==="[object FileConstructor]";function oe(n){return ft&&(n instanceof ArrayBuffer||dt(n))||pt&&n instanceof Blob||gt&&n instanceof File}function j(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,s=n.length;t<s;t++)if(j(n[t]))return!0;return!1}if(oe(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return j(n.toJSON(),!0);for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&j(n[t]))return!0;return!1}function mt(n){const e=[],t=n.data,s=n;return s.data=ee(t,e),s.attachments=e.length,{packet:s,buffers:e}}function ee(n,e){if(!n)return n;if(oe(n)){const t={_placeholder:!0,num:e.length};return e.push(n),t}else if(Array.isArray(n)){const t=new Array(n.length);for(let s=0;s<n.length;s++)t[s]=ee(n[s],e);return t}else if(typeof n=="object"&&!(n instanceof Date)){const t={};for(const s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=ee(n[s],e));return t}return n}function _t(n,e){return n.data=te(n.data,e),delete n.attachments,n}function te(n,e){if(!n)return n;if(n&&n._placeholder===!0){if(typeof n.num=="number"&&n.num>=0&&n.num<e.length)return e[n.num];throw new Error("illegal attachments")}else if(Array.isArray(n))for(let t=0;t<n.length;t++)n[t]=te(n[t],e);else if(typeof n=="object")for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=te(n[t],e));return n}const Te=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],yt=5;var l;(function(n){n[n.CONNECT=0]="CONNECT",n[n.DISCONNECT=1]="DISCONNECT",n[n.EVENT=2]="EVENT",n[n.ACK=3]="ACK",n[n.CONNECT_ERROR=4]="CONNECT_ERROR",n[n.BINARY_EVENT=5]="BINARY_EVENT",n[n.BINARY_ACK=6]="BINARY_ACK"})(l||(l={}));class wt{constructor(e){this.replacer=e}encode(e){return(e.type===l.EVENT||e.type===l.ACK)&&j(e)?this.encodeAsBinary({type:e.type===l.EVENT?l.BINARY_EVENT:l.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===l.BINARY_EVENT||e.type===l.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=mt(e),s=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(s),i}}class ce extends m{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const s=t.type===l.BINARY_EVENT;s||t.type===l.BINARY_ACK?(t.type=s?l.EVENT:l.ACK,this.reconstructor=new kt(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(oe(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0;const s={type:Number(e.charAt(0))};if(l[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===l.BINARY_EVENT||s.type===l.BINARY_ACK){const r=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const o=e.substring(r,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");s.attachments=Number(o)}if(e.charAt(t+1)==="/"){const r=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););s.nsp=e.substring(r,t)}else s.nsp="/";const i=e.charAt(t+1);if(i!==""&&Number(i)==i){const r=t+1;for(;++t;){const o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}s.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(ce.isPayloadValid(s.type,r))s.data=r;else throw new Error("invalid payload")}return s}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case l.CONNECT:return F(t);case l.DISCONNECT:return t===void 0;case l.CONNECT_ERROR:return typeof t=="string"||F(t);case l.EVENT:case l.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Te.indexOf(t[0])===-1);case l.ACK:case l.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class kt{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const t=_t(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function bt(n){return typeof n=="string"}const vt=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n};function Et(n){return n===void 0||vt(n)}function F(n){return Object.prototype.toString.call(n)==="[object Object]"}function xt(n,e){switch(n){case l.CONNECT:return e===void 0||F(e);case l.DISCONNECT:return e===void 0;case l.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Te.indexOf(e[0])===-1);case l.ACK:return Array.isArray(e);case l.CONNECT_ERROR:return typeof e=="string"||F(e);default:return!1}}function Tt(n){return bt(n.nsp)&&Et(n.id)&&xt(n.type,n.data)}const Ct=Object.freeze(Object.defineProperty({__proto__:null,Decoder:ce,Encoder:wt,get PacketType(){return l},isPacketValid:Tt,protocol:yt},Symbol.toStringTag,{value:"Module"}));function E(n,e,t){return n.on(e,t),function(){n.off(e,t)}}const St=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Ce extends m{constructor(e,t,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[E(e,"open",this.onopen.bind(this)),E(e,"packet",this.onpacket.bind(this)),E(e,"error",this.onerror.bind(this)),E(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var s,i,r;if(St.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const o={type:l.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const p=this.ids++,g=t.pop();this._registerAckCallback(p,g),o.id=p}const h=(i=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||i===void 0?void 0:i.writable,f=this.connected&&!(!((r=this.io.engine)===null||r===void 0)&&r._hasPingExpired());return this.flags.volatile&&!h||(f?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var s;const i=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}const r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let h=0;h<this.sendBuffer.length;h++)this.sendBuffer[h].id===e&&this.sendBuffer.splice(h,1);t.call(this,new Error("operation has timed out"))},i),o=(...h)=>{this.io.clearTimeoutFn(r),t.apply(this,h)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((s,i)=>{const r=(o,h)=>o?i(o):s(h);r.withError=!0,t.push(r),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...r)=>(this._queue[0],i!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(i)):(this._queue.shift(),t&&t(null,...r)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:l.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(s=>String(s.id)===e)){const s=this.acks[e];delete this.acks[e],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case l.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case l.EVENT:case l.BINARY_EVENT:this.onevent(e);break;case l.ACK:case l.BINARY_ACK:this.onack(e);break;case l.DISCONNECT:this.ondisconnect();break;case l.CONNECT_ERROR:this.destroy();const s=new Error(e.data.message);s.data=e.data.data,this.emitReserved("connect_error",s);break}}onevent(e){const t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const s of t)s.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let s=!1;return function(...i){s||(s=!0,t.packet({type:l.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:l.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const s of t)s.apply(this,e.data)}}}function O(n){n=n||{},this.ms=n.min||100,this.max=n.max||1e4,this.factor=n.factor||2,this.jitter=n.jitter>0&&n.jitter<=1?n.jitter:0,this.attempts=0}O.prototype.duration=function(){var n=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*n);n=Math.floor(e*10)&1?n+t:n-t}return Math.min(n,this.max)|0};O.prototype.reset=function(){this.attempts=0};O.prototype.setMin=function(n){this.ms=n};O.prototype.setMax=function(n){this.max=n};O.prototype.setJitter=function(n){this.jitter=n};class se extends m{constructor(e,t){var s;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,K(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((s=t.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new O({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||Ct;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new ut(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const i=E(t,"open",function(){s.onopen(),e&&e()}),r=h=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",h),e?e(h):this.maybeReconnectOnOpen()},o=E(t,"error",r);if(this._timeout!==!1){const h=this._timeout,f=this.setTimeoutFn(()=>{i(),r(new Error("timeout")),t.close()},h);this.opts.autoUnref&&f.unref(),this.subs.push(()=>{this.clearTimeoutFn(f)})}return this.subs.push(i),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(E(e,"ping",this.onping.bind(this)),E(e,"data",this.ondata.bind(this)),E(e,"error",this.onerror.bind(this)),E(e,"close",this.onclose.bind(this)),E(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){H(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let s=this.nsps[e];return s?this._autoConnect&&!s.active&&s.connect():(s=new Ce(this,e,t),this.nsps[e]=s),s}_destroy(e){const t=Object.keys(this.nsps);for(const s of t)if(this.nsps[s].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let s=0;s<t.length;s++)this.engine.write(t[s],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var s;this.cleanup(),(s=this.engine)===null||s===void 0||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):e.onreconnect()}))},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const L={};function V(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};const t=lt(n,e.path||"/socket.io"),s=t.source,i=t.id,r=t.path,o=L[i]&&r in L[i].nsps,h=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let f;return h?f=new se(s,e):(L[i]||(L[i]=new se(s,e)),f=L[i]),t.query&&!e.query&&(e.query=t.queryKey),f.socket(t.path,e)}Object.assign(V,{Manager:se,Socket:Ce,io:V,connect:V});function N(){return`${Date.now().toString(36)}-${Math.random().toString(16).slice(2,8)}`}class Nt{constructor(e){this.socket=null,this.reconnectAttempts=0,this.listeners=new Map,this.lastContext=null,this.config={reconnectAttempts:5,reconnectDelayMs:1500,logger:console,...e}}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{var s;return(s=this.listeners.get(e))==null?void 0:s.delete(t)}}emit(e,t){var s;(s=this.listeners.get(e))==null||s.forEach(i=>{var r,o;try{i(t)}catch(h){(o=(r=this.config.logger)==null?void 0:r.error)==null||o.call(r,`chat-sdk listener error for ${e}`,h)}})}setConnection(e){var t,s;this.emit("connection",e),(s=(t=this.config).onConnectionChange)==null||s.call(t,e)}async getToken(){var t,s;const{tokenProvider:e}=this.config;if(!e)return null;try{return(typeof e=="function"?await e():e)||null}catch(i){return(s=(t=this.config.logger)==null?void 0:t.warn)==null||s.call(t,"chat-sdk token provider failed",i),null}}async connect(){var r;if((r=this.socket)!=null&&r.connected)return;const e=new URL(this.config.websocketUrl),t=e.pathname==="/"?"/socket.io":e.pathname,s=e.origin,i=await this.getToken();return this.socket=V(s,{path:t,transports:["websocket","polling"],autoConnect:!1,reconnection:!1,auth:i?{token:i}:void 0}),this.registerSocketEvents(),this.setConnection({connected:!1,connecting:!0}),new Promise((o,h)=>{const f=setTimeout(()=>{h(new Error("connection timeout"))},1e4);this.socket.once("connect",()=>{clearTimeout(f),this.reconnectAttempts=0,this.setConnection({connected:!0,connecting:!1}),o()}),this.socket.once("connect_error",u=>{clearTimeout(f),this.setConnection({connected:!1,connecting:!1,error:u.message}),this.handleReconnect(),h(u)}),this.socket.connect()})}disconnect(){var e;(e=this.socket)==null||e.disconnect(),this.socket=null,this.setConnection({connected:!1,connecting:!1})}async submitInstruction(e,t){var r,o;if(!((r=this.socket)!=null&&r.connected))throw new Error("Not connected");this.lastContext=t;const s=await this.getToken(),i={trans_doc_id:t.trans_doc_id,page_num:t.page_num,instruction:e,modification_level:"page",access_token:s||void 0,region_coordinates:t.highlighted_region?{start_offset:t.highlighted_region.start_offset,end_offset:t.highlighted_region.end_offset}:void 0,region_text:(o=t.highlighted_region)==null?void 0:o.text,selection_id:t.selection_id};this.socket.emit("INSTR_SUBMIT",i)}async requestChatHistory(e){var s;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();this.lastContext=e,this.socket.emit("CHAT_HISTORY_REQUEST",{trans_doc_id:e.trans_doc_id,access_token:t||void 0})}async sendPatchDecision(e){var s;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();this.socket.emit("PATCH_DECISION",{...e,access_token:t||void 0})}async requestPageTranslation(e){var s;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();this.socket.emit("PAGE_TRANSLATION_REQUEST",{...e,access_token:t||void 0})}async requestBulkTranslation(e){var s;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();this.socket.emit("BULK_TRANSLATION_REQUEST",{...e,access_token:t||void 0})}async cancelBulkTranslation(e){var s;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();this.socket.emit("CANCEL_BULK_TRANSLATION_REQUEST",{trans_doc_id:e,access_token:t||void 0})}registerSocketEvents(){this.socket&&(this.socket.on("disconnect",()=>{this.setConnection({connected:!1,connecting:!1}),this.handleReconnect()}),this.socket.on("connect_error",e=>{this.setConnection({connected:!1,connecting:!1,error:e.message}),this.handleReconnect()}),this.socket.on("CHAT_RESPONSE",e=>{this.emit("chat-response",e)}),this.socket.on("PATCH_OFFER",e=>{this.emit("patch-offer",e)}),this.socket.on("CHAT_HISTORY_RESPONSE",e=>{this.emit("chat-history-response",e)}),this.socket.on("INSTRUCTION_ERROR",e=>{this.emit("instruction-error",e)}),this.socket.on("PAGE_TRANSLATION_RESPONSE",e=>{var t,s;this.emit("page-translation-response",e),(s=(t=this.config).onPageTranslationResponse)==null||s.call(t,e)}),this.socket.on("BULK_TRANSLATION_RESPONSE",e=>{var t,s;this.emit("bulk-translation-response",e),(s=(t=this.config).onBulkTranslationResponse)==null||s.call(t,e)}),this.socket.on("connected",()=>{this.lastContext&&this.requestChatHistory(this.lastContext).catch(e=>{var t,s;return(s=(t=this.config.logger)==null?void 0:t.warn)==null?void 0:s.call(t,"chat-sdk history on reconnect failed",e)})}))}handleReconnect(){var e,t;if(this.reconnectAttempts>=(this.config.reconnectAttempts??5)){(t=(e=this.config.logger)==null?void 0:e.warn)==null||t.call(e,"chat-sdk max reconnection attempts reached");return}this.reconnectAttempts+=1,setTimeout(()=>{this.connect().catch(s=>{var i,r;return(r=(i=this.config.logger)==null?void 0:i.error)==null?void 0:r.call(i,"chat-sdk reconnect failed",s)})},this.config.reconnectDelayMs)}}function At(n){return n.map(e=>{const t={id:N(),instructionId:e.instruction_id,pageNum:e.page_num,timestamp:new Date(e.timestamp)},s={...t,type:"user",content:e.instruction,contextText:e.region_text},i=[];return e.response_content&&e.response_type==="chat"&&i.push({...t,type:"ai-chat",content:e.response_content}),e.response_content&&e.response_type==="patch"&&i.push({...t,type:"ai-patch",content:e.response_content,patchData:{originalText:e.region_text,improvedText:e.response_content,regionText:e.region_text,isComplete:!0}}),[s,...i]}).flat().sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}const Se=k.createContext(null),Rt={connected:!1,connecting:!1};function Ot({config:n,children:e}){const t=k.useRef(null),s=k.useRef(new Map),[i,r]=k.useState({messages:[],connection:Rt,latestPatchOffer:null,isSubmitting:!1}),o=k.useMemo(()=>({reconnectAttempts:5,reconnectDelayMs:1500,...n}),[n]);k.useEffect(()=>{const u=new Nt(o);t.current=u;const p=u.on("connection",c=>{r(d=>({...d,connection:c}))}),g=u.on("chat-response",c=>{r(d=>{const b=[...d.messages];let C=b.find(w=>w.instructionId===c.instruction_id&&w.type==="ai-chat");C||(C={id:N(),type:"ai-chat",content:"",timestamp:new Date,instructionId:c.instruction_id,pageNum:c.page_num,isStreaming:!0},b.push(C));const S={...C,content:(C.content||"")+(c.chunk_text||""),isStreaming:!c.is_final},R=b.map(w=>w.id===C.id?S:w);return{...d,messages:R,isSubmitting:c.is_final?!1:d.isSubmitting}})}),_=u.on("patch-offer",c=>{var C;const d=`${c.trans_doc_id}-${c.instruction_id}`,b=s.current.get(d)??{trans_doc_id:c.trans_doc_id,page_num:c.page_num,instruction_id:c.instruction_id,original_text:c.region_original_text||"",highlighted_region:c.region_coordinates,new_suggestion:"",is_page_level:!c.region_coordinates,selection_id:c.selection_id};if(b.new_suggestion+=c.region_replacement_text_chunk||"",c.selection_id&&!b.selection_id&&(b.selection_id=c.selection_id),s.current.set(d,b),r(S=>{var ae;const R=[...S.messages];let w=R.find(P=>P.instructionId===c.instruction_id&&P.type==="ai-patch");w||(w={id:N(),type:"ai-patch",content:"",timestamp:new Date,instructionId:c.instruction_id,pageNum:c.page_num,isStreaming:!0,patchData:{originalText:c.region_original_text,improvedText:"",regionText:c.region_original_text,isComplete:!1}},R.push(w));const Ae={...w,content:(w.content||"")+(c.region_replacement_text_chunk||""),isStreaming:!c.is_final,patchData:{...w.patchData,improvedText:(((ae=w.patchData)==null?void 0:ae.improvedText)||"")+(c.region_replacement_text_chunk||""),regionText:c.region_original_text,isComplete:c.is_final}},Re=R.map(P=>P.id===w.id?Ae:P);return{...S,messages:Re,isSubmitting:c.is_final?!1:S.isSubmitting}}),c.is_final){const S=s.current.get(d);S&&((C=o.onPatchOffer)==null||C.call(o,S),r(R=>({...R,latestPatchOffer:S}))),s.current.delete(d)}}),y=u.on("chat-history-response",c=>{if(c.status==="success"){const d=At(c.messages);r(b=>({...b,messages:d}))}else r(d=>({...d,messages:[...d.messages,{id:N(),type:"system",content:c.error||"Failed to load chat history",timestamp:new Date}]}))}),B=u.on("instruction-error",c=>{r(d=>({...d,isSubmitting:!1,messages:[...d.messages,{id:N(),type:"error",content:c.error,timestamp:new Date}]}))}),$=u.on("page-translation-response",c=>{var d;(d=o.onPageTranslationResponse)==null||d.call(o,c)}),W=u.on("bulk-translation-response",c=>{var d;(d=o.onBulkTranslationResponse)==null||d.call(o,c)});return u.connect().then(()=>{const c=o.contextProvider();if(c)return u.requestChatHistory(c)}).catch(c=>{var d,b;return(b=(d=o.logger)==null?void 0:d.warn)==null?void 0:b.call(d,"chat-sdk connect failed",c)}),()=>{p(),g(),_(),y(),B(),$(),W(),u.disconnect()}},[o]);const h=k.useMemo(()=>({async submitInstruction(u){const p=t.current;if(!p)throw new Error("SDK not ready");const g=o.contextProvider();if(!g)throw new Error("contextProvider returned null");r(_=>{var y;return{..._,isSubmitting:!0,messages:[..._.messages,{id:N(),type:"user",content:u,timestamp:new Date,contextText:(y=g.highlighted_region)==null?void 0:y.text},{id:N(),type:"loading",content:"Processing your instruction...",timestamp:new Date,isStreaming:!0}]}}),await p.submitInstruction(u,g)},async submitInstructionWithContext(u,p){const g=t.current;if(!g)throw new Error("SDK not ready");r(_=>{var y;return{..._,isSubmitting:!0,messages:[..._.messages,{id:N(),type:"user",content:u,timestamp:new Date,contextText:(y=p.highlighted_region)==null?void 0:y.text},{id:N(),type:"loading",content:"Processing your instruction...",timestamp:new Date,isStreaming:!0}]}}),await g.submitInstruction(u,p)},async requestChatHistory(){const u=t.current;if(!u)throw new Error("SDK not ready");const p=o.contextProvider();if(!p)throw new Error("contextProvider returned null");await u.requestChatHistory(p)},async sendPatchDecision(u,p,g,_){const y=t.current;if(!y)throw new Error("SDK not ready");await y.sendPatchDecision({trans_doc_id:u,page_num:p,instruction_id:g,decision:_}),r(B=>({...B,latestPatchOffer:null}))},async requestPageTranslation(u,p){const g=t.current;if(!g)throw new Error("SDK not ready");return await g.requestPageTranslation({trans_doc_id:u,page_num:p}),!0},async requestBulkTranslation(u,p){const g=t.current;if(!g)throw new Error("SDK not ready");return await g.requestBulkTranslation({trans_doc_id:u,page_list:p}),!0},async cancelBulkTranslation(u){const p=t.current;if(!p)throw new Error("SDK not ready");return await p.cancelBulkTranslation(u),!0},clearMessages(){r(u=>({...u,messages:[]}))}}),[o]),f=k.useMemo(()=>({...i,...h}),[i,h]);return a.jsx(Se.Provider,{value:f,children:e})}function Bt(){const n=k.useContext(Se);if(!n)throw new Error("useChat must be used within ChatProvider");return n}function Ne(){return Bt()}function Pt({title:n="AI Assistance",placeholder:e="Ask anything...",height:t="500px"}){const{messages:s,connection:i,submitInstruction:r,isSubmitting:o}=Ne(),[h,f]=k.useState(""),[u,p]=k.useState(null),g=k.useRef(null),_=!i.connected||o,y=k.useMemo(()=>[...s].sort((c,d)=>c.timestamp.getTime()-d.timestamp.getTime()),[s]);k.useEffect(()=>{g.current&&(g.current.scrollTop=g.current.scrollHeight)},[y]);const B=async c=>{c.preventDefault();const d=h.trim();d&&(await r(d),f(""),p(null))},$=(c,d=40)=>c.length>d?`${c.slice(0,d)}...`:c,W=()=>{p(null)};return a.jsxs("div",{className:"chat-sdk",style:{height:t},children:[a.jsxs("div",{className:"chat-sdk__header",children:[a.jsx("div",{className:"chat-sdk__title",children:n}),a.jsxs("div",{className:"chat-sdk__status",children:[a.jsx("span",{className:`chat-sdk__status-dot ${i.connected?"connected":"disconnected"}`}),i.connected?"Connected":i.connecting?"Connecting...":"Disconnected"]})]}),a.jsx("div",{className:"chat-sdk__messages",ref:g,children:y.length===0?a.jsx("div",{className:"chat-sdk__empty",children:"Welcome! Ask anything about the translation."}):y.map(c=>a.jsx(Lt,{message:c},c.id))}),a.jsxs("div",{className:"chat-sdk__composer",children:[a.jsxs("div",{className:"chat-sdk__input-bar",children:[u&&a.jsx("div",{className:"chat-sdk__input-context",children:a.jsxs("div",{className:"chat-sdk__context-chip",children:[a.jsx("span",{className:"chat-sdk__context-text",children:$(u)}),a.jsx("button",{type:"button",className:"chat-sdk__context-remove",onClick:W,"aria-label":"Remove context",children:a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:a.jsx("path",{d:"M1 1L9 9M9 1L1 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})})]})}),a.jsxs("form",{className:"chat-sdk__form",onSubmit:B,children:[a.jsx("div",{className:"chat-sdk__input-wrapper",children:a.jsx("textarea",{className:"chat-sdk__input",placeholder:e,value:h,onChange:c=>f(c.target.value),disabled:_,rows:1})}),a.jsxs("div",{className:"chat-sdk__actions",children:[a.jsx("button",{type:"button",className:"chat-sdk__add-btn","aria-label":"Add context",children:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:a.jsx("path",{d:"M8 3V13M3 8H13",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})}),a.jsx("button",{className:"chat-sdk__send",type:"submit",disabled:!h.trim()||_,"aria-label":"Send message",children:a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:a.jsx("path",{d:"M7 12V2M7 2L3 6M7 2L11 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})]}),i.error&&a.jsxs("div",{className:"chat-sdk__error",children:["⚠️ ",i.error]})]})]})}function Lt({message:n}){var r;const e=n.type==="user",t=n.type==="loading",s=n.type==="ai-patch",i=(o,h=40)=>o.length>h?`${o.slice(0,h)}...`:o;return e?a.jsxs("div",{className:"chat-sdk__user-container",children:[n.contextText&&a.jsx("div",{className:"chat-sdk__user-context",children:a.jsx("div",{className:"chat-sdk__context-chip chat-sdk__context-chip--display",children:a.jsx("span",{className:"chat-sdk__context-text",children:i(n.contextText)})})}),a.jsx("div",{className:"chat-sdk__bubble user",children:a.jsx("div",{className:"chat-sdk__bubble-body",children:n.content})})]}):a.jsx("div",{className:"chat-sdk__ai-container",children:a.jsx("div",{className:"chat-sdk__ai-response",children:s&&((r=n.patchData)!=null&&r.originalText)?a.jsxs("div",{className:"chat-sdk__patch",children:[a.jsx("div",{className:"chat-sdk__ai-title",children:"I have a suggestion for you."}),a.jsxs("div",{className:"chat-sdk__patch-content",children:[a.jsx("div",{className:"chat-sdk__patch-label",children:"Original"}),a.jsx("div",{className:"chat-sdk__patch-block",children:n.patchData.originalText}),a.jsx("div",{className:"chat-sdk__patch-label",children:"Improved"}),a.jsxs("div",{className:"chat-sdk__patch-block",children:[n.patchData.improvedText,n.isStreaming&&a.jsx(Q,{})]})]})]}):a.jsx(a.Fragment,{children:n.content&&a.jsxs("div",{className:"chat-sdk__ai-body",children:[n.content,t&&a.jsx(Q,{}),n.isStreaming&&!t&&a.jsx(Q,{})]})})})})}function Q(){return a.jsxs("span",{className:"chat-sdk__stream",children:[a.jsx("span",{}),a.jsx("span",{}),a.jsx("span",{})]})}exports.ChatProvider=Ot;exports.ChatWidget=Pt;exports.useChat=Ne;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("react/jsx-runtime"),k=require("react"),C=Object.create(null);C.open="0";C.close="1";C.ping="2";C.pong="3";C.message="4";C.upgrade="5";C.noop="6";const U=Object.create(null);Object.keys(C).forEach(n=>{U[C[n]]=n});const X={type:"error",data:"parser error"},de=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",pe=typeof ArrayBuffer=="function",ge=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,ne=({type:n,data:e},t,s)=>de&&e instanceof Blob?t?s(e):he(e,s):pe&&(e instanceof ArrayBuffer||ge(e))?t?s(e):he(new Blob([e]),s):s(C[n]+(e||"")),he=(n,e)=>{const t=new FileReader;return t.onload=function(){const s=t.result.split(",")[1];e("b"+(s||""))},t.readAsDataURL(n)};function ue(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let Y;function Be(n,e){if(de&&n.data instanceof Blob)return n.data.arrayBuffer().then(ue).then(e);if(pe&&(n.data instanceof ArrayBuffer||ge(n.data)))return e(ue(n.data));ne(n,!1,t=>{Y||(Y=new TextEncoder),e(Y.encode(t))})}const le="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",I=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<le.length;n++)I[le.charCodeAt(n)]=n;const Pe=n=>{let e=n.length*.75,t=n.length,s,i=0,r,o,h,f;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);const u=new ArrayBuffer(e),d=new Uint8Array(u);for(s=0;s<t;s+=4)r=I[n.charCodeAt(s)],o=I[n.charCodeAt(s+1)],h=I[n.charCodeAt(s+2)],f=I[n.charCodeAt(s+3)],d[i++]=r<<2|o>>4,d[i++]=(o&15)<<4|h>>2,d[i++]=(h&3)<<6|f&63;return u},Le=typeof ArrayBuffer=="function",ie=(n,e)=>{if(typeof n!="string")return{type:"message",data:me(n,e)};const t=n.charAt(0);return t==="b"?{type:"message",data:De(n.substring(1),e)}:U[t]?n.length>1?{type:U[t],data:n.substring(1)}:{type:U[t]}:X},De=(n,e)=>{if(Le){const t=Pe(n);return me(t,e)}else return{base64:!0,data:n}},me=(n,e)=>{switch(e){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},_e="",Ie=(n,e)=>{const t=n.length,s=new Array(t);let i=0;n.forEach((r,o)=>{ne(r,!1,h=>{s[o]=h,++i===t&&e(s.join(_e))})})},qe=(n,e)=>{const t=n.split(_e),s=[];for(let i=0;i<t.length;i++){const r=ie(t[i],e);if(s.push(r),r.type==="error")break}return s};function Me(){return new TransformStream({transform(n,e){Be(n,t=>{const s=t.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const r=new DataView(i.buffer);r.setUint8(0,126),r.setUint16(1,s)}else{i=new Uint8Array(9);const r=new DataView(i.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(s))}n.data&&typeof n.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(t)})}})}let z;function q(n){return n.reduce((e,t)=>e+t.length,0)}function M(n,e){if(n[0].length===e)return n.shift();const t=new Uint8Array(e);let s=0;for(let i=0;i<e;i++)t[i]=n[0][s++],s===n[0].length&&(n.shift(),s=0);return n.length&&s<n[0].length&&(n[0]=n[0].slice(s)),t}function Ue(n,e){z||(z=new TextDecoder);const t=[];let s=0,i=-1,r=!1;return new TransformStream({transform(o,h){for(t.push(o);;){if(s===0){if(q(t)<1)break;const f=M(t,1);r=(f[0]&128)===128,i=f[0]&127,i<126?s=3:i===126?s=1:s=2}else if(s===1){if(q(t)<2)break;const f=M(t,2);i=new DataView(f.buffer,f.byteOffset,f.length).getUint16(0),s=3}else if(s===2){if(q(t)<8)break;const f=M(t,8),u=new DataView(f.buffer,f.byteOffset,f.length),d=u.getUint32(0);if(d>Math.pow(2,21)-1){h.enqueue(X);break}i=d*Math.pow(2,32)+u.getUint32(4),s=3}else{if(q(t)<i)break;const f=M(t,i);h.enqueue(ie(r?f:z.decode(f),e)),s=0}if(i===0||i>n){h.enqueue(X);break}}}})}const ye=4;function w(n){if(n)return je(n)}function je(n){for(var e in w.prototype)n[e]=w.prototype[e];return n}w.prototype.on=w.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};w.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};w.prototype.off=w.prototype.removeListener=w.prototype.removeAllListeners=w.prototype.removeEventListener=function(n,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+n];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var s,i=0;i<t.length;i++)if(s=t[i],s===e||s.fn===e){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+n],this};w.prototype.emit=function(n){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+n],s=1;s<arguments.length;s++)e[s-1]=arguments[s];if(t){t=t.slice(0);for(var s=0,i=t.length;s<i;++s)t[s].apply(this,e)}return this};w.prototype.emitReserved=w.prototype.emit;w.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};w.prototype.hasListeners=function(n){return!!this.listeners(n).length};const K=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),E=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Ve="arraybuffer";function we(n,...e){return e.reduce((t,s)=>(n.hasOwnProperty(s)&&(t[s]=n[s]),t),{})}const Fe=E.setTimeout,He=E.clearTimeout;function W(n,e){e.useNativeTimers?(n.setTimeoutFn=Fe.bind(E),n.clearTimeoutFn=He.bind(E)):(n.setTimeoutFn=E.setTimeout.bind(E),n.clearTimeoutFn=E.clearTimeout.bind(E))}const Ke=1.33;function We(n){return typeof n=="string"?$e(n):Math.ceil((n.byteLength||n.size)*Ke)}function $e(n){let e=0,t=0;for(let s=0,i=n.length;s<i;s++)e=n.charCodeAt(s),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(s++,t+=4);return t}function ke(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Ye(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function ze(n){let e={},t=n.split("&");for(let s=0,i=t.length;s<i;s++){let r=t[s].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e}class Je extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class re extends w{constructor(e){super(),this.writable=!1,W(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,s){return super.emitReserved("error",new Je(e,t,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=ie(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const t=Ye(e);return t.length?"?"+t:""}}class Qe extends re{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||t()})),this.writable||(s++,this.once("drain",function(){--s||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const t=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};qe(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,Ie(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=ke()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let be=!1;try{be=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Xe=be;function Ge(){}class Ze extends Qe{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let s=location.port;s||(s=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||s!==e.port}}doWrite(e,t){const s=this.request({method:"POST",data:e});s.on("success",t),s.on("error",(i,r)=>{this.onError("xhr post error",i,r)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,s)=>{this.onError("xhr poll error",t,s)}),this.pollXhr=e}}class T extends w{constructor(e,t,s){super(),this.createRequest=e,W(this,s),this._opts=s,this._method=s.method||"GET",this._uri=t,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var e;const t=we(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(t);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&s.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var i;s.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=T.requestsCount++,T.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Ge,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete T.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}T.requestsCount=0;T.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",fe);else if(typeof addEventListener=="function"){const n="onpagehide"in E?"pagehide":"unload";addEventListener(n,fe,!1)}}function fe(){for(let n in T.requests)T.requests.hasOwnProperty(n)&&T.requests[n].abort()}const et=function(){const n=ve({xdomain:!1});return n&&n.responseType!==null}();class tt extends Ze{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=et&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new T(ve,this.uri(),e)}}function ve(n){const e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Xe))return new XMLHttpRequest}catch{}if(!e)try{return new E[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Ee=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class st extends re{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=Ee?{}:we(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,s)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],i=t===e.length-1;ne(s,this.supportsBinary,r=>{try{this.doWrite(s,r)}catch{}i&&K(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=ke()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const J=E.WebSocket||E.MozWebSocket;class nt extends st{createSocket(e,t,s){return Ee?new J(e,t,s):t?new J(e,t):new J(e)}doWrite(e,t){this.ws.send(t)}}class it extends re{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=Ue(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),i=Me();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const r=()=>{s.read().then(({done:h,value:f})=>{h||(this.onPacket(f),r())}).catch(h=>{})};r();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],i=t===e.length-1;this._writer.write(s).then(()=>{i&&K(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const rt={websocket:nt,webtransport:it,polling:tt},ot=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ct=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function G(n){if(n.length>8e3)throw"URI too long";const e=n,t=n.indexOf("["),s=n.indexOf("]");t!=-1&&s!=-1&&(n=n.substring(0,t)+n.substring(t,s).replace(/:/g,";")+n.substring(s,n.length));let i=ot.exec(n||""),r={},o=14;for(;o--;)r[ct[o]]=i[o]||"";return t!=-1&&s!=-1&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=at(r,r.path),r.queryKey=ht(r,r.query),r}function at(n,e){const t=/\/{2,9}/g,s=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&s.splice(0,1),e.slice(-1)=="/"&&s.splice(s.length-1,1),s}function ht(n,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,i,r){i&&(t[i]=r)}),t}const Z=typeof addEventListener=="function"&&typeof removeEventListener=="function",j=[];Z&&addEventListener("offline",()=>{j.forEach(n=>n())},!1);class R extends w{constructor(e,t){if(super(),this.binaryType=Ve,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const s=G(e);t.hostname=s.host,t.secure=s.protocol==="https"||s.protocol==="wss",t.port=s.port,s.query&&(t.query=s.query)}else t.host&&(t.hostname=G(t.host).host);W(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(s=>{const i=s.prototype.name;this.transports.push(i),this._transportsByName[i]=s}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=ze(this.opts.query)),Z&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},j.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=ye,t.transport=e,this.id&&(t.sid=this.id);const s=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&R.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",R.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s<this.writeBuffer.length;s++){const i=this.writeBuffer[s].data;if(i&&(t+=We(i)),s>0&&t>this._maxPayload)return this.writeBuffer.slice(0,s);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,K(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,s){return this._sendPacket("message",e,t,s),this}send(e,t,s){return this._sendPacket("message",e,t,s),this}_sendPacket(e,t,s,i){if(typeof t=="function"&&(i=t,t=void 0),typeof s=="function"&&(i=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const r={type:e,data:t,options:s};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},s=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():e()}):this.upgrading?s():e()),this}_onError(e){if(R.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Z&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=j.indexOf(this._offlineEventListener);s!==-1&&j.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}R.protocol=ye;class ut extends R{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),s=!1;R.priorWebsocketSuccess=!1;const i=()=>{s||(t.send([{type:"ping",data:"probe"}]),t.once("packet",m=>{if(!s)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;R.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const y=new Error("probe error");y.transport=t.name,this.emitReserved("upgradeError",y)}}))};function r(){s||(s=!0,d(),t.close(),t=null)}const o=m=>{const y=new Error("probe error: "+m);y.transport=t.name,r(),this.emitReserved("upgradeError",y)};function h(){o("transport closed")}function f(){o("socket closed")}function u(m){t&&m.name!==t.name&&r()}const d=()=>{t.removeListener("open",i),t.removeListener("error",o),t.removeListener("close",h),this.off("close",f),this.off("upgrading",u)};t.once("open",i),t.once("error",o),t.once("close",h),this.once("close",f),this.once("upgrading",u),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{s||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let s=0;s<e.length;s++)~this.transports.indexOf(e[s])&&t.push(e[s]);return t}}let lt=class extends ut{constructor(e,t={}){const s=typeof e=="object"?e:t;(!s.transports||s.transports&&typeof s.transports[0]=="string")&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(i=>rt[i]).filter(i=>!!i)),super(e,s)}};function ft(n,e="",t){let s=n;t=t||typeof location<"u"&&location,n==null&&(n=t.protocol+"//"+t.host),typeof n=="string"&&(n.charAt(0)==="/"&&(n.charAt(1)==="/"?n=t.protocol+n:n=t.host+n),/^(https?|wss?):\/\//.test(n)||(typeof t<"u"?n=t.protocol+"//"+n:n="https://"+n),s=G(n)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const r=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+r+":"+s.port+e,s.href=s.protocol+"://"+r+(t&&t.port===s.port?"":":"+s.port),s}const dt=typeof ArrayBuffer=="function",pt=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,xe=Object.prototype.toString,gt=typeof Blob=="function"||typeof Blob<"u"&&xe.call(Blob)==="[object BlobConstructor]",mt=typeof File=="function"||typeof File<"u"&&xe.call(File)==="[object FileConstructor]";function oe(n){return dt&&(n instanceof ArrayBuffer||pt(n))||gt&&n instanceof Blob||mt&&n instanceof File}function V(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,s=n.length;t<s;t++)if(V(n[t]))return!0;return!1}if(oe(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return V(n.toJSON(),!0);for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&V(n[t]))return!0;return!1}function _t(n){const e=[],t=n.data,s=n;return s.data=ee(t,e),s.attachments=e.length,{packet:s,buffers:e}}function ee(n,e){if(!n)return n;if(oe(n)){const t={_placeholder:!0,num:e.length};return e.push(n),t}else if(Array.isArray(n)){const t=new Array(n.length);for(let s=0;s<n.length;s++)t[s]=ee(n[s],e);return t}else if(typeof n=="object"&&!(n instanceof Date)){const t={};for(const s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=ee(n[s],e));return t}return n}function yt(n,e){return n.data=te(n.data,e),delete n.attachments,n}function te(n,e){if(!n)return n;if(n&&n._placeholder===!0){if(typeof n.num=="number"&&n.num>=0&&n.num<e.length)return e[n.num];throw new Error("illegal attachments")}else if(Array.isArray(n))for(let t=0;t<n.length;t++)n[t]=te(n[t],e);else if(typeof n=="object")for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=te(n[t],e));return n}const Te=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],wt=5;var l;(function(n){n[n.CONNECT=0]="CONNECT",n[n.DISCONNECT=1]="DISCONNECT",n[n.EVENT=2]="EVENT",n[n.ACK=3]="ACK",n[n.CONNECT_ERROR=4]="CONNECT_ERROR",n[n.BINARY_EVENT=5]="BINARY_EVENT",n[n.BINARY_ACK=6]="BINARY_ACK"})(l||(l={}));class kt{constructor(e){this.replacer=e}encode(e){return(e.type===l.EVENT||e.type===l.ACK)&&V(e)?this.encodeAsBinary({type:e.type===l.EVENT?l.BINARY_EVENT:l.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===l.BINARY_EVENT||e.type===l.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=_t(e),s=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(s),i}}class ce extends w{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const s=t.type===l.BINARY_EVENT;s||t.type===l.BINARY_ACK?(t.type=s?l.EVENT:l.ACK,this.reconstructor=new bt(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(oe(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0;const s={type:Number(e.charAt(0))};if(l[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===l.BINARY_EVENT||s.type===l.BINARY_ACK){const r=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const o=e.substring(r,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");s.attachments=Number(o)}if(e.charAt(t+1)==="/"){const r=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););s.nsp=e.substring(r,t)}else s.nsp="/";const i=e.charAt(t+1);if(i!==""&&Number(i)==i){const r=t+1;for(;++t;){const o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}s.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(ce.isPayloadValid(s.type,r))s.data=r;else throw new Error("invalid payload")}return s}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case l.CONNECT:return H(t);case l.DISCONNECT:return t===void 0;case l.CONNECT_ERROR:return typeof t=="string"||H(t);case l.EVENT:case l.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Te.indexOf(t[0])===-1);case l.ACK:case l.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class bt{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const t=yt(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function vt(n){return typeof n=="string"}const Et=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n};function xt(n){return n===void 0||Et(n)}function H(n){return Object.prototype.toString.call(n)==="[object Object]"}function Tt(n,e){switch(n){case l.CONNECT:return e===void 0||H(e);case l.DISCONNECT:return e===void 0;case l.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Te.indexOf(e[0])===-1);case l.ACK:return Array.isArray(e);case l.CONNECT_ERROR:return typeof e=="string"||H(e);default:return!1}}function Ct(n){return vt(n.nsp)&&xt(n.id)&&Tt(n.type,n.data)}const St=Object.freeze(Object.defineProperty({__proto__:null,Decoder:ce,Encoder:kt,get PacketType(){return l},isPacketValid:Ct,protocol:wt},Symbol.toStringTag,{value:"Module"}));function x(n,e,t){return n.on(e,t),function(){n.off(e,t)}}const Nt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Ce extends w{constructor(e,t,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[x(e,"open",this.onopen.bind(this)),x(e,"packet",this.onpacket.bind(this)),x(e,"error",this.onerror.bind(this)),x(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var s,i,r;if(Nt.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const o={type:l.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const d=this.ids++,m=t.pop();this._registerAckCallback(d,m),o.id=d}const h=(i=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||i===void 0?void 0:i.writable,f=this.connected&&!(!((r=this.io.engine)===null||r===void 0)&&r._hasPingExpired());return this.flags.volatile&&!h||(f?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var s;const i=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}const r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let h=0;h<this.sendBuffer.length;h++)this.sendBuffer[h].id===e&&this.sendBuffer.splice(h,1);t.call(this,new Error("operation has timed out"))},i),o=(...h)=>{this.io.clearTimeoutFn(r),t.apply(this,h)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((s,i)=>{const r=(o,h)=>o?i(o):s(h);r.withError=!0,t.push(r),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...r)=>(this._queue[0],i!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(i)):(this._queue.shift(),t&&t(null,...r)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:l.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(s=>String(s.id)===e)){const s=this.acks[e];delete this.acks[e],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case l.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case l.EVENT:case l.BINARY_EVENT:this.onevent(e);break;case l.ACK:case l.BINARY_ACK:this.onack(e);break;case l.DISCONNECT:this.ondisconnect();break;case l.CONNECT_ERROR:this.destroy();const s=new Error(e.data.message);s.data=e.data.data,this.emitReserved("connect_error",s);break}}onevent(e){const t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const s of t)s.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let s=!1;return function(...i){s||(s=!0,t.packet({type:l.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:l.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const s of t)s.apply(this,e.data)}}}function B(n){n=n||{},this.ms=n.min||100,this.max=n.max||1e4,this.factor=n.factor||2,this.jitter=n.jitter>0&&n.jitter<=1?n.jitter:0,this.attempts=0}B.prototype.duration=function(){var n=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*n);n=Math.floor(e*10)&1?n+t:n-t}return Math.min(n,this.max)|0};B.prototype.reset=function(){this.attempts=0};B.prototype.setMin=function(n){this.ms=n};B.prototype.setMax=function(n){this.max=n};B.prototype.setJitter=function(n){this.jitter=n};class se extends w{constructor(e,t){var s;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,W(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((s=t.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new B({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||St;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new lt(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const i=x(t,"open",function(){s.onopen(),e&&e()}),r=h=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",h),e?e(h):this.maybeReconnectOnOpen()},o=x(t,"error",r);if(this._timeout!==!1){const h=this._timeout,f=this.setTimeoutFn(()=>{i(),r(new Error("timeout")),t.close()},h);this.opts.autoUnref&&f.unref(),this.subs.push(()=>{this.clearTimeoutFn(f)})}return this.subs.push(i),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(x(e,"ping",this.onping.bind(this)),x(e,"data",this.ondata.bind(this)),x(e,"error",this.onerror.bind(this)),x(e,"close",this.onclose.bind(this)),x(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){K(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let s=this.nsps[e];return s?this._autoConnect&&!s.active&&s.connect():(s=new Ce(this,e,t),this.nsps[e]=s),s}_destroy(e){const t=Object.keys(this.nsps);for(const s of t)if(this.nsps[s].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let s=0;s<t.length;s++)this.engine.write(t[s],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var s;this.cleanup(),(s=this.engine)===null||s===void 0||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):e.onreconnect()}))},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const D={};function F(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};const t=ft(n,e.path||"/socket.io"),s=t.source,i=t.id,r=t.path,o=D[i]&&r in D[i].nsps,h=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let f;return h?f=new se(s,e):(D[i]||(D[i]=new se(s,e)),f=D[i]),t.query&&!e.query&&(e.query=t.queryKey),f.socket(t.path,e)}Object.assign(F,{Manager:se,Socket:Ce,io:F,connect:F});function N(){return`${Date.now().toString(36)}-${Math.random().toString(16).slice(2,8)}`}class Rt{constructor(e){this.socket=null,this.reconnectAttempts=0,this.listeners=new Map,this.lastContext=null,this.config={reconnectAttempts:5,reconnectDelayMs:1500,logger:console,...e}}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{var s;return(s=this.listeners.get(e))==null?void 0:s.delete(t)}}emit(e,t){var s;(s=this.listeners.get(e))==null||s.forEach(i=>{var r,o;try{i(t)}catch(h){(o=(r=this.config.logger)==null?void 0:r.error)==null||o.call(r,`chat-sdk listener error for ${e}`,h)}})}setConnection(e){var t,s;this.emit("connection",e),(s=(t=this.config).onConnectionChange)==null||s.call(t,e)}async getToken(){var t,s;const{tokenProvider:e}=this.config;if(!e)return null;try{return(typeof e=="function"?await e():e)||null}catch(i){return(s=(t=this.config.logger)==null?void 0:t.warn)==null||s.call(t,"chat-sdk token provider failed",i),null}}async connect(){var r;if((r=this.socket)!=null&&r.connected)return;const e=new URL(this.config.websocketUrl),t=e.pathname==="/"?"/socket.io":e.pathname,s=e.origin,i=await this.getToken();return this.socket=F(s,{path:t,transports:["websocket","polling"],autoConnect:!1,reconnection:!1,auth:i?{token:i}:void 0}),this.registerSocketEvents(),this.setConnection({connected:!1,connecting:!0}),new Promise((o,h)=>{const f=setTimeout(()=>{h(new Error("connection timeout"))},1e4);this.socket.once("connect",()=>{clearTimeout(f),this.reconnectAttempts=0,this.setConnection({connected:!0,connecting:!1}),o()}),this.socket.once("connect_error",u=>{clearTimeout(f),this.setConnection({connected:!1,connecting:!1,error:u.message}),this.handleReconnect(),h(u)}),this.socket.connect()})}disconnect(){var e;(e=this.socket)==null||e.disconnect(),this.socket=null,this.setConnection({connected:!1,connecting:!1})}async submitInstruction(e,t){var r,o;if(!((r=this.socket)!=null&&r.connected))throw new Error("Not connected");this.lastContext=t;const s=await this.getToken(),i={trans_doc_id:t.trans_doc_id,page_num:t.page_num,instruction:e,modification_level:"page",access_token:s||void 0,region_coordinates:t.highlighted_region?{start_offset:t.highlighted_region.start_offset,end_offset:t.highlighted_region.end_offset}:void 0,region_text:(o=t.highlighted_region)==null?void 0:o.text,selection_id:t.selection_id};this.socket.emit("INSTR_SUBMIT",i)}async requestChatHistory(e){var s;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();this.lastContext=e,this.socket.emit("CHAT_HISTORY_REQUEST",{trans_doc_id:e.trans_doc_id,access_token:t||void 0})}async sendPatchDecision(e){var s;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();this.socket.emit("PATCH_DECISION",{...e,access_token:t||void 0})}async requestPageTranslation(e){var s;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();this.socket.emit("PAGE_TRANSLATION_REQUEST",{...e,access_token:t||void 0})}async requestBulkTranslation(e){var s;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();this.socket.emit("BULK_TRANSLATION_REQUEST",{...e,access_token:t||void 0})}async cancelBulkTranslation(e){var s;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();this.socket.emit("CANCEL_BULK_TRANSLATION_REQUEST",{trans_doc_id:e,access_token:t||void 0})}registerSocketEvents(){this.socket&&(this.socket.on("disconnect",()=>{this.setConnection({connected:!1,connecting:!1}),this.handleReconnect()}),this.socket.on("connect_error",e=>{this.setConnection({connected:!1,connecting:!1,error:e.message}),this.handleReconnect()}),this.socket.on("CHAT_RESPONSE",e=>{this.emit("chat-response",e)}),this.socket.on("PATCH_OFFER",e=>{this.emit("patch-offer",e)}),this.socket.on("CHAT_HISTORY_RESPONSE",e=>{this.emit("chat-history-response",e)}),this.socket.on("INSTRUCTION_ERROR",e=>{this.emit("instruction-error",e)}),this.socket.on("PAGE_TRANSLATION_RESPONSE",e=>{var t,s;this.emit("page-translation-response",e),(s=(t=this.config).onPageTranslationResponse)==null||s.call(t,e)}),this.socket.on("BULK_TRANSLATION_RESPONSE",e=>{var t,s;this.emit("bulk-translation-response",e),(s=(t=this.config).onBulkTranslationResponse)==null||s.call(t,e)}),this.socket.on("connected",()=>{this.lastContext&&this.requestChatHistory(this.lastContext).catch(e=>{var t,s;return(s=(t=this.config.logger)==null?void 0:t.warn)==null?void 0:s.call(t,"chat-sdk history on reconnect failed",e)})}))}handleReconnect(){var e,t;if(this.reconnectAttempts>=(this.config.reconnectAttempts??5)){(t=(e=this.config.logger)==null?void 0:e.warn)==null||t.call(e,"chat-sdk max reconnection attempts reached");return}this.reconnectAttempts+=1,setTimeout(()=>{this.connect().catch(s=>{var i,r;return(r=(i=this.config.logger)==null?void 0:i.error)==null?void 0:r.call(i,"chat-sdk reconnect failed",s)})},this.config.reconnectDelayMs)}}function At(n){return n.map(e=>{const t={id:N(),instructionId:e.instruction_id,pageNum:e.page_num,timestamp:new Date(e.timestamp)},s={...t,type:"user",content:e.instruction,contextText:e.region_text},i=[];return e.response_content&&e.response_type==="chat"&&i.push({...t,type:"ai-chat",content:e.response_content}),e.response_content&&e.response_type==="patch"&&i.push({...t,type:"ai-patch",content:e.response_content,patchData:{originalText:e.region_text,improvedText:e.response_content,regionText:e.region_text,isComplete:!0}}),[s,...i]}).flat().sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}const Se=k.createContext(null),Ot={connected:!1,connecting:!1};function Bt({config:n,children:e}){const t=k.useRef(null),s=k.useRef(new Map),[i,r]=k.useState({messages:[],connection:Ot,latestPatchOffer:null,isSubmitting:!1}),o=k.useMemo(()=>({reconnectAttempts:5,reconnectDelayMs:1500,...n}),[n]);k.useEffect(()=>{const u=new Rt(o);t.current=u;const d=u.on("connection",a=>{r(g=>({...g,connection:a}))}),m=u.on("chat-response",a=>{r(g=>{const p=[...g.messages];let _=p.find(v=>v.instructionId===a.instruction_id&&v.type==="ai-chat");_||(_={id:N(),type:"ai-chat",content:"",timestamp:new Date,instructionId:a.instruction_id,pageNum:a.page_num,isStreaming:!0},p.push(_));const S={..._,content:(_.content||"")+(a.chunk_text||""),isStreaming:!a.is_final},A=p.map(v=>v.id===_.id?S:v);return{...g,messages:A,isSubmitting:a.is_final?!1:g.isSubmitting}})}),y=u.on("patch-offer",a=>{var _;const g=`${a.trans_doc_id}-${a.instruction_id}`,p=s.current.get(g)??{trans_doc_id:a.trans_doc_id,page_num:a.page_num,instruction_id:a.instruction_id,original_text:a.region_original_text||"",highlighted_region:a.region_coordinates,new_suggestion:"",is_page_level:!a.region_coordinates,selection_id:a.selection_id};if(p.new_suggestion+=a.region_replacement_text_chunk||"",a.selection_id&&!p.selection_id&&(p.selection_id=a.selection_id),s.current.set(g,p),r(S=>{var ae;const A=[...S.messages];let v=A.find(L=>L.instructionId===a.instruction_id&&L.type==="ai-patch");v||(v={id:N(),type:"ai-patch",content:"",timestamp:new Date,instructionId:a.instruction_id,pageNum:a.page_num,isStreaming:!0,patchData:{originalText:a.region_original_text,improvedText:"",regionText:a.region_original_text,isComplete:!1}},A.push(v));const Ae={...v,content:(v.content||"")+(a.region_replacement_text_chunk||""),isStreaming:!a.is_final,patchData:{...v.patchData,improvedText:(((ae=v.patchData)==null?void 0:ae.improvedText)||"")+(a.region_replacement_text_chunk||""),regionText:a.region_original_text,isComplete:a.is_final}},Oe=A.map(L=>L.id===v.id?Ae:L);return{...S,messages:Oe,isSubmitting:a.is_final?!1:S.isSubmitting}}),a.is_final){const S=s.current.get(g);S&&((_=o.onPatchOffer)==null||_.call(o,S),r(A=>({...A,latestPatchOffer:S}))),s.current.delete(g)}}),b=u.on("chat-history-response",a=>{if(a.status==="success"){const g=At(a.messages);r(p=>({...p,messages:g}))}else r(g=>({...g,messages:[...g.messages,{id:N(),type:"system",content:a.error||"Failed to load chat history",timestamp:new Date}]}))}),O=u.on("instruction-error",a=>{r(g=>({...g,isSubmitting:!1,messages:[...g.messages,{id:N(),type:"error",content:a.error,timestamp:new Date}]}))}),P=u.on("page-translation-response",a=>{var g;(g=o.onPageTranslationResponse)==null||g.call(o,a)}),$=u.on("bulk-translation-response",a=>{var g;(g=o.onBulkTranslationResponse)==null||g.call(o,a)});return u.connect().then(()=>{const a=o.contextProvider();if(a)return u.requestChatHistory(a)}).catch(a=>{var g,p;return(p=(g=o.logger)==null?void 0:g.warn)==null?void 0:p.call(g,"chat-sdk connect failed",a)}),()=>{d(),m(),y(),b(),O(),P(),$(),u.disconnect()}},[o]);const h=k.useMemo(()=>({async submitInstruction(u){const d=t.current;if(!d)throw new Error("SDK not ready");const m=o.contextProvider();if(!m)throw new Error("contextProvider returned null");r(y=>{var b;return{...y,isSubmitting:!0,messages:[...y.messages,{id:N(),type:"user",content:u,timestamp:new Date,contextText:(b=m.highlighted_region)==null?void 0:b.text},{id:N(),type:"loading",content:"Processing your instruction...",timestamp:new Date,isStreaming:!0}]}}),await d.submitInstruction(u,m)},async submitInstructionWithContext(u,d){const m=t.current;if(!m)throw new Error("SDK not ready");r(y=>{var b;return{...y,isSubmitting:!0,messages:[...y.messages,{id:N(),type:"user",content:u,timestamp:new Date,contextText:(b=d.highlighted_region)==null?void 0:b.text},{id:N(),type:"loading",content:"Processing your instruction...",timestamp:new Date,isStreaming:!0}]}}),await m.submitInstruction(u,d)},async requestChatHistory(){const u=t.current;if(!u)throw new Error("SDK not ready");const d=o.contextProvider();if(!d)throw new Error("contextProvider returned null");await u.requestChatHistory(d)},async sendPatchDecision(u,d,m,y){const b=t.current;if(!b)throw new Error("SDK not ready");await b.sendPatchDecision({trans_doc_id:u,page_num:d,instruction_id:m,decision:y}),r(O=>({...O,latestPatchOffer:null}))},async requestPageTranslation(u,d){const m=t.current;if(!m)throw new Error("SDK not ready");return await m.requestPageTranslation({trans_doc_id:u,page_num:d}),!0},async requestBulkTranslation(u,d){const m=t.current;if(!m)throw new Error("SDK not ready");return await m.requestBulkTranslation({trans_doc_id:u,page_list:d}),!0},async cancelBulkTranslation(u){const d=t.current;if(!d)throw new Error("SDK not ready");return await d.cancelBulkTranslation(u),!0},clearMessages(){r(u=>({...u,messages:[]}))}}),[o]),f=k.useMemo(()=>({...i,...h}),[i,h]);return c.jsx(Se.Provider,{value:f,children:e})}function Pt(){const n=k.useContext(Se);if(!n)throw new Error("useChat must be used within ChatProvider");return n}function Ne(){return Pt()}const Re=k.forwardRef(({title:n="AI Assistance",placeholder:e="Ask anything...",height:t="500px"},s)=>{const{messages:i,connection:r,submitInstructionWithContext:o,isSubmitting:h}=Ne(),[f,u]=k.useState(""),[d,m]=k.useState(null),y=k.useRef(null),b=k.useRef(null),O=!r.connected||h,P=k.useMemo(()=>[...i].sort((p,_)=>p.timestamp.getTime()-_.timestamp.getTime()),[i]);k.useEffect(()=>{y.current&&(y.current.scrollTop=y.current.scrollHeight)},[P]),k.useImperativeHandle(s,()=>({focus:()=>{var p;(p=b.current)==null||p.focus()},setContext:p=>{m(p),p&&setTimeout(()=>{var _;return(_=b.current)==null?void 0:_.focus()},0)},clearContext:()=>{m(null)}}),[]);const $=async p=>{p.preventDefault();const _=f.trim();_&&(d?await o(_,d.context):await o(_,{trans_doc_id:"",page_num:0}),u(""),m(null))},a=(p,_=40)=>p.length>_?`${p.slice(0,_)}...`:p,g=()=>{m(null)};return c.jsxs("div",{className:"chat-sdk",style:{height:t},children:[c.jsxs("div",{className:"chat-sdk__header",children:[c.jsx("div",{className:"chat-sdk__title",children:n}),c.jsxs("div",{className:"chat-sdk__status",children:[c.jsx("span",{className:`chat-sdk__status-dot ${r.connected?"connected":"disconnected"}`}),r.connected?"Connected":r.connecting?"Connecting...":"Disconnected"]})]}),c.jsx("div",{className:"chat-sdk__messages",ref:y,children:P.length===0?c.jsx("div",{className:"chat-sdk__empty",children:"Welcome! Ask anything about the translation."}):P.map(p=>c.jsx(Lt,{message:p},p.id))}),c.jsxs("div",{className:"chat-sdk__composer",children:[c.jsxs("div",{className:"chat-sdk__input-bar",children:[d&&c.jsx("div",{className:"chat-sdk__input-context",children:c.jsxs("div",{className:"chat-sdk__context-chip",children:[c.jsx("span",{className:"chat-sdk__context-text",children:a(d.text)}),c.jsx("button",{type:"button",className:"chat-sdk__context-remove",onClick:g,"aria-label":"Remove context",children:c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:c.jsx("path",{d:"M1 1L9 9M9 1L1 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})})]})}),c.jsxs("form",{className:"chat-sdk__form",onSubmit:$,children:[c.jsx("div",{className:"chat-sdk__input-wrapper",children:c.jsx("textarea",{ref:b,className:"chat-sdk__input",placeholder:e,value:f,onChange:p=>u(p.target.value),disabled:O,rows:1})}),c.jsxs("div",{className:"chat-sdk__actions",children:[c.jsx("button",{type:"button",className:"chat-sdk__add-btn","aria-label":"Add context",children:c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:c.jsx("path",{d:"M8 3V13M3 8H13",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})}),c.jsx("button",{className:"chat-sdk__send",type:"submit",disabled:!f.trim()||O,"aria-label":"Send message",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:c.jsx("path",{d:"M7 12V2M7 2L3 6M7 2L11 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})]}),r.error&&c.jsxs("div",{className:"chat-sdk__error",children:["⚠️ ",r.error]})]})]})});Re.displayName="ChatWidget";function Lt({message:n}){var r;const e=n.type==="user",t=n.type==="loading",s=n.type==="ai-patch",i=(o,h=40)=>o.length>h?`${o.slice(0,h)}...`:o;return e?c.jsxs("div",{className:"chat-sdk__user-container",children:[n.contextText&&c.jsx("div",{className:"chat-sdk__user-context",children:c.jsx("div",{className:"chat-sdk__context-chip chat-sdk__context-chip--display",children:c.jsx("span",{className:"chat-sdk__context-text",children:i(n.contextText)})})}),c.jsx("div",{className:"chat-sdk__bubble user",children:c.jsx("div",{className:"chat-sdk__bubble-body",children:n.content})})]}):c.jsx("div",{className:"chat-sdk__ai-container",children:c.jsx("div",{className:"chat-sdk__ai-response",children:s&&((r=n.patchData)!=null&&r.originalText)?c.jsxs("div",{className:"chat-sdk__patch",children:[c.jsx("div",{className:"chat-sdk__ai-title",children:"I have a suggestion for you."}),c.jsxs("div",{className:"chat-sdk__patch-content",children:[c.jsx("div",{className:"chat-sdk__patch-label",children:"Original"}),c.jsx("div",{className:"chat-sdk__patch-block",children:n.patchData.originalText}),c.jsx("div",{className:"chat-sdk__patch-label",children:"Improved"}),c.jsxs("div",{className:"chat-sdk__patch-block",children:[n.patchData.improvedText,n.isStreaming&&c.jsx(Q,{})]})]})]}):c.jsx(c.Fragment,{children:n.content&&c.jsxs("div",{className:"chat-sdk__ai-body",children:[n.content,t&&c.jsx(Q,{}),n.isStreaming&&!t&&c.jsx(Q,{})]})})})})}function Q(){return c.jsxs("span",{className:"chat-sdk__stream",children:[c.jsx("span",{}),c.jsx("span",{}),c.jsx("span",{})]})}exports.ChatProvider=Bt;exports.ChatWidget=Re;exports.useChat=Ne;
2
2
  //# sourceMappingURL=translation-chat-sdk.cjs.js.map