@paramms/chat-widget 1.6.2 → 1.6.3

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,5 +1,5 @@
1
- var RelayEmbedLite=function(ee){"use strict";var Mn=Object.defineProperty;var $n=(ee,X,ce)=>X in ee?Mn(ee,X,{enumerable:!0,configurable:!0,writable:!0,value:ce}):ee[X]=ce;var c=(ee,X,ce)=>$n(ee,typeof X!="symbol"?X+"":X,ce);const X="oc_uid";function ce(t){try{const e=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return e?decodeURIComponent(e[1]):null}catch{return null}}function ht(t,e){try{const i=location.protocol==="https:"?"; Secure":"";document.cookie=`${t}=${encodeURIComponent(e)}; Max-Age=31536000; Path=/; SameSite=Lax${i}`}catch{}}function pt(){return`g_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`}function He(){let t=null;try{t=localStorage.getItem(X)}catch{}t||(t=ce(X));const e=t??pt();try{localStorage.setItem(X,e)}catch{}return ht(X,e),e}function ut(t){const e=t.length;let n=0,i=0;for(;i<e;){let o=t.charCodeAt(i++);if(o&4294967168)if(!(o&4294965248))n+=2;else{if(o>=55296&&o<=56319&&i<e){const s=t.charCodeAt(i);(s&64512)===56320&&(++i,o=((o&1023)<<10)+(s&1023)+65536)}o&4294901760?n+=4:n+=3}else{n++;continue}}return n}function ft(t,e,n){const i=t.length;let o=n,s=0;for(;s<i;){let r=t.charCodeAt(s++);if(r&4294967168)if(!(r&4294965248))e[o++]=r>>6&31|192;else{if(r>=55296&&r<=56319&&s<i){const w=t.charCodeAt(s);(w&64512)===56320&&(++s,r=((r&1023)<<10)+(w&1023)+65536)}r&4294901760?(e[o++]=r>>18&7|240,e[o++]=r>>12&63|128,e[o++]=r>>6&63|128):(e[o++]=r>>12&15|224,e[o++]=r>>6&63|128)}else{e[o++]=r;continue}e[o++]=r&63|128}}const wt=new TextEncoder,gt=50;function xt(t,e,n){wt.encodeInto(t,e.subarray(n))}function yt(t,e,n){t.length>gt?xt(t,e,n):ft(t,e,n)}const mt=4096;function We(t,e,n){let i=e;const o=i+n,s=[];let r="";for(;i<o;){const w=t[i++];if(!(w&128))s.push(w);else if((w&224)===192){const d=t[i++]&63;s.push((w&31)<<6|d)}else if((w&240)===224){const d=t[i++]&63,u=t[i++]&63;s.push((w&31)<<12|d<<6|u)}else if((w&248)===240){const d=t[i++]&63,u=t[i++]&63,g=t[i++]&63;let l=(w&7)<<18|d<<12|u<<6|g;l>65535&&(l-=65536,s.push(l>>>10&1023|55296),l=56320|l&1023),s.push(l)}else s.push(w);s.length>=mt&&(r+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(r+=String.fromCharCode(...s)),r}const bt=new TextDecoder,vt=200;function kt(t,e,n){const i=t.subarray(e,e+n);return bt.decode(i)}function St(t,e,n){return n>vt?kt(t,e,n):We(t,e,n)}class me{constructor(e,n){c(this,"type");c(this,"data");this.type=e,this.data=n}}class V extends Error{constructor(e){super(e);const n=Object.create(V.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:V.name})}}const he=4294967295;function It(t,e,n){const i=n/4294967296,o=n;t.setUint32(e,i),t.setUint32(e+4,o)}function Ke(t,e,n){const i=Math.floor(n/4294967296),o=n;t.setUint32(e,i),t.setUint32(e+4,o)}function Ve(t,e){const n=t.getInt32(e),i=t.getUint32(e+4);return n*4294967296+i}function Et(t,e){const n=t.getUint32(e),i=t.getUint32(e+4);return n*4294967296+i}const Tt=-1,Ct=4294967296-1,Ut=17179869184-1;function Bt({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=Ut)if(e===0&&t<=Ct){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,i=t&4294967295,o=new Uint8Array(8),s=new DataView(o.buffer);return s.setUint32(0,e<<2|n&3),s.setUint32(4,i),o}else{const n=new Uint8Array(12),i=new DataView(n.buffer);return i.setUint32(0,e),Ke(i,4,t),n}}function Lt(t){const e=t.getTime(),n=Math.floor(e/1e3),i=(e-n*1e3)*1e6,o=Math.floor(i/1e9);return{sec:n+o,nsec:i-o*1e9}}function At(t){if(t instanceof Date){const e=Lt(t);return Bt(e)}else return null}function zt(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const n=e.getUint32(0),i=e.getUint32(4),o=(n&3)*4294967296+i,s=n>>>2;return{sec:o,nsec:s}}case 12:{const n=Ve(e,4),i=e.getUint32(0);return{sec:n,nsec:i}}default:throw new V(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function Mt(t){const e=zt(t);return new Date(e.sec*1e3+e.nsec/1e6)}const $t={type:Tt,encode:At,decode:Mt},Ie=class Ie{constructor(){c(this,"__brand");c(this,"builtInEncoders",[]);c(this,"builtInDecoders",[]);c(this,"encoders",[]);c(this,"decoders",[]);this.register($t)}register({type:e,encode:n,decode:i}){if(e>=0)this.encoders[e]=n,this.decoders[e]=i;else{const o=-1-e;this.builtInEncoders[o]=n,this.builtInDecoders[o]=i}}tryToEncode(e,n){for(let i=0;i<this.builtInEncoders.length;i++){const o=this.builtInEncoders[i];if(o!=null){const s=o(e,n);if(s!=null){const r=-1-i;return new me(r,s)}}}for(let i=0;i<this.encoders.length;i++){const o=this.encoders[i];if(o!=null){const s=o(e,n);if(s!=null){const r=i;return new me(r,s)}}}return e instanceof me?e:null}decode(e,n,i){const o=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return o?o(e,n,i):new me(n,e)}};c(Ie,"defaultCodec",new Ie);let be=Ie;function Rt(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function Be(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Rt(t)?new Uint8Array(t):Uint8Array.from(t)}const Pt=100,_t=2048;class Le{constructor(e){c(this,"extensionCodec");c(this,"context");c(this,"useBigInt64");c(this,"maxDepth");c(this,"initialBufferSize");c(this,"sortKeys");c(this,"forceFloat32");c(this,"ignoreUndefined");c(this,"forceIntegerToFloat");c(this,"pos");c(this,"view");c(this,"bytes");c(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??be.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.maxDepth=(e==null?void 0:e.maxDepth)??Pt,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??_t,this.sortKeys=(e==null?void 0:e.sortKeys)??!1,this.forceFloat32=(e==null?void 0:e.forceFloat32)??!1,this.ignoreUndefined=(e==null?void 0:e.ignoreUndefined)??!1,this.forceIntegerToFloat=(e==null?void 0:e.forceIntegerToFloat)??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new Le({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){const n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){const n=new ArrayBuffer(e),i=new Uint8Array(n),o=new DataView(n);i.set(this.bytes),this.view=o,this.bytes=i}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const i=ut(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),yt(e,this.bytes,this.pos),this.pos+=i}encodeObject(e,n){const i=this.extensionCodec.tryToEncode(e,this.context);if(i!=null)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);const i=Be(e);this.writeU8a(i)}encodeArray(e,n){const i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else if(i<4294967296)this.writeU8(221),this.writeU32(i);else throw new Error(`Too large array: ${i}`);for(const o of e)this.doEncode(o,n+1)}countWithoutUndefined(e,n){let i=0;for(const o of n)e[o]!==void 0&&i++;return i}encodeMap(e,n){const i=Object.keys(e);this.sortKeys&&i.sort();const o=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(o<16)this.writeU8(128+o);else if(o<65536)this.writeU8(222),this.writeU16(o);else if(o<4294967296)this.writeU8(223),this.writeU32(o);else throw new Error(`Too large map object: ${o}`);for(const s of i){const r=e[s];this.ignoreUndefined&&r===void 0||(this.encodeString(s),this.doEncode(r,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const i=e.data(this.pos+6),o=i.length;if(o>=4294967296)throw new Error(`Too large extension object: ${o}`);this.writeU8(201),this.writeU32(o),this.writeI8(e.type),this.writeU8a(i);return}const n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),It(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Ke(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function Dt(t,e){return new Le(e).encodeSharedRef(t)}function Ae(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const qt=16,Nt=16;class jt{constructor(e=qt,n=Nt){c(this,"hit",0);c(this,"miss",0);c(this,"caches");c(this,"maxKeyLength");c(this,"maxLengthPerKey");this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let i=0;i<this.maxKeyLength;i++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,i){const o=this.caches[i-1];e:for(const s of o){const r=s.bytes;for(let w=0;w<i;w++)if(r[w]!==e[n+w])continue e;return s.str}return null}store(e,n){const i=this.caches[e.length-1],o={bytes:e,str:n};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=o:i.push(o)}decode(e,n,i){const o=this.find(e,n,i);if(o!=null)return this.hit++,o;this.miss++;const s=We(e,n,i),r=Uint8Array.prototype.slice.call(e,n,n+i);return this.store(r,s),s}}const ze="array",pe="map_key",Ge="map_value",Ot=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new V("The type of key must be string or number but "+typeof t)};class Ft{constructor(){c(this,"stack",[]);c(this,"stackHeadPosition",-1)}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=ze,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=pe,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===ze){const i=e;i.size=0,i.array=void 0,i.position=0,i.type=void 0}if(e.type===pe||e.type===Ge){const i=e;i.size=0,i.map=void 0,i.readCount=0,i.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const ue=-1,Me=new DataView(new ArrayBuffer(0)),Ht=new Uint8Array(Me.buffer);try{Me.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Ye=new RangeError("Insufficient data"),Wt=new jt;class $e{constructor(e){c(this,"extensionCodec");c(this,"context");c(this,"useBigInt64");c(this,"rawStrings");c(this,"maxStrLength");c(this,"maxBinLength");c(this,"maxArrayLength");c(this,"maxMapLength");c(this,"maxExtLength");c(this,"keyDecoder");c(this,"mapKeyConverter");c(this,"totalPos",0);c(this,"pos",0);c(this,"view",Me);c(this,"bytes",Ht);c(this,"headByte",ue);c(this,"stack",new Ft);c(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??be.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.rawStrings=(e==null?void 0:e.rawStrings)??!1,this.maxStrLength=(e==null?void 0:e.maxStrLength)??he,this.maxBinLength=(e==null?void 0:e.maxBinLength)??he,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??he,this.maxMapLength=(e==null?void 0:e.maxMapLength)??he,this.maxExtLength=(e==null?void 0:e.maxExtLength)??he,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:Wt,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??Ot}clone(){return new $e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=ue,this.stack.reset()}setBuffer(e){const n=Be(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===ue&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),i=Be(e),o=new Uint8Array(n.length+i.length);o.set(n),o.set(i,n.length),this.setBuffer(o)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:n,pos:i}=this;return new RangeError(`Extra ${n.byteLength-i} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,i;for await(const w of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(w);try{i=this.doDecodeSync(),n=!0}catch(d){if(!(d instanceof RangeError))throw d}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return i}const{headByte:o,pos:s,totalPos:r}=this;throw new RangeError(`Insufficient data in parsing ${Ae(o)} at ${r} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let i=n,o=-1;for await(const s of e){if(n&&o===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),i&&(o=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),--o!==0;);}catch(r){if(!(r instanceof RangeError))throw r}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const o=e-128;if(o!==0){this.pushMapState(o),this.complete();continue e}else n={}}else if(e<160){const o=e-144;if(o!==0){this.pushArrayState(o),this.complete();continue e}else n=[]}else{const o=e-160;n=this.decodeString(o,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){const o=this.lookU8();n=this.decodeString(o,1)}else if(e===218){const o=this.lookU16();n=this.decodeString(o,2)}else if(e===219){const o=this.lookU32();n=this.decodeString(o,4)}else if(e===220){const o=this.readU16();if(o!==0){this.pushArrayState(o),this.complete();continue e}else n=[]}else if(e===221){const o=this.readU32();if(o!==0){this.pushArrayState(o),this.complete();continue e}else n=[]}else if(e===222){const o=this.readU16();if(o!==0){this.pushMapState(o),this.complete();continue e}else n={}}else if(e===223){const o=this.readU32();if(o!==0){this.pushMapState(o),this.complete();continue e}else n={}}else if(e===196){const o=this.lookU8();n=this.decodeBinary(o,1)}else if(e===197){const o=this.lookU16();n=this.decodeBinary(o,2)}else if(e===198){const o=this.lookU32();n=this.decodeBinary(o,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){const o=this.lookU8();n=this.decodeExtension(o,1)}else if(e===200){const o=this.lookU16();n=this.decodeExtension(o,2)}else if(e===201){const o=this.lookU32();n=this.decodeExtension(o,4)}else throw new V(`Unrecognized type byte: ${Ae(e)}`);this.complete();const i=this.stack;for(;i.length>0;){const o=i.top();if(o.type===ze)if(o.array[o.position]=n,o.position++,o.position===o.size)n=o.array,i.release(o);else continue e;else if(o.type===pe){if(n==="__proto__")throw new V("The key __proto__ is not allowed");o.key=this.mapKeyConverter(n),o.type=Ge;continue e}else if(o.map[o.key]=n,o.readCount++,o.readCount===o.size)n=o.map,i.release(o);else{o.key=null,o.type=pe;continue e}}return n}}readHeadByte(){return this.headByte===ue&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=ue}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new V(`Unrecognized array type byte: ${Ae(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new V(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new V(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){var s;if(e>this.maxStrLength)throw new V(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Ye;const i=this.pos+n;let o;return this.stateIsMapKey()&&((s=this.keyDecoder)!=null&&s.canBeCached(e))?o=this.keyDecoder.decode(this.bytes,i,e):o=St(this.bytes,i,e),this.pos+=n+e,o}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===pe:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new V(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Ye;const i=this.pos+n,o=this.bytes.subarray(i,i+e);return this.pos+=n+e,o}decodeExtension(e,n){if(e>this.maxExtLength)throw new V(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const i=this.view.getInt8(this.pos+n),o=this.decodeBinary(e,n+1);return this.extensionCodec.decode(o,i,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=Et(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Ve(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function Kt(t,e){return new $e(e).decode(t)}const Vt=new Set(["auth","open","send","sync","history","read","typing","react","edit","delete","invoke","pubkey","ping","uploadPrekeys","fetchPrekey","assign","tag","note","agent_status","subscribe_inbox","unsubscribe_inbox"]);function Gt(t){return Vt.has(t.type)}function Re(t){return Dt(t)}function Xe(t){let e;try{e=Kt(t)}catch{return null}return typeof e!="object"||e===null||typeof e.type!="string"?null:e}class Yt{constructor(e){c(this,"conversationId");c(this,"state","");c(this,"version",0);c(this,"hasMoreHistory",!1);c(this,"lastReadByOthers",0);c(this,"assignedAgentId");c(this,"accent");c(this,"subject");c(this,"name");c(this,"e2e",!1);c(this,"offline",!1);c(this,"offlineMessage","");c(this,"launcherMessage",null);c(this,"preChat",null);c(this,"whiteLabel",!1);c(this,"typing",new Set);c(this,"online",new Set);c(this,"sentiment");c(this,"sentimentScore");c(this,"actions",[]);c(this,"byId",new Map);c(this,"keyByClient",new Map);c(this,"_maxSeq",0);c(this,"_sorted",null);this.me=e}messages(){return this._sorted||(this._sorted=[...this.byId.values()].sort((e,n)=>{const i=e.status==="pending",o=n.status==="pending";return i!==o?i?1:-1:i&&o?e.ts-n.ts:e.seq-n.seq})),this._sorted}visibleActions(){return this.actions.filter(e=>!e.availableInStates||e.availableInStates.includes(this.state))}highestSeq(){return this._maxSeq}addOptimistic(e,n){const i={id:e,conversationId:this.conversationId,seq:0,senderId:this.me,senderRole:"guest",content:n,ts:Date.now(),clientMsgId:e,status:"pending"};return this.byId.set(e,i),this.keyByClient.set(e,e),this._sorted=null,i}apply(e){var n;switch(e.type){case"opened":this.conversationId=e.conversation.id,this.state=e.conversation.state,e.subject&&(this.subject=e.subject);return;case"manifest":this.actions=e.actions,this.version=e.version,e.name&&(this.name=e.name),(n=e.theme)!=null&&n.accent&&(this.accent=e.theme.accent),e.e2e&&(this.e2e=!0),this.offline=e.offline===!0,this.offlineMessage=e.offlineMessage??"",e.launcherMessage&&(this.launcherMessage=e.launcherMessage),e.whiteLabel&&(this.whiteLabel=!0),e.preChat&&(this.preChat=e.preChat);return;case"message":this.upsert({...e.message});return;case"ack":{const i=this.keyByClient.get(e.clientMsgId),o=i?this.byId.get(i):void 0;if(o&&i){this.byId.delete(i);const s={...o,id:e.messageId,seq:e.seq,ts:e.ts,status:"sent"};this.byId.set(e.messageId,s),this.keyByClient.set(e.clientMsgId,e.messageId),e.seq>this._maxSeq&&(this._maxSeq=e.seq)}this._sorted=null;return}case"delivered":this.markOwnStatus(e.seq,"delivered");return;case"read":e.by!==this.me&&(this.lastReadByOthers=Math.max(this.lastReadByOthers,e.seq),this.markOwnStatus(e.seq,"read"));return;case"sync":for(const i of e.messages)this.upsert({...i});return;case"history":for(const i of e.messages)this.upsert({...i});this.hasMoreHistory=e.hasMore;return;case"typing":e.userId!==this.me&&(e.isTyping?this.typing.add(e.userId):this.typing.delete(e.userId));return;case"reaction":{const i=this.byId.get(e.messageId);if(!i)return;const o={...i.reactions??{}},s=(o[e.emoji]??[]).filter(r=>r!==e.by);e.removed||s.push(e.by),s.length?o[e.emoji]=s:delete o[e.emoji],this.byId.set(e.messageId,{...i,reactions:o}),this._sorted=null;return}case"edited":{const i=this.byId.get(e.messageId);i&&(this.byId.set(e.messageId,{...i,content:e.content,editedAt:e.editedAt}),this._sorted=null);return}case"deleted":{const i=this.byId.get(e.messageId);i&&(this.byId.set(e.messageId,{...i,deletedAt:e.ts}),this._sorted=null);return}case"state":this.state=e.state;return;case"assigned":this.assignedAgentId=e.agentId??void 0;return;case"presence":e.status==="online"?this.online.add(e.userId):this.online.delete(e.userId);return;case"subjectState":case"invoked":case"authed":case"error":case"pong":return;case"sentiment":this.sentiment=e.label,this.sentimentScore=e.score;return;default:return}}upsert(e){const n=this.byId.get(e.id);this.byId.set(e.id,n?{...n,...e}:e),e.seq>this._maxSeq&&(this._maxSeq=e.seq),this._sorted=null}markOwnStatus(e,n){const i=Je(n);let o=!1;for(const[s,r]of this.byId)r.senderId!==this.me||r.seq<=0||r.seq>e||Je(r.status)>=i||(this.byId.set(s,{...r,status:n}),o=!0);o&&(this._sorted=null)}}function Je(t){switch(t){case"read":return 3;case"delivered":return 2;case"sent":return 1;default:return 0}}class Xt{constructor(e){c(this,"socket",null);c(this,"state","idle");c(this,"authed",!1);c(this,"everAuthed",!1);c(this,"attempt",0);c(this,"outbox",[]);c(this,"stopped",!1);c(this,"timer",null);c(this,"refreshing",!1);this.opts=e}connect(){var i,o;if(this.state==="connecting"||this.state==="open")return;this.stopped=!1,this.state="connecting",this.authed=!1,(o=(i=this.opts).onStatusChange)==null||o.call(i,this.attempt>0?"reconnecting":"connecting");const n=(this.opts.socketFactory??Zt)(this.opts.url);n.binaryType="arraybuffer",this.socket=n,n.onopen=()=>{this.raw({type:"auth",token:this.opts.token})},n.onmessage=s=>{const r=Xe(new Uint8Array(s.data));!r||Gt(r)||this.handle(r)},n.onclose=()=>this.onClosed(),n.onerror=()=>{try{n.close()}catch{}}}send(e){if(this.state==="open"&&this.authed){this.raw(e);return}this.queue(e)}pendingCount(){return this.outbox.length}close(){var e;this.stopped=!0,this.timer&&clearTimeout(this.timer),this.state="closed";try{(e=this.socket)==null||e.close()}catch{}}handle(e){var n,i,o,s;if(e.type==="authed"&&(this.attempt=0,this.state="open",this.authed=!0,this.everAuthed=!0,(i=(n=this.opts).onStatusChange)==null||i.call(n,"open"),this.raw(this.opts.open),this.opts.open.type!=="open"&&this.flush()),e.type==="opened"&&(this.raw({type:"sync",conversationId:e.conversation.id,sinceSeq:this.opts.getCursor()}),this.flush(e.conversation.id)),e.type==="error"&&Jt.has(e.code)){if(e.code==="UNAUTHORIZED"&&this.opts.refreshToken&&!this.refreshing){this.refreshing=!0,(s=(o=this.opts).onStatusChange)==null||s.call(o,"reconnecting","Renewing session…"),this.opts.refreshToken().then(r=>{var w;if(this.refreshing=!1,!r){this.fatal(e);return}this.opts.token=r;try{(w=this.socket)==null||w.close()}catch{}}).catch(()=>{this.refreshing=!1,this.fatal(e)});return}this.fatal(e);return}this.opts.onFrame(e)}fatal(e){var n,i,o;this.stopped=!0;try{(n=this.socket)==null||n.close()}catch{}this.state="closed",(o=(i=this.opts).onStatusChange)==null||o.call(i,"error",Qt(e.code)),this.opts.onFrame(e)}flush(e){const n=this.outbox;this.outbox=[];for(const i of n)this.raw(e&&i.type==="send"&&i.conversationId!==e?{...i,conversationId:e}:i)}queue(e){const n=this.opts.maxOutbox??1e3;this.outbox.length>=n&&(this.outbox=this.outbox.slice(this.outbox.length-(n>>1))),this.outbox.push(e)}raw(e){if(!this.socket){this.queue(e);return}try{this.socket.send(Re(e))}catch{this.queue(e)}}onClosed(){var o,s;if(this.authed=!1,this.socket=null,this.stopped){this.state="closed";return}this.state="idle";const e=this.opts.backoffBaseMs??500,n=this.opts.backoffMaxMs??15e3,i=Math.min(n,e*2**this.attempt)*(.5+Math.random()*.5);this.attempt++,this.attempt>=3&&!this.everAuthed&&((s=(o=this.opts).onStatusChange)==null||s.call(o,"reconnecting","Can't reach chat — retrying…")),this.timer=setTimeout(()=>this.connect(),i)}}const Jt=new Set(["UNAUTHORIZED"]);function Qt(t){switch(t){case"UNAUTHORIZED":return"Chat unavailable — sign-in/token was rejected";default:return"Chat unavailable"}}function Zt(t){return new WebSocket(t)}const Qe=200,en=7*864e5;class tn{constructor(e){c(this,"key");this.key=`ocw_outbox_${e}`}load(){try{const e=localStorage.getItem(this.key);if(!e)return[];const n=JSON.parse(e),i=Date.now()-en,o=n.filter(s=>s.ts>=i);return o.length!==n.length&&this.save(o),o}catch{return[]}}add(e){try{const n=this.load();n.push(e),this.save(n.length>Qe?n.slice(n.length-Qe):n)}catch{}}remove(e){try{const n=this.load().filter(i=>i.clientMsgId!==e);this.save(n)}catch{}}save(e){try{localStorage.setItem(this.key,JSON.stringify(e))}catch{}}}const nn={accent:"#6c5ce7",accent2:"#4c6fff",bg:"#f4f3fb",card:"#fff",tint:"#eeecfb",line:"#e6e2f5",ink:"#221d3a",mut:"#8f8aa8",onaccent:"#fff",rowhover:"#e7e3f8",shadow:"0 12px 32px rgba(108,92,231,.14)"},on={accent:"#a99cf2",accent2:"#6f8cff",bg:"#221d3a",card:"#2b2550",tint:"#2f2853",line:"#3a3363",ink:"#eceafc",mut:"#9b93c9",onaccent:"#221d3a",rowhover:"#39325e",shadow:"0 12px 32px rgba(0,0,0,.4)"},sn="'Nunito',-apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif";function Ze(t,e){return Object.entries(e).map(([n,i])=>`--${t}-${n}:${i};`).join(" ")}function et(t){return`${Ze(t,nn)} --${t}-fb:${sn}; --${t}-fh:'Baloo 2',var(--${t}-fb);`}function ve(t){return Ze(t,on)}const rn=`
2
- .ocw { ${et("ocw")}
1
+ var RelayEmbedLite=function(ee){"use strict";var $n=Object.defineProperty;var Rn=(ee,X,ce)=>X in ee?$n(ee,X,{enumerable:!0,configurable:!0,writable:!0,value:ce}):ee[X]=ce;var c=(ee,X,ce)=>Rn(ee,typeof X!="symbol"?X+"":X,ce);const X="oc_uid";function ce(t){try{const e=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return e?decodeURIComponent(e[1]):null}catch{return null}}function pt(t,e){try{const o=location.protocol==="https:"?"; Secure":"";document.cookie=`${t}=${encodeURIComponent(e)}; Max-Age=31536000; Path=/; SameSite=Lax${o}`}catch{}}function ut(){return`g_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`}function We(){let t=null;try{t=localStorage.getItem(X)}catch{}t||(t=ce(X));const e=t??ut();try{localStorage.setItem(X,e)}catch{}return pt(X,e),e}function ft(t){const e=t.length;let n=0,o=0;for(;o<e;){let i=t.charCodeAt(o++);if(i&4294967168)if(!(i&4294965248))n+=2;else{if(i>=55296&&i<=56319&&o<e){const s=t.charCodeAt(o);(s&64512)===56320&&(++o,i=((i&1023)<<10)+(s&1023)+65536)}i&4294901760?n+=4:n+=3}else{n++;continue}}return n}function wt(t,e,n){const o=t.length;let i=n,s=0;for(;s<o;){let r=t.charCodeAt(s++);if(r&4294967168)if(!(r&4294965248))e[i++]=r>>6&31|192;else{if(r>=55296&&r<=56319&&s<o){const w=t.charCodeAt(s);(w&64512)===56320&&(++s,r=((r&1023)<<10)+(w&1023)+65536)}r&4294901760?(e[i++]=r>>18&7|240,e[i++]=r>>12&63|128,e[i++]=r>>6&63|128):(e[i++]=r>>12&15|224,e[i++]=r>>6&63|128)}else{e[i++]=r;continue}e[i++]=r&63|128}}const xt=new TextEncoder,gt=50;function yt(t,e,n){xt.encodeInto(t,e.subarray(n))}function mt(t,e,n){t.length>gt?yt(t,e,n):wt(t,e,n)}const bt=4096;function Ke(t,e,n){let o=e;const i=o+n,s=[];let r="";for(;o<i;){const w=t[o++];if(!(w&128))s.push(w);else if((w&224)===192){const l=t[o++]&63;s.push((w&31)<<6|l)}else if((w&240)===224){const l=t[o++]&63,u=t[o++]&63;s.push((w&31)<<12|l<<6|u)}else if((w&248)===240){const l=t[o++]&63,u=t[o++]&63,x=t[o++]&63;let d=(w&7)<<18|l<<12|u<<6|x;d>65535&&(d-=65536,s.push(d>>>10&1023|55296),d=56320|d&1023),s.push(d)}else s.push(w);s.length>=bt&&(r+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(r+=String.fromCharCode(...s)),r}const vt=new TextDecoder,kt=200;function St(t,e,n){const o=t.subarray(e,e+n);return vt.decode(o)}function It(t,e,n){return n>kt?St(t,e,n):Ke(t,e,n)}class me{constructor(e,n){c(this,"type");c(this,"data");this.type=e,this.data=n}}class V extends Error{constructor(e){super(e);const n=Object.create(V.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:V.name})}}const he=4294967295;function Tt(t,e,n){const o=n/4294967296,i=n;t.setUint32(e,o),t.setUint32(e+4,i)}function Ve(t,e,n){const o=Math.floor(n/4294967296),i=n;t.setUint32(e,o),t.setUint32(e+4,i)}function Ge(t,e){const n=t.getInt32(e),o=t.getUint32(e+4);return n*4294967296+o}function Et(t,e){const n=t.getUint32(e),o=t.getUint32(e+4);return n*4294967296+o}const Ct=-1,Ut=4294967296-1,Bt=17179869184-1;function Lt({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=Bt)if(e===0&&t<=Ut){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,o=t&4294967295,i=new Uint8Array(8),s=new DataView(i.buffer);return s.setUint32(0,e<<2|n&3),s.setUint32(4,o),i}else{const n=new Uint8Array(12),o=new DataView(n.buffer);return o.setUint32(0,e),Ve(o,4,t),n}}function At(t){const e=t.getTime(),n=Math.floor(e/1e3),o=(e-n*1e3)*1e6,i=Math.floor(o/1e9);return{sec:n+i,nsec:o-i*1e9}}function zt(t){if(t instanceof Date){const e=At(t);return Lt(e)}else return null}function Mt(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const n=e.getUint32(0),o=e.getUint32(4),i=(n&3)*4294967296+o,s=n>>>2;return{sec:i,nsec:s}}case 12:{const n=Ge(e,4),o=e.getUint32(0);return{sec:n,nsec:o}}default:throw new V(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function $t(t){const e=Mt(t);return new Date(e.sec*1e3+e.nsec/1e6)}const Rt={type:Ct,encode:zt,decode:$t},Ie=class Ie{constructor(){c(this,"__brand");c(this,"builtInEncoders",[]);c(this,"builtInDecoders",[]);c(this,"encoders",[]);c(this,"decoders",[]);this.register(Rt)}register({type:e,encode:n,decode:o}){if(e>=0)this.encoders[e]=n,this.decoders[e]=o;else{const i=-1-e;this.builtInEncoders[i]=n,this.builtInDecoders[i]=o}}tryToEncode(e,n){for(let o=0;o<this.builtInEncoders.length;o++){const i=this.builtInEncoders[o];if(i!=null){const s=i(e,n);if(s!=null){const r=-1-o;return new me(r,s)}}}for(let o=0;o<this.encoders.length;o++){const i=this.encoders[o];if(i!=null){const s=i(e,n);if(s!=null){const r=o;return new me(r,s)}}}return e instanceof me?e:null}decode(e,n,o){const i=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return i?i(e,n,o):new me(n,e)}};c(Ie,"defaultCodec",new Ie);let be=Ie;function Pt(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function Be(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Pt(t)?new Uint8Array(t):Uint8Array.from(t)}const _t=100,Dt=2048;class Le{constructor(e){c(this,"extensionCodec");c(this,"context");c(this,"useBigInt64");c(this,"maxDepth");c(this,"initialBufferSize");c(this,"sortKeys");c(this,"forceFloat32");c(this,"ignoreUndefined");c(this,"forceIntegerToFloat");c(this,"pos");c(this,"view");c(this,"bytes");c(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??be.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.maxDepth=(e==null?void 0:e.maxDepth)??_t,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??Dt,this.sortKeys=(e==null?void 0:e.sortKeys)??!1,this.forceFloat32=(e==null?void 0:e.forceFloat32)??!1,this.ignoreUndefined=(e==null?void 0:e.ignoreUndefined)??!1,this.forceIntegerToFloat=(e==null?void 0:e.forceIntegerToFloat)??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new Le({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){const n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){const n=new ArrayBuffer(e),o=new Uint8Array(n),i=new DataView(n);o.set(this.bytes),this.view=i,this.bytes=o}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const o=ft(e);this.ensureBufferSizeToWrite(5+o),this.writeStringHeader(o),mt(e,this.bytes,this.pos),this.pos+=o}encodeObject(e,n){const o=this.extensionCodec.tryToEncode(e,this.context);if(o!=null)this.encodeExtension(o);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);const o=Be(e);this.writeU8a(o)}encodeArray(e,n){const o=e.length;if(o<16)this.writeU8(144+o);else if(o<65536)this.writeU8(220),this.writeU16(o);else if(o<4294967296)this.writeU8(221),this.writeU32(o);else throw new Error(`Too large array: ${o}`);for(const i of e)this.doEncode(i,n+1)}countWithoutUndefined(e,n){let o=0;for(const i of n)e[i]!==void 0&&o++;return o}encodeMap(e,n){const o=Object.keys(e);this.sortKeys&&o.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(e,o):o.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(`Too large map object: ${i}`);for(const s of o){const r=e[s];this.ignoreUndefined&&r===void 0||(this.encodeString(s),this.doEncode(r,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const o=e.data(this.pos+6),i=o.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);this.writeU8(201),this.writeU32(i),this.writeI8(e.type),this.writeU8a(o);return}const n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),Tt(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Ve(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function qt(t,e){return new Le(e).encodeSharedRef(t)}function Ae(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const jt=16,Nt=16;class Ot{constructor(e=jt,n=Nt){c(this,"hit",0);c(this,"miss",0);c(this,"caches");c(this,"maxKeyLength");c(this,"maxLengthPerKey");this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let o=0;o<this.maxKeyLength;o++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,o){const i=this.caches[o-1];e:for(const s of i){const r=s.bytes;for(let w=0;w<o;w++)if(r[w]!==e[n+w])continue e;return s.str}return null}store(e,n){const o=this.caches[e.length-1],i={bytes:e,str:n};o.length>=this.maxLengthPerKey?o[Math.random()*o.length|0]=i:o.push(i)}decode(e,n,o){const i=this.find(e,n,o);if(i!=null)return this.hit++,i;this.miss++;const s=Ke(e,n,o),r=Uint8Array.prototype.slice.call(e,n,n+o);return this.store(r,s),s}}const ze="array",pe="map_key",Ye="map_value",Ft=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new V("The type of key must be string or number but "+typeof t)};class Ht{constructor(){c(this,"stack",[]);c(this,"stackHeadPosition",-1)}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=ze,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=pe,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===ze){const o=e;o.size=0,o.array=void 0,o.position=0,o.type=void 0}if(e.type===pe||e.type===Ye){const o=e;o.size=0,o.map=void 0,o.readCount=0,o.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const ue=-1,Me=new DataView(new ArrayBuffer(0)),Wt=new Uint8Array(Me.buffer);try{Me.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Xe=new RangeError("Insufficient data"),Kt=new Ot;class $e{constructor(e){c(this,"extensionCodec");c(this,"context");c(this,"useBigInt64");c(this,"rawStrings");c(this,"maxStrLength");c(this,"maxBinLength");c(this,"maxArrayLength");c(this,"maxMapLength");c(this,"maxExtLength");c(this,"keyDecoder");c(this,"mapKeyConverter");c(this,"totalPos",0);c(this,"pos",0);c(this,"view",Me);c(this,"bytes",Wt);c(this,"headByte",ue);c(this,"stack",new Ht);c(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??be.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.rawStrings=(e==null?void 0:e.rawStrings)??!1,this.maxStrLength=(e==null?void 0:e.maxStrLength)??he,this.maxBinLength=(e==null?void 0:e.maxBinLength)??he,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??he,this.maxMapLength=(e==null?void 0:e.maxMapLength)??he,this.maxExtLength=(e==null?void 0:e.maxExtLength)??he,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:Kt,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??Ft}clone(){return new $e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=ue,this.stack.reset()}setBuffer(e){const n=Be(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===ue&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),o=Be(e),i=new Uint8Array(n.length+o.length);i.set(n),i.set(o,n.length),this.setBuffer(i)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:n,pos:o}=this;return new RangeError(`Extra ${n.byteLength-o} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,o;for await(const w of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(w);try{o=this.doDecodeSync(),n=!0}catch(l){if(!(l instanceof RangeError))throw l}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return o}const{headByte:i,pos:s,totalPos:r}=this;throw new RangeError(`Insufficient data in parsing ${Ae(i)} at ${r} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let o=n,i=-1;for await(const s of e){if(n&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),o&&(i=this.readArraySize(),o=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(r){if(!(r instanceof RangeError))throw r}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const i=e-128;if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e<160){const i=e-144;if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else{const i=e-160;n=this.decodeString(i,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){const i=this.lookU8();n=this.decodeString(i,1)}else if(e===218){const i=this.lookU16();n=this.decodeString(i,2)}else if(e===219){const i=this.lookU32();n=this.decodeString(i,4)}else if(e===220){const i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else if(e===221){const i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else if(e===222){const i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e===223){const i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e===196){const i=this.lookU8();n=this.decodeBinary(i,1)}else if(e===197){const i=this.lookU16();n=this.decodeBinary(i,2)}else if(e===198){const i=this.lookU32();n=this.decodeBinary(i,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){const i=this.lookU8();n=this.decodeExtension(i,1)}else if(e===200){const i=this.lookU16();n=this.decodeExtension(i,2)}else if(e===201){const i=this.lookU32();n=this.decodeExtension(i,4)}else throw new V(`Unrecognized type byte: ${Ae(e)}`);this.complete();const o=this.stack;for(;o.length>0;){const i=o.top();if(i.type===ze)if(i.array[i.position]=n,i.position++,i.position===i.size)n=i.array,o.release(i);else continue e;else if(i.type===pe){if(n==="__proto__")throw new V("The key __proto__ is not allowed");i.key=this.mapKeyConverter(n),i.type=Ye;continue e}else if(i.map[i.key]=n,i.readCount++,i.readCount===i.size)n=i.map,o.release(i);else{i.key=null,i.type=pe;continue e}}return n}}readHeadByte(){return this.headByte===ue&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=ue}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new V(`Unrecognized array type byte: ${Ae(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new V(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new V(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){var s;if(e>this.maxStrLength)throw new V(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Xe;const o=this.pos+n;let i;return this.stateIsMapKey()&&((s=this.keyDecoder)!=null&&s.canBeCached(e))?i=this.keyDecoder.decode(this.bytes,o,e):i=It(this.bytes,o,e),this.pos+=n+e,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===pe:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new V(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Xe;const o=this.pos+n,i=this.bytes.subarray(o,o+e);return this.pos+=n+e,i}decodeExtension(e,n){if(e>this.maxExtLength)throw new V(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const o=this.view.getInt8(this.pos+n),i=this.decodeBinary(e,n+1);return this.extensionCodec.decode(i,o,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=Et(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Ge(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function Vt(t,e){return new $e(e).decode(t)}const Gt=new Set(["auth","open","send","sync","history","read","typing","react","edit","delete","invoke","pubkey","ping","uploadPrekeys","fetchPrekey","assign","tag","note","agent_status","subscribe_inbox","unsubscribe_inbox"]);function Yt(t){return Gt.has(t.type)}function Re(t){return qt(t)}function Je(t){let e;try{e=Vt(t)}catch{return null}return typeof e!="object"||e===null||typeof e.type!="string"?null:e}class Xt{constructor(e){c(this,"conversationId");c(this,"state","");c(this,"version",0);c(this,"hasMoreHistory",!1);c(this,"lastReadByOthers",0);c(this,"assignedAgentId");c(this,"accent");c(this,"subject");c(this,"name");c(this,"e2e",!1);c(this,"offline",!1);c(this,"offlineMessage","");c(this,"launcherMessage",null);c(this,"preChat",null);c(this,"whiteLabel",!1);c(this,"typing",new Set);c(this,"online",new Set);c(this,"sentiment");c(this,"sentimentScore");c(this,"actions",[]);c(this,"byId",new Map);c(this,"keyByClient",new Map);c(this,"_maxSeq",0);c(this,"_sorted",null);this.me=e}messages(){return this._sorted||(this._sorted=[...this.byId.values()].sort((e,n)=>{const o=e.status==="pending",i=n.status==="pending";return o!==i?o?1:-1:o&&i?e.ts-n.ts:e.seq-n.seq})),this._sorted}visibleActions(){return this.actions.filter(e=>!e.availableInStates||e.availableInStates.includes(this.state))}highestSeq(){return this._maxSeq}addOptimistic(e,n){const o={id:e,conversationId:this.conversationId,seq:0,senderId:this.me,senderRole:"guest",content:n,ts:Date.now(),clientMsgId:e,status:"pending"};return this.byId.set(e,o),this.keyByClient.set(e,e),this._sorted=null,o}apply(e){var n;switch(e.type){case"opened":this.conversationId=e.conversation.id,this.state=e.conversation.state,e.subject&&(this.subject=e.subject);return;case"manifest":this.actions=e.actions,this.version=e.version,e.name&&(this.name=e.name),(n=e.theme)!=null&&n.accent&&(this.accent=e.theme.accent),e.e2e&&(this.e2e=!0),this.offline=e.offline===!0,this.offlineMessage=e.offlineMessage??"",e.launcherMessage&&(this.launcherMessage=e.launcherMessage),e.whiteLabel&&(this.whiteLabel=!0),e.preChat&&(this.preChat=e.preChat);return;case"message":this.upsert({...e.message});return;case"ack":{const o=this.keyByClient.get(e.clientMsgId),i=o?this.byId.get(o):void 0;if(i&&o){this.byId.delete(o);const s={...i,id:e.messageId,seq:e.seq,ts:e.ts,status:"sent"};this.byId.set(e.messageId,s),this.keyByClient.set(e.clientMsgId,e.messageId),e.seq>this._maxSeq&&(this._maxSeq=e.seq)}this._sorted=null;return}case"delivered":this.markOwnStatus(e.seq,"delivered");return;case"read":e.by!==this.me&&(this.lastReadByOthers=Math.max(this.lastReadByOthers,e.seq),this.markOwnStatus(e.seq,"read"));return;case"sync":for(const o of e.messages)this.upsert({...o});return;case"history":for(const o of e.messages)this.upsert({...o});this.hasMoreHistory=e.hasMore;return;case"typing":e.userId!==this.me&&(e.isTyping?this.typing.add(e.userId):this.typing.delete(e.userId));return;case"reaction":{const o=this.byId.get(e.messageId);if(!o)return;const i={...o.reactions??{}},s=(i[e.emoji]??[]).filter(r=>r!==e.by);e.removed||s.push(e.by),s.length?i[e.emoji]=s:delete i[e.emoji],this.byId.set(e.messageId,{...o,reactions:i}),this._sorted=null;return}case"edited":{const o=this.byId.get(e.messageId);o&&(this.byId.set(e.messageId,{...o,content:e.content,editedAt:e.editedAt}),this._sorted=null);return}case"deleted":{const o=this.byId.get(e.messageId);o&&(this.byId.set(e.messageId,{...o,deletedAt:e.ts}),this._sorted=null);return}case"state":this.state=e.state;return;case"assigned":this.assignedAgentId=e.agentId??void 0;return;case"presence":e.status==="online"?this.online.add(e.userId):this.online.delete(e.userId);return;case"subjectState":case"invoked":case"authed":case"error":case"pong":return;case"sentiment":this.sentiment=e.label,this.sentimentScore=e.score;return;default:return}}upsert(e){const n=this.byId.get(e.id);this.byId.set(e.id,n?{...n,...e}:e),e.seq>this._maxSeq&&(this._maxSeq=e.seq),this._sorted=null}markOwnStatus(e,n){const o=Qe(n);let i=!1;for(const[s,r]of this.byId)r.senderId!==this.me||r.seq<=0||r.seq>e||Qe(r.status)>=o||(this.byId.set(s,{...r,status:n}),i=!0);i&&(this._sorted=null)}}function Qe(t){switch(t){case"read":return 3;case"delivered":return 2;case"sent":return 1;default:return 0}}class Jt{constructor(e){c(this,"socket",null);c(this,"state","idle");c(this,"authed",!1);c(this,"everAuthed",!1);c(this,"attempt",0);c(this,"outbox",[]);c(this,"stopped",!1);c(this,"timer",null);c(this,"refreshing",!1);this.opts=e}connect(){var o,i;if(this.state==="connecting"||this.state==="open")return;this.stopped=!1,this.state="connecting",this.authed=!1,(i=(o=this.opts).onStatusChange)==null||i.call(o,this.attempt>0?"reconnecting":"connecting");const n=(this.opts.socketFactory??en)(this.opts.url);n.binaryType="arraybuffer",this.socket=n,n.onopen=()=>{this.raw({type:"auth",token:this.opts.token})},n.onmessage=s=>{const r=Je(new Uint8Array(s.data));!r||Yt(r)||this.handle(r)},n.onclose=()=>this.onClosed(),n.onerror=()=>{try{n.close()}catch{}}}send(e){if(this.state==="open"&&this.authed){this.raw(e);return}this.queue(e)}pendingCount(){return this.outbox.length}close(){var e;this.stopped=!0,this.timer&&clearTimeout(this.timer),this.state="closed";try{(e=this.socket)==null||e.close()}catch{}}handle(e){var n,o,i,s;if(e.type==="authed"&&(this.attempt=0,this.state="open",this.authed=!0,this.everAuthed=!0,(o=(n=this.opts).onStatusChange)==null||o.call(n,"open"),this.raw(this.opts.open),this.opts.open.type!=="open"&&this.flush()),e.type==="opened"&&(this.raw({type:"sync",conversationId:e.conversation.id,sinceSeq:this.opts.getCursor()}),this.flush(e.conversation.id)),e.type==="error"&&Qt.has(e.code)){if(e.code==="UNAUTHORIZED"&&this.opts.refreshToken&&!this.refreshing){this.refreshing=!0,(s=(i=this.opts).onStatusChange)==null||s.call(i,"reconnecting","Renewing session…"),this.opts.refreshToken().then(r=>{var w;if(this.refreshing=!1,!r){this.fatal(e);return}this.opts.token=r;try{(w=this.socket)==null||w.close()}catch{}}).catch(()=>{this.refreshing=!1,this.fatal(e)});return}this.fatal(e);return}this.opts.onFrame(e)}fatal(e){var n,o,i;this.stopped=!0;try{(n=this.socket)==null||n.close()}catch{}this.state="closed",(i=(o=this.opts).onStatusChange)==null||i.call(o,"error",Zt(e.code)),this.opts.onFrame(e)}flush(e){const n=this.outbox;this.outbox=[];for(const o of n)this.raw(e&&o.type==="send"&&o.conversationId!==e?{...o,conversationId:e}:o)}queue(e){const n=this.opts.maxOutbox??1e3;this.outbox.length>=n&&(this.outbox=this.outbox.slice(this.outbox.length-(n>>1))),this.outbox.push(e)}raw(e){if(!this.socket){this.queue(e);return}try{this.socket.send(Re(e))}catch{this.queue(e)}}onClosed(){var i,s;if(this.authed=!1,this.socket=null,this.stopped){this.state="closed";return}this.state="idle";const e=this.opts.backoffBaseMs??500,n=this.opts.backoffMaxMs??15e3,o=Math.min(n,e*2**this.attempt)*(.5+Math.random()*.5);this.attempt++,this.attempt>=3&&!this.everAuthed&&((s=(i=this.opts).onStatusChange)==null||s.call(i,"reconnecting","Can't reach chat — retrying…")),this.timer=setTimeout(()=>this.connect(),o)}}const Qt=new Set(["UNAUTHORIZED"]);function Zt(t){switch(t){case"UNAUTHORIZED":return"Chat unavailable — sign-in/token was rejected";default:return"Chat unavailable"}}function en(t){return new WebSocket(t)}const Ze=200,tn=7*864e5;class nn{constructor(e){c(this,"key");this.key=`ocw_outbox_${e}`}load(){try{const e=localStorage.getItem(this.key);if(!e)return[];const n=JSON.parse(e),o=Date.now()-tn,i=n.filter(s=>s.ts>=o);return i.length!==n.length&&this.save(i),i}catch{return[]}}add(e){try{const n=this.load();n.push(e),this.save(n.length>Ze?n.slice(n.length-Ze):n)}catch{}}remove(e){try{const n=this.load().filter(o=>o.clientMsgId!==e);this.save(n)}catch{}}save(e){try{localStorage.setItem(this.key,JSON.stringify(e))}catch{}}}const on={accent:"#6c5ce7",accent2:"#4c6fff",bg:"#f4f3fb",card:"#fff",tint:"#eeecfb",line:"#e6e2f5",ink:"#221d3a",mut:"#8f8aa8",onaccent:"#fff",rowhover:"#e7e3f8",shadow:"0 12px 32px rgba(108,92,231,.14)"},sn={accent:"#a99cf2",accent2:"#6f8cff",bg:"#221d3a",card:"#2b2550",tint:"#2f2853",line:"#3a3363",ink:"#eceafc",mut:"#9b93c9",onaccent:"#221d3a",rowhover:"#39325e",shadow:"0 12px 32px rgba(0,0,0,.4)"},rn="'Nunito',-apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif";function et(t,e){return Object.entries(e).map(([n,o])=>`--${t}-${n}:${o};`).join(" ")}function tt(t){return`${et(t,on)} --${t}-fb:${rn}; --${t}-fh:'Baloo 2',var(--${t}-fb);`}function ve(t){return et(t,sn)}const an=`
2
+ .ocw { ${tt("ocw")}
3
3
  position:relative;
4
4
  display:flex; flex-direction:column; height:100%; min-height:320px; background:var(--ocw-bg);
5
5
  font-family:var(--ocw-fb); color:var(--ocw-ink); overflow:hidden; }
@@ -189,8 +189,8 @@ var RelayEmbedLite=function(ee){"use strict";var Mn=Object.defineProperty;var $n
189
189
  .ocw-bubble-wrap:hover .ocw-translate-btn { opacity:1; }
190
190
  .ocw-translation { margin-top:6px; padding-top:6px; border-top:1px solid var(--ocw-line); font-size:13px; line-height:1.45; }
191
191
  .ocw-translation::before { content:'🌐 '; opacity:.75; }
192
- `,tt="objectchat-widget-styles",an=["👍","❤️","😂","😮","😢","🙏"],cn=400,ln='<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M22 2 11 13M22 2l-7 20-4-9-9-4 20-7z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function dn(){if(typeof document>"u"||document.getElementById(tt))return;const t=document.createElement("style");t.id=tt,t.textContent=rn,document.head.appendChild(t)}const nt="ocw-webfont";function hn(){if(typeof document>"u"||document.getElementById(nt))return;const t=document.createElement("link");t.id=nt,t.rel="stylesheet",t.href="https://fonts.googleapis.com/css2?family=Baloo+2:wght@500;600;700&family=Nunito:wght@400;500;600;700&display=swap",document.head.appendChild(t)}function a(t,e,n){const i=document.createElement(t);return e&&(i.className=e),n!==void 0&&(i.textContent=n),i}function pn(t){try{return new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function Pe(t){var e;switch(t.kind){case"text":return t.text;case"system":return typeof((e=t.data)==null?void 0:e.message)=="string"?String(t.data.message):t.event;case"card":return[t.title,t.body].filter(Boolean).join(" — ");case"attachment":return t.name??t.url;case"form":return t.prompt;case"appointment":return`📅 ${t.title} — ${new Date(t.startIso).toLocaleString()}`}}class un{constructor(e,n,i,o={}){c(this,"scroll");c(this,"chips");c(this,"typing");c(this,"quick");c(this,"formHost");c(this,"csatPanel");c(this,"awayNotice");c(this,"headStatus");c(this,"reopenBtn");c(this,"preChatPanel");c(this,"deflectPanel");c(this,"preChatBuilt",!1);c(this,"preChatDone",!1);c(this,"footer");c(this,"input");c(this,"subjectCard");c(this,"e2eBadge");c(this,"statusBadge");c(this,"headerName");c(this,"connStatus");c(this,"typingTimer",null);c(this,"csatSubmitted",!1);c(this,"sendBtn");c(this,"compactObserver",null);c(this,"storeRef",null);c(this,"cfgAccent2");c(this,"scrollCleanup",null);c(this,"translationCache",new Map);c(this,"showingTranslation",new Set);c(this,"subjectBuilt",!1);var R,O,B,J,p,h,C,m,k,E,$;this.root=e,this.me=n,this.h=i,this.cfg=o,dn(),o.webfont!==!1&&hn(),e.replaceChildren(),e.classList.add("ocw"),o.accent&&e.style.setProperty("--ocw-accent",o.accent);const s=o.accent2??o.accent;s&&e.style.setProperty("--ocw-accent2",s),this.cfgAccent2=o.accent2,e.dataset.theme=o.theme??"light";const r=a("div","ocw-head");if(this.h.onBack){const b=a("button","ocw-back","‹");b.type="button",b.setAttribute("aria-label","Back"),b.addEventListener("click",()=>this.h.onBack()),r.append(b)}const w=((R=o.subject)==null?void 0:R.ownerLabel)??((O=o.subject)==null?void 0:O.title)??"",d=a("div","ocw-avatar");w.trim()&&(d.textContent=w.trim()[0].toUpperCase(),r.append(d));const u=a("div","ocw-head-main");this.headerName=a("div","ocw-head-name",((B=o.subject)==null?void 0:B.ownerLabel)??((J=o.subject)==null?void 0:J.title)??""),u.append(this.headerName),this.headStatus=a("div","ocw-head-status"),this.headStatus.style.display="none",u.append(this.headStatus),(p=o.subject)!=null&&p.subtitle&&u.append(a("div","ocw-head-meta",o.subject.subtitle)),r.append(u),this.statusBadge=a("span","ocw-badge",((h=o.subject)==null?void 0:h.status)??""),(C=o.subject)!=null&&C.status||(this.statusBadge.style.display="none"),r.append(this.statusBadge),this.e2eBadge=a("span","ocw-e2e","🔒 E2E"),this.e2eBadge.style.display="none",r.append(this.e2eBadge),this.connStatus=a("span","ocw-conn-status"),this.connStatus.style.display="none",r.append(this.connStatus),r.append(a("button","ocw-menu","⋯")),this.chips=a("div","ocw-chiprow"),this.scroll=a("div","ocw-scroll"),this.subjectCard=a("div","ocw-subject"),this.typing=a("div","ocw-typing");const g=a("div","ocw-typing-bubble");g.append(a("div","ocw-typing-dot"),a("div","ocw-typing-dot"),a("div","ocw-typing-dot")),this.typing.append(g),this.quick=a("div","ocw-quick");for(const b of o.quickReplies??[]){const S=a("button",void 0,b);S.addEventListener("click",()=>{this.h.onSend(b),this.quick.style.display="none"}),this.quick.append(S)}this.formHost=a("div","ocw-form-host"),this.csatPanel=a("div","ocw-csat"),this.csatPanel.style.display="none",this.awayNotice=a("div","ocw-away"),this.awayNotice.style.display="none",this.preChatPanel=a("div","ocw-prechat"),this.preChatPanel.style.display="none",this.deflectPanel=a("div","ocw-deflect"),this.deflectPanel.style.display="none",this.input=a("textarea",void 0),this.input.rows=1,this.input.placeholder=((m=o.i18n)==null?void 0:m.placeholder)??"Message…";const l=a("button","ocw-sendbtn");l.type="button";const y=(k=o.i18n)==null?void 0:k.send;y?(l.textContent=y,l.classList.add("ocw-sendbtn-label"),l.setAttribute("aria-label",y)):(l.innerHTML=ln,l.setAttribute("aria-label","Send message")),l.disabled=!0,this.sendBtn=l,l.addEventListener("click",()=>this.flushSend()),this.input.addEventListener("input",()=>{var b,S;this.sendBtn.disabled=this.input.value.trim().length===0,this.autoGrowInput(),this.storeRef&&!this.storeRef.messages().some(j=>j.senderRole==="guest")?(S=(b=this.h).onDeflectQuery)==null||S.call(b,this.input.value):this.hideDeflection()}),this.input.addEventListener("keydown",b=>{b.isComposing||b.keyCode===229||(b.key==="Enter"&&!b.shiftKey?(b.preventDefault(),this.flushSend()):this.signalTyping())});const U=a("button","ocw-attach","📎");U.title="Attach image or file";const T=document.createElement("input");T.type="file",T.accept="image/*,.pdf,.txt,.doc,.docx",T.style.display="none",U.addEventListener("click",()=>T.click()),T.addEventListener("change",()=>{var b;(b=T.files)!=null&&b[0]&&this.h.onAttach&&this.h.onAttach(T.files[0]),T.value=""});const _=a("div","ocw-input");_.append(U,T,this.input,l);const z=a("div","ocw-footer");((E=o.i18n)==null?void 0:E.poweredBy)!==void 0?z.textContent=o.i18n.poweredBy:z.innerHTML='Powered by <a href="https://relay.paramms.com" target="_blank" rel="noopener">Relay</a>',this.footer=z,this.reopenBtn=a("button","ocw-reopen",(($=this.cfg.i18n)==null?void 0:$.reopen)??"Reopen conversation"),this.reopenBtn.type="button",this.reopenBtn.addEventListener("click",()=>{this.reopenBtn.style.display="none";const b=this.root.querySelector(".ocw-input textarea");b==null||b.focus()}),e.append(r,this.chips,this.scroll,this.typing,this.quick,this.formHost,this.csatPanel,this.preChatPanel,this.deflectPanel,this.awayNotice,_,this.reopenBtn,this.footer);const M=b=>{e.classList.toggle("ocw-compact",b>0&&b<cn)};M(e.clientWidth),typeof ResizeObserver<"u"&&(this.compactObserver=new ResizeObserver(b=>{var j;const S=((j=b[0])==null?void 0:j.contentRect.width)??e.clientWidth;M(S)}),this.compactObserver.observe(e))}getScrollEl(){return this.scroll}setScrollCleanup(e){var n;(n=this.scrollCleanup)==null||n.call(this),this.scrollCleanup=e}destroy(){var e,n;(e=this.scrollCleanup)==null||e.call(this),this.scrollCleanup=null,this.typingTimer&&(clearTimeout(this.typingTimer),this.typingTimer=null),(n=this.compactObserver)==null||n.disconnect(),this.compactObserver=null}flushSend(){this.hideDeflection();const e=this.input.value.trim();e&&(this.input.value="",this.sendBtn.disabled=!0,this.autoGrowInput(),this.h.onTyping(!1),this.h.onSend(e))}autoGrowInput(){this.input.style.height="auto";const e=this.input.scrollHeight;e>0?this.input.style.height=`${Math.min(e,120)}px`:this.input.style.removeProperty("height")}signalTyping(){const e=this.input.value.trim().slice(0,100)||void 0;this.h.onTyping(!0,e),this.typingTimer&&clearTimeout(this.typingTimer),this.typingTimer=setTimeout(()=>this.h.onTyping(!1),2e3)}setBotName(e){this.cfg.i18n={...this.cfg.i18n??{},aiAssistant:e}}render(e){var T,_,z,M,R,O,B,J;if(this.storeRef=e,e.accent&&(this.root.style.setProperty("--ocw-accent",e.accent),this.root.style.setProperty("--ocw-accent2",this.cfgAccent2??e.accent)),this.e2eBadge.style.display=e.e2e?"inline-flex":"none",this.buildSubjectCard(e),e.subject){const p=(T=this.cfg.subject)==null?void 0:T.ownerLabel;p&&(this.headerName.textContent=p)}this.quick.style.display=e.messages().length===0?"flex":"none",this.chips.replaceChildren();const n=e.visibleActions();this.chips.style.display=n.length?"flex":"none";for(const p of n)this.chips.append(this.chipEl(p));const i=this.scroll.scrollHeight,o=this.scroll.scrollTop;if(this.scroll.replaceChildren(),this.subjectCard.childNodes.length&&this.scroll.append(this.subjectCard),e.hasMoreHistory){const p=a("div","ocw-load-more");p.textContent="↑ Loading earlier messages…",p.style.pointerEvents="none",this.scroll.append(p)}let s=0,r=null;const w=[...e.messages()];for(let p=0;p<w.length;p++){const h=w[p],C=h.senderRole!=="system"&&h.senderId!==this.me&&!h.internal&&h.senderId!==r;this.scroll.append(this.messageEl(h,e,C,p===w.length-1)),h.senderRole!=="system"&&(r=h.senderId),h.senderId!==this.me&&h.seq>s&&(s=h.seq)}o>20?this.scroll.scrollTop=this.scroll.scrollHeight-i+o:this.scroll.scrollTop=this.scroll.scrollHeight,s>0&&this.h.onReadUpTo(s);const d=[...e.typing];this.typing.classList.toggle("active",d.length>0);const u=this.typing.querySelector(".ocw-typing-bubble");u&&u.setAttribute("aria-label",d.length?"typing":""),this.footer.style.display=e.whiteLabel?"none":"block";const g=e.messages().some(p=>p.senderRole==="guest");if(!!((_=e.preChat)!=null&&_.enabled)&&!this.preChatDone&&!g&&(e.preChat.showWhen!=="offline"||e.offline))this.preChatBuilt||this.buildPreChatPanel(e.preChat),this.preChatPanel.style.display="block",this.awayNotice.style.display="none",(z=this.root.querySelector(".ocw-input"))==null||z.style.setProperty("display","none");else{if(this.preChatPanel.style.display="none",e.offline){this.awayNotice.firstChild||this.awayNotice.append(a("span","ocw-away-icon","🌙"),a("span","",""));const p=this.awayNotice.lastChild;p.textContent=e.offlineMessage||((M=this.cfg.i18n)==null?void 0:M.offline)||"We're away right now — send your message and we'll reply as soon as we're back.",this.awayNotice.style.display="flex"}else this.awayNotice.style.display="none";(R=this.root.querySelector(".ocw-input"))==null||R.style.removeProperty("display")}const y=["resolved","closed","sold","issued","checked_out"];this.h.onCsat&&!this.csatSubmitted&&y.includes(e.state)&&e.messages().length>0&&(this.csatPanel.style.display==="none"&&this.buildCsatPanel(),this.csatPanel.style.display="block");const U=y.includes(e.state);if(e.offline?(this.headStatus.textContent=`● ${e.offlineMessage||((O=this.cfg.i18n)==null?void 0:O.away)||"Away"}`,this.headStatus.className="ocw-head-status away",this.headStatus.style.display=""):e.conversationId?(this.headStatus.textContent=`● ${((B=this.cfg.i18n)==null?void 0:B.online)??"Online"}`,this.headStatus.className="ocw-head-status online",this.headStatus.style.display=""):this.headStatus.style.display="none",U&&e.messages().length>0){const p=a("div","ocw-resolved-note",`— ${((J=this.cfg.i18n)==null?void 0:J.resolved)??"Marked as resolved"} —`);this.scroll.append(p),this.reopenBtn.style.display="block"}else this.reopenBtn.style.display="none"}setConnStatus(e,n){if(e==="open"){this.connStatus.style.display="none";return}this.connStatus.style.display="";const i=e==="error";this.connStatus.className=`ocw-conn-status${i?" err":e==="reconnecting"?" warn":""}`,this.connStatus.textContent=i?`⚠ ${n??"Chat unavailable"}`:e==="reconnecting"?n??"↻ reconnecting…":"● connecting…"}buildPreChatPanel(e){var d;this.preChatBuilt=!0,this.preChatPanel.replaceChildren(),this.preChatPanel.append(a("div","ocw-prechat-title",e.title??"Before we start…"));const n=a("div","ocw-offline-form"),i={};for(const u of e.fields??["name","email"]){const g=a("input","ocw-offline-input");g.type=u==="email"?"email":u==="phone"?"tel":"text",g.placeholder=u==="name"?"Your name":u==="email"?"Your email":"Your phone number",i[u]=g,n.append(g)}let o=null;if((d=e.topics)!=null&&d.length){o=a("select",void 0);const u=document.createElement("option");u.value="",u.textContent="What is this about?",o.append(u);for(const g of e.topics){const l=document.createElement("option");l.value=g,l.textContent=g,o.append(l)}n.append(o)}let s=null,r=null;if(e.callbackOption){const u=a("label","ocw-prechat-cb");s=document.createElement("input"),s.type="checkbox",u.append(s,document.createTextNode("📞 Request a call back")),n.append(u),i.phone||(r=a("input","ocw-offline-input"),r.type="tel",r.placeholder="Phone number for the call",r.style.display="none",s.addEventListener("change",()=>r.style.setProperty("display",s.checked?"block":"none")),n.append(r))}const w=a("button","ocw-offline-submit","Start chat");w.type="button",w.addEventListener("click",()=>{var y,U,T,_,z,M,R;const u=(y=i.email)==null?void 0:y.value.trim();if(i.email&&(!u||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(u))){i.email.focus();return}const g=!!(s!=null&&s.checked),l=(((U=i.phone)==null?void 0:U.value)??(r==null?void 0:r.value)??"").trim();if(g&&!l){(T=i.phone??r)==null||T.focus();return}if(o&&((_=e.topics)!=null&&_.length)&&!o.value){o.focus();return}w.disabled=!0,this.completePreChat(),(R=(M=this.h).onPreChat)==null||R.call(M,{...(z=i.name)!=null&&z.value.trim()?{name:i.name.value.trim()}:{},...u?{email:u}:{},...l?{phone:l}:{},...o!=null&&o.value?{topic:o.value}:{},...g?{callback:!0}:{}})}),n.append(w),this.preChatPanel.append(n)}completePreChat(){this.preChatDone=!0,this.preChatPanel.style.display="none",this.storeRef&&this.render(this.storeRef)}showDeflection(e){if(!e.length)return this.hideDeflection();this.deflectPanel.replaceChildren(),this.deflectPanel.append(a("div","ocw-deflect-hint","Instant answers — tap to expand"));for(const n of e.slice(0,3)){const i=a("button","ocw-deflect-card");i.append(a("div","ocw-deflect-q",n.title),a("div","ocw-deflect-a",n.answer)),i.addEventListener("click",()=>i.classList.toggle("open")),this.deflectPanel.append(i)}this.deflectPanel.style.display="flex"}hideDeflection(){this.deflectPanel.style.display="none",this.deflectPanel.replaceChildren()}buildCsatPanel(){this.csatPanel.replaceChildren(),this.csatPanel.append(a("div","ocw-csat-title","How did we do?"));const e=a("div","ocw-csat-stars"),n=[];for(let i=1;i<=5;i++){const o=a("button","ocw-csat-star","★");o.dataset.score=String(i),o.addEventListener("mouseenter",()=>n.forEach((s,r)=>s.classList.toggle("lit",r<i))),o.addEventListener("mouseleave",()=>n.forEach(s=>s.classList.remove("lit"))),o.addEventListener("click",()=>{var s,r;this.csatSubmitted=!0,this.csatPanel.replaceChildren(a("div","ocw-csat-done",`Thanks for your ${i}★ rating!`)),(r=(s=this.h).onCsat)==null||r.call(s,i)}),n.push(o),e.append(o)}this.csatPanel.append(e)}buildSubjectCard(e){if(this.subjectBuilt)return;const n=e.subject,i=this.cfg.subject,o=(n==null?void 0:n.title)??(i==null?void 0:i.title);if(!o)return;this.subjectBuilt=!0,this.subjectCard.replaceChildren(),this.subjectCard.append(a("div","ocw-subject-title",o)),i!=null&&i.subtitle&&this.subjectCard.append(a("div","ocw-subject-sub",i.subtitle));const s=a("div","ocw-tags");if(n)for(const[w,d]of Object.entries(n.fields))s.append(a("span","ocw-tag",`${w}: ${d}`));else for(const w of(i==null?void 0:i.tags)??[])s.append(a("span","ocw-tag",w));s.childNodes.length&&this.subjectCard.append(s);const r=(n==null?void 0:n.state)??(i==null?void 0:i.status);r&&(this.statusBadge.textContent=r,this.statusBadge.style.display="inline-flex")}chipEl(e){const n=a("button","ocw-chip",e.icon?`${e.icon} ${e.label}`:e.label);return n.dataset.actionId=e.id,n.addEventListener("click",async()=>{var i;e.confirm&&!await this.confirm(e.label)||((i=e.input)!=null&&i.length?this.openForm(e):this.h.onInvoke(e.id))}),n}confirm(e){return new Promise(n=>{const i=a("div","ocw-modal"),o=a("div","ocw-modal-card");o.append(a("div","ocw-modal-title",e)),o.append(a("div","ocw-modal-body",`Confirm “${e}”?`));const s=a("div","ocw-modal-actions"),r=a("button","ocw-modal-cancel","Cancel"),w=a("button","ocw-modal-ok","Confirm"),d=u=>{i.remove(),n(u)};r.addEventListener("click",()=>d(!1)),w.addEventListener("click",()=>d(!0)),i.addEventListener("click",u=>{u.target===i&&d(!1)}),s.append(r,w),o.append(s),i.append(o),this.root.append(i),w.focus()})}openForm(e){var w,d;this.formHost.replaceChildren();const n=a("div","ocw-form");n.append(a("div","ocw-form-title",e.icon?`${e.icon} ${e.label}`:e.label));const i=new Map;for(const u of e.input??[]){const g=a("label","ocw-form-row");if(g.append(a("span","ocw-form-lbl",u.label)),u.type==="select"&&((w=u.options)!=null&&w.length)){const l=a("select","ocw-form-input");u.required||l.append(a("option",void 0,"— select —"));for(const y of u.options){const U=a("option");U.value=y,U.textContent=y,l.append(U)}u.required&&(l.required=!0),g.append(l),i.set(u.name,l)}else{const l=a("input","ocw-form-input");l.type=u.type==="number"?"number":u.type==="date"?"datetime-local":"text",u.required&&(l.required=!0),g.append(l),i.set(u.name,l)}n.append(g)}const o=a("div","ocw-form-actions"),s=a("button","ocw-form-cancel","Cancel"),r=a("button","ocw-form-submit","Send");s.addEventListener("click",()=>this.formHost.replaceChildren()),r.addEventListener("click",()=>{const u={};for(const[g,l]of i){if(l.required&&!l.value){l.style.borderColor="#e5484d";return}u[g]=l.type==="number"?Number(l.value):l.value}this.formHost.replaceChildren(),this.h.onInvoke(e.id,u)}),o.append(s,r),n.append(o),this.formHost.append(n),(d=i.values().next().value)==null||d.focus()}messageEl(e,n,i=!1,o=!1){var U,T,_,z,M,R,O,B,J;if(e.senderRole==="system"){const p=a("div","ocw-sys");return p.textContent=e.deletedAt?"message deleted":Pe(e.content),p}const s=e.senderId===this.me,r=!!e.internal,w=a("div",`ocw-row ${r?"ocw-note mine":s?"mine":"theirs"} ${e.senderRole==="bot"?"ocw-bot":""}`),d=a("div");if(i){const p=e.senderRole==="bot"?((U=this.cfg.i18n)==null?void 0:U.aiAssistant)??"AI Assistant":((T=this.cfg.subject)==null?void 0:T.ownerLabel)??((_=this.cfg.subject)==null?void 0:_.title)??"Support";d.append(a("div","ocw-msg-sender",p))}const u=a("div","ocw-bubble-wrap");if(e.replyToId){const p=a("div","ocw-reply-to","↩ replying to a message");p.style.cssText="font-size:11px;color:var(--ocw-mut);margin-bottom:2px;font-style:italic",d.append(p)}const g=a("div","ocw-bubble");let l=null;if(e.deletedAt)g.append(a("span","ocw-deleted","message deleted"));else if(e.content.kind==="attachment"){const p=e.content;if((z=p.mime)!=null&&z.startsWith("image/")){const h=document.createElement("img");h.src=p.url,h.alt=p.name??"image",h.style.cssText="max-width:220px;max-height:160px;border-radius:10px;display:block;cursor:pointer",h.addEventListener("click",()=>window.open(p.url,"_blank")),g.append(h)}else if((M=p.mime)!=null&&M.startsWith("video/")){const h=document.createElement("video");h.src=p.url,h.controls=!0,h.style.cssText="max-width:240px;max-height:180px;border-radius:10px;display:block",g.append(h)}else{const h=document.createElement("a");h.href=p.url,h.target="_blank",h.rel="noopener",h.style.cssText="display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none",h.append(a("span",void 0,"📄"),a("span",void 0,p.name??"file")),g.append(h)}}else if(e.content.kind==="appointment"){const p=e.content,h=a("div","ocw-appt");h.append(a("div","ocw-appt-title",`📅 ${p.title}`)),h.append(a("div","ocw-appt-time",new Date(p.startIso).toLocaleString()+" – "+new Date(p.endIso).toLocaleTimeString())),p.location&&h.append(a("div","ocw-appt-loc",`📍 ${p.location}`)),p.description&&h.append(a("div","ocw-appt-desc",p.description));const C=a("div","ocw-appt-links"),m=document.createElement("a");m.href=p.googleUrl,m.target="_blank",m.rel="noopener",m.className="ocw-appt-btn",m.textContent="📅 Add to Google Calendar";const k=document.createElement("a");k.href=p.icalUrl,k.download=`${p.title}.ics`,k.className="ocw-appt-btn ocw-appt-btn-sec",k.textContent="🍎 Apple / iCal",C.append(m,k),h.append(C),g.append(h)}else l=document.createTextNode(Pe(e.content)),g.append(l),e.editedAt&&g.append(a("span","ocw-edited","(edited)"));if(u.append(g),o&&!e.deletedAt&&e.content.kind==="text"&&((R=e.content.quickReplies)!=null&&R.length)){const p=a("div","ocw-flow-choices");p.style.cssText="display:flex;flex-wrap:wrap;gap:6px;margin-top:6px";for(const h of e.content.quickReplies){const C=a("button","ocw-flow-choice",h);C.type="button",C.style.cssText="border:1px solid var(--ocw-bd,rgba(0,0,0,.12));background:var(--ocw-bg,#fff);color:inherit;border-radius:14px;padding:5px 12px;font:inherit;font-size:13px;cursor:pointer",C.addEventListener("click",()=>{p.querySelectorAll("button").forEach(m=>m.disabled=!0),p.style.opacity="0.5",this.h.onSend(h)}),p.append(C)}u.append(p)}if(!s&&!r&&this.h.onTranslate&&e.content.kind==="text"&&!e.deletedAt&&e.seq>0&&l){const p=e.content.text;if(p.trim()){const h=a("button","ocw-translate-btn","🌐");h.type="button",h.title="Translate";const C=a("div","ocw-translation");C.style.display="none",g.append(C);const m=$=>{C.textContent=$,C.style.display="",this.showingTranslation.add(e.id),h.textContent="↩",h.title="Show original"},k=()=>{C.style.display="none",this.showingTranslation.delete(e.id),h.textContent="🌐",h.title="Translate"};h.addEventListener("click",$=>{if($.stopPropagation(),this.showingTranslation.has(e.id)){k();return}const b=this.translationCache.get(e.id);if(b!==void 0){m(b);return}h.textContent="⏳",this.h.onTranslate(p).then(S=>{if(S===null){h.textContent="⚠️",h.title="Translation unavailable",setTimeout(()=>{h.textContent="🌐",h.title="Translate"},1500);return}this.translationCache.set(e.id,S),m(S)})}),u.append(h);const E=this.translationCache.get(e.id);this.showingTranslation.has(e.id)&&E!==void 0&&m(E)}}if(s&&!e.deletedAt&&e.seq>0&&(this.h.onEdit??this.h.onDelete)){const p=a("div","ocw-msg-menu");if(this.h.onEdit){const h=a("button",void 0,"✏️");h.title="Edit",h.addEventListener("click",C=>{C.stopPropagation();const m=Pe(e.content),k=document.createElement("textarea");k.value=m,k.rows=Math.min(4,Math.ceil(m.length/40)+1),k.style.cssText="width:100%;resize:vertical;border:1px solid var(--ocw-accent);border-radius:8px;padding:6px 10px;font:inherit;font-size:14px;background:var(--ocw-card);color:#1c1b1a;box-sizing:border-box";const E=a("button","ocw-form-submit","Save");E.style.cssText="margin-top:6px;padding:5px 14px;font-size:13px";const $=a("button","ocw-form-cancel","Cancel");$.style.cssText="margin-top:6px;padding:5px 10px;font-size:13px";const b=a("div");b.style.cssText="display:flex;gap:6px;justify-content:flex-end",b.append($,E);const S=a("div");S.append(k,b),g.replaceChildren(S),k.focus(),k.select();const j=()=>g.replaceChildren(l??document.createTextNode(m));$.addEventListener("click",j),E.addEventListener("click",()=>{const F=k.value.trim();F&&F!==m&&this.h.onEdit(e.id,F),j()}),k.addEventListener("keydown",F=>{F.key==="Enter"&&!F.shiftKey&&(F.preventDefault(),E.click()),F.key==="Escape"&&j()})}),p.append(h)}if(this.h.onDelete){const h=a("button","del","🗑");h.title="Delete",h.addEventListener("click",C=>{C.stopPropagation(),this.h.onDelete(e.id)}),p.append(h)}u.append(p)}if(d.append(u),e.senderRole==="bot"&&!e.deletedAt&&e.seq>0&&e.content.kind==="text"){const p=e.content.citations;if(p!=null&&p.length){const h=a("div","ocw-cites");h.style.cssText="margin-top:4px;font-size:11px;color:var(--ocw-mut,#667)",h.textContent=`${((O=this.cfg.i18n)==null?void 0:O.sources)??"Sources"}: ${p.map(C=>C.source).join(", ")}`,d.append(h)}if(this.h.onReact){const h=a("div","ocw-bot-feedback");h.style.cssText="display:flex;gap:6px;margin-top:4px";const C=(m,k)=>{const E=a("button","ocw-fb-btn",m);E.type="button",E.title=k,E.style.cssText="border:1px solid var(--ocw-bd,rgba(0,0,0,.12));background:transparent;border-radius:12px;padding:1px 8px;font-size:12px;cursor:pointer;opacity:.7";const $=()=>{var b,S;return!!((S=(b=e.reactions)==null?void 0:b[m])!=null&&S.includes(this.me))};return $()&&(E.style.opacity="1"),E.addEventListener("click",()=>{var b,S;(S=(b=this.h).onReact)==null||S.call(b,e.id,m,$()),E.style.opacity="1"}),E};h.append(C("👍",((B=this.cfg.i18n)==null?void 0:B.helpful)??"Helpful"),C("👎",((J=this.cfg.i18n)==null?void 0:J.notHelpful)??"Not helpful")),d.append(h)}}if(this.h.onReact&&!e.deletedAt&&e.seq>0){const p=a("div","ocw-react-wrap"),h=a("div","ocw-react");if(e.reactions&&Object.keys(e.reactions).length)for(const[k,E]of Object.entries(e.reactions)){const $=a("button",`ocw-react-pill${E.includes(this.me)?" mine":""}`,`${k} ${E.length}`);$.addEventListener("click",()=>{var b,S;return(S=(b=this.h).onReact)==null?void 0:S.call(b,e.id,k,E.includes(this.me))}),h.append($)}const C=a("button","ocw-react-btn","+"),m=a("div","ocw-react-picker");for(const k of an){const E=a("button",void 0,k);E.addEventListener("click",$=>{var S,j,F,Q;$.stopPropagation();const b=(j=(S=e.reactions)==null?void 0:S[k])==null?void 0:j.includes(this.me);(Q=(F=this.h).onReact)==null||Q.call(F,e.id,k,!!b),m.style.display="none"}),m.append(E)}m.style.display="none",C.addEventListener("click",k=>{k.stopPropagation();const E=m.style.display==="none";m.style.display=E?"flex":"none",E&&document.addEventListener("click",()=>{m.style.display="none"},{once:!0})}),h.append(C),p.append(h,m),d.append(p)}else e.reactions&&Object.keys(e.reactions).length&&d.append(a("div","ocw-react",Object.entries(e.reactions).map(([p,h])=>`${p}${h.length}`).join(" ")));const y=a("div","ocw-time ocw-meta",pn(e.ts));if(s&&e.status){const p=a("span",`ocw-tick${e.status==="read"?" read":e.status==="delivered"?" delivered":""}`,fn(e.status));y.append(p)}return s&&e.seq>0&&n.lastReadByOthers>=e.seq&&y.append(a("span","ocw-seen"," · Seen")),d.append(y),w.append(d),w}}function fn(t){switch(t){case"read":return"✓✓";case"delivered":return"✓✓";case"sent":return"✓";default:return"🕓"}}const wn=20;function _e(t,e){var d;const n=t.trim().replace(/\/+$/,""),i=(d=n.match(/^(https|http|wss|ws):\/\//))==null?void 0:d[1],o=i?i==="https"||i==="wss":!0,s=(i?n.slice(i.length+3):n).replace(/\/ws$/,""),r=e?e.trim().replace(/\/+$/,""):`${o?"https":"http"}://${s}`;return{wsUrl:`${o?"wss":"ws"}://${s}/ws`,httpBase:r}}function gn(t){return _e(t).httpBase}function xn(t,e,n,i){const o=`beforeSeq=${n}&limit=${i}`;return[`${t}/conversations/${e}/messages?${o}`,`${t}/conversations/${e}/history?${o}`]}async function ot(t,e,n,i,o=wn){let s,r=!1;for(const w of xn(t,e,i,o))try{const d=await fetch(w,{headers:{authorization:`Bearer ${n}`}});if(r=!0,!d.ok)continue;const u=await d.json();return{messages:u.messages??[],hasMore:u.hasMore??!1}}catch(d){s=d}return r?console.error(`[chat-widget] history request to ${t} was rejected for conversation ${e}.`):console.error(`[chat-widget] could not load history from ${t} — the request never reached the server. This is almost always CORS: add this site's origin to the chatroom's allowed origins (dashboard → chatroom → allowed origins) or to the server's CORS_ORIGINS.`,s),null}async function yn(t,e,n,i,o,s){const r=s?s.replace(/\/+$/,""):gn(t),w=await ot(r,n,e,Number.MAX_SAFE_INTEGER);if(!w||(w.messages.length?(i.apply({type:"sync",conversationId:n,messages:w.messages}),i.apply({type:"history",conversationId:n,messages:[],hasMore:w.hasMore}),o.render(i)):i.apply({type:"history",conversationId:n,messages:[],hasMore:!1}),!w.hasMore))return;let d=!1;const u=async()=>{if(d||!i.hasMoreHistory)return;d=!0;const U=i.messages()[0];if(!U){d=!1;return}const T=await ot(r,n,e,U.seq);T&&(i.apply({type:"history",conversationId:n,messages:T.messages,hasMore:T.hasMore}),o.render(i)),d=!1},g=o.getScrollEl();if(!g)return;let l=!1;setTimeout(()=>{l=!0},300);const y=()=>{l&&g.scrollTop<80&&i.hasMoreHistory&&!d&&u()};g.addEventListener("scroll",y,{passive:!0}),o.setScrollCleanup(()=>g.removeEventListener("scroll",y))}const fe=new WeakMap,ke=new Map;function it(t){return`relay-launcher::${t.profileId}::${t.subjectId??""}`}let we=null;function mn(){if(we&&we.state!=="closed")return we;try{return we=new AudioContext,we}catch{return null}}function st(t){var P,H,G,K,Z,L,ae,le;fe.has(t.el)&&(fe.get(t.el).close(),fe.delete(t.el)),t.launcher&&((P=ke.get(it(t)))==null||P.close());const e=He();let n,i=!1;const o=t.token??t.userId??e,s=o!==e?e:void 0,{wsUrl:r,httpBase:w}=_e(t.url,t.apiUrl);let d=new Yt(o);const u=t.subjectId?`${o}::${t.subjectId}`:o,g=new tn(u);let l,y=!1,U=null,T=null,_=null,z=null;!t.launcher&&!t.el.style.height&&t.el.clientHeight===0&&(t.el.style.width=t.el.style.width||"100%",t.el.style.height="600px");for(const f of g.load())d.addOptimistic(f.clientMsgId,f.content);let M=null,R=null,O=0,B=!t.launcher;if(t.launcher){const x=(t.position??"bottom-right").includes("right");M=document.createElement("div"),M.style.cssText=`position:fixed;${x?"right:20px":"left:20px"};bottom:20px;z-index:9999;display:flex;flex-direction:column;align-items:${x?"flex-end":"flex-start"};gap:12px`;const I=document.createElement("div"),W=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(max-width: 479px)"):null,re=q=>{t.el.classList.toggle("ocw-fs",q),I.style.cssText=q?["position:fixed","inset:0","width:100%","height:100dvh","border-radius:0","overflow:hidden","box-shadow:none","display:none","flex-direction:column","background:#fff","transition:opacity .18s","opacity:0","z-index:9998"].join(";"):["width:min(380px, calc(100vw - 40px))","height:min(600px, calc(100dvh - 108px))","border-radius:28px","overflow:hidden","box-shadow:0 12px 32px rgba(108,92,231,.14)","display:none","flex-direction:column","background:#fff","transform-origin:bottom "+(x?"right":"left"),"transition:opacity .18s,transform .18s","opacity:0","transform:scale(.95)"].join(";")};re((W==null?void 0:W.matches)??!1);const ye=q=>re(q.matches);W==null||W.addEventListener("change",ye),U=W,T=ye,t.el.style.cssText="width:100%;height:100%;overflow:hidden",I.append(t.el);const Ee='<svg viewBox="0 0 24 24" width="26" height="26" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',Te='<svg viewBox="0 0 24 24" width="22" height="22" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/></svg>',Y=document.createElement("button");Y.type="button",Y.style.cssText=["width:56px;height:56px;border-radius:50%",`background:${t.accent??"#6c5ce7"}`,"color:#fff;border:none;cursor:pointer","box-shadow:0 12px 32px rgba(108,92,231,.14)","position:relative;flex:none","display:flex;align-items:center;justify-content:center","transition:transform .15s"].join(";"),Y.onmouseenter=()=>{Y.style.transform="scale(1.08)"},Y.onmouseleave=()=>{Y.style.transform="scale(1)"},R=document.createElement("span"),R.style.cssText="position:absolute;top:-4px;right:-4px;background:#4c6fff;color:#fff;border-radius:50%;width:20px;height:20px;font-size:11px;font-weight:700;display:none;align-items:center;justify-content:center";const Ce=()=>{Y.innerHTML=B?Te:Ee,Y.setAttribute("aria-label",B?"Close chat":"Open chat"),Y.setAttribute("aria-expanded",String(B)),Y.append(R)};Ce(),M.append(I,Y),document.body.append(M);const Ne=`ocw-teaser-dismissed::${t.profileId}`,Ue=typeof t.launcherMessage=="string"?{title:t.launcherMessage}:t.launcherMessage;let D=null;const An=()=>{try{return sessionStorage.getItem(Ne)==="1"}catch{return!1}},zn='<svg viewBox="0 0 24 24" width="15" height="15" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',ct=()=>{const q=Ue!=null&&Ue.title?Ue:d.launcherMessage??void 0;if(!(!!(q!=null&&q.title)&&!B&&!An())){D&&(D.remove(),D=null);return}if(D)return;D=document.createElement("div"),D.setAttribute("role","button"),D.setAttribute("tabindex","0"),D.setAttribute("aria-label",q.title),D.style.cssText=["max-width:280px","background:#fff","border-radius:16px","box-shadow:0 12px 32px rgba(108,92,231,.14)","padding:14px 40px 14px 16px","position:relative","cursor:pointer","font-family:inherit",`align-self:${x?"flex-end":"flex-start"}`,"animation:ocw-teaser-in .22s ease-out"].join(";");const Oe=document.createElement("div");if(Oe.textContent=q.title,Oe.style.cssText="font-size:15px;font-weight:600;color:#111;line-height:1.35",D.append(Oe),q.subtitle){const oe=document.createElement("div");oe.style.cssText="display:flex;align-items:center;gap:6px;margin-top:6px;font-size:13px;color:#6b7280";const Fe=document.createElement("span");Fe.innerHTML=zn,Fe.style.cssText=`color:${t.accent??"#6c5ce7"};display:inline-flex`;const dt=document.createElement("span");dt.textContent=q.subtitle,oe.append(Fe,dt),D.append(oe)}const de=document.createElement("button");de.type="button",de.setAttribute("aria-label","Dismiss"),de.innerHTML='<svg viewBox="0 0 24 24" width="14" height="14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M18 6 6 18M6 6l12 12" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/></svg>',de.style.cssText="position:absolute;top:8px;right:8px;width:24px;height:24px;border:none;border-radius:50%;background:#f3f4f6;color:#6b7280;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0",de.addEventListener("click",oe=>{oe.stopPropagation();try{sessionStorage.setItem(Ne,"1")}catch{}D&&(D.remove(),D=null)}),D.append(de);const lt=()=>{B||(B=!0,je(!0),Ce(),O=0,R&&(R.style.display="none"),D&&(D.remove(),D=null))};D.addEventListener("click",lt),D.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),lt())}),M.insertBefore(D,Y)};if(!document.getElementById("ocw-teaser-style")){const q=document.createElement("style");q.id="ocw-teaser-style",q.textContent="@keyframes ocw-teaser-in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",document.head.append(q)}z=ct,ct();const je=q=>{q?(I.style.display="flex",requestAnimationFrame(()=>{I.style.opacity="1",I.style.transform="scale(1)"})):(I.style.opacity="0",I.style.transform="scale(.95)",setTimeout(()=>{B||(I.style.display="none")},180))};Y.addEventListener("click",()=>{if(B=!B,je(B),Ce(),B){O=0,R&&(R.style.display="none");try{sessionStorage.setItem(Ne,"1")}catch{}}z==null||z()}),_=q=>{q.key==="Escape"&&B&&(B=!1,je(!1),Ce())},document.addEventListener("keydown",_)}const J=()=>{B||(O++,R&&(R.textContent=String(O),R.style.display="flex"))},p=()=>{try{const f=mn();if(!f)return;f.state==="suspended"&&f.resume().catch(()=>{});const x=f.createOscillator(),I=f.createGain();x.connect(I),I.connect(f.destination),x.frequency.setValueAtTime(880,f.currentTime),x.frequency.exponentialRampToValueAtTime(440,f.currentTime+.15),I.gain.setValueAtTime(.3,f.currentTime),I.gain.exponentialRampToValueAtTime(.001,f.currentTime+.3),x.start(),x.stop(f.currentTime+.3)}catch{}},h=[],C=f=>{for(;h.length;){const x=h.shift();g.add({clientMsgId:x.clientMsgId,content:x.content,ts:Date.now()}),m.send({type:"send",conversationId:f,clientMsgId:x.clientMsgId,content:x.content})}};let m;const k=t.i18n??{},E=["ar","he","fa","ur"],$=typeof navigator<"u"?(navigator.language??"").slice(0,2).toLowerCase():"";E.includes($)&&!t.el.dir&&(t.el.dir="rtl",t.el.style.fontFamily=t.el.style.fontFamily||"Tahoma,Arial,system-ui,sans-serif");const b=`oc_prechat_${t.profileId}_${o.slice(-8)}`,S=new un(t.el,o,{onSend(f){const x=`cm_${Math.random().toString(36).slice(2)}`,I={kind:"text",text:f};if(d.addOptimistic(x,I),S.render(d),d.e2e){console.error("[relay] this chat is end-to-end encrypted — use the full widget build");return}else l?(g.add({clientMsgId:x,content:I,ts:Date.now()}),m.send({type:"send",conversationId:l,clientMsgId:x,content:I})):h.push({clientMsgId:x,content:I})},async onAttach(f){if(!l)return;const x=`${w}/upload?name=${encodeURIComponent(f.name)}`,I=`cm_${Math.random().toString(36).slice(2)}`;d.addOptimistic(I,{kind:"text",text:`📎 Uploading ${f.name}…`}),S.render(d);try{const W=await fetch(x,{method:"POST",headers:{"content-type":f.type,authorization:`Bearer ${o}`},body:f});if(!W.ok)throw new Error(`Upload failed: ${W.status}`);const{url:re,name:ye,mime:Ee,size:Te}=await W.json();d.addOptimistic(I,{kind:"attachment",url:re,name:ye,mime:Ee,size:Te}),S.render(d),m.send({type:"send",conversationId:l,clientMsgId:I,content:{kind:"attachment",url:re,name:ye,mime:Ee,size:Te}})}catch(W){d.addOptimistic(I,{kind:"text",text:`⚠️ Upload failed: ${W.message}`}),S.render(d)}},onInvoke(f,x){l&&m.send({type:"invoke",conversationId:l,actionId:f,clientInvokeId:`iv_${Math.random().toString(36).slice(2)}`,...x?{inputs:x}:{}})},onTyping(f,x){l&&m.send({type:"typing",conversationId:l,isTyping:f,...x?{preview:x}:{}})},onPreChat(f){try{localStorage.setItem(b,"1")}catch{}m.send({type:"open",profileId:t.profileId,...t.subjectId?{subjectId:t.subjectId}:{},userInfo:{...f.name?{name:f.name}:{},...f.email?{email:f.email}:{},...f.phone||f.topic?{meta:{...f.phone?{phone:f.phone}:{},...f.topic?{topic:f.topic}:{}}}:{}}});const x=f.callback?`📞 Call-back requested${f.phone?`: ${f.phone}`:""}${f.topic?` — ${f.topic}`:""}`:f.topic?`Topic: ${f.topic}`:"";x&&l&&!d.e2e&&m.send({type:"send",conversationId:l,clientMsgId:`pc_${Math.random().toString(36).slice(2,12)}`,content:{kind:"text",text:x}})},...((H=t.features)==null?void 0:H.deflection)!==!1?{onDeflectQuery(f){if(i)return;clearTimeout(n);const x=f.trim();if(x.length<3){S.hideDeflection();return}n=setTimeout(()=>{fetch(`${w}/kb/search?profileId=${encodeURIComponent(t.profileId)}&q=${encodeURIComponent(x.slice(0,200))}`).then(I=>I.ok?I.json():{articles:[]}).then(I=>S.showDeflection(I.articles??[])).catch(()=>S.hideDeflection())},350)}}:{},onReadUpTo(f){l&&m.send({type:"read",conversationId:l,seq:f})},onLoadMore(){if(!l||!d.e2e)return;const f=d.messages()[0];f&&m.send({type:"history",conversationId:l,beforeSeq:f.seq,limit:20})},onEdit(f,x){l&&m.send({type:"edit",conversationId:l,messageId:f,content:{kind:"text",text:x}})},onDelete(f){l&&m.send({type:"delete",conversationId:l,messageId:f})},...((G=t.features)==null?void 0:G.reactions)!==!1?{onReact(f,x,I){l&&m.send({type:"react",conversationId:l,messageId:f,emoji:x,remove:I})}}:{},...((K=t.features)==null?void 0:K.csat)!==!1?{onCsat(f){l&&fetch(`${w}/conversations/${l}/csat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({score:f})}).catch(()=>{})}}:{},...t.translateLang?{async onTranslate(f){try{const x=await fetch(`${w}/translate`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify({text:f,targetLang:t.translateLang})});if(!x.ok)return null;const{translated:I}=await x.json();return I}catch{return null}}}:{},...t.onBack?{onBack:t.onBack}:{}},{...t.subject?{subject:t.subject}:{},...t.quickReplies?{quickReplies:t.quickReplies}:{},...t.accent?{accent:t.accent}:{},...t.accent2?{accent2:t.accent2}:{},...t.theme?{theme:t.theme}:{},...t.webfont===!1?{webfont:!1}:{},...(Z=t.user)!=null&&Z.name||(L=t.user)!=null&&L.avatar?{userInfo:{...t.user.name?{name:t.user.name}:{},...t.user.avatar?{avatar:t.user.avatar}:{}}}:{},i18n:k});try{localStorage.getItem(b)&&S.completePreChat()}catch{}const j=t.user&&(t.user.name||t.user.email||t.user.avatar||t.user.meta)?{...t.user.name?{name:t.user.name}:{},...t.user.email?{email:t.user.email}:{},...t.user.avatar?{avatar:t.user.avatar}:{},...t.user.meta?{meta:t.user.meta}:{}}:void 0,F={type:"open",profileId:t.profileId,...t.kind==="direct"&&t.peerId?{kind:"direct",peerId:t.peerId}:t.subjectId?{subjectId:t.subjectId}:{},...s?{linkFrom:s}:{},...j?{userInfo:j}:{},...typeof location<"u"?{pageUrl:location.href}:{},...typeof document<"u"&&document.title?{pageTitle:document.title}:{},...(ae=t.subject)!=null&&ae.title?{subjectTitle:t.subject.title}:{},...(le=t.subject)!=null&&le.subtitle?{subjectMeta:t.subject.subtitle}:{}};m=new Xt({...t.refreshToken?{refreshToken:t.refreshToken}:{},url:r,token:o,open:F,getCursor:()=>d.highestSeq(),onStatusChange:(f,x)=>S.setConnStatus(f,x),onFrame(f){if(f.type==="opened"){if(l=f.conversation.id,!y){y=!0;for(const x of g.load())m.send({type:"send",conversationId:l,clientMsgId:x.clientMsgId,content:x.content})}yn(r,o,l,d,S,w),h.length&&C(l)}f.type==="ack"&&g.remove(f.clientMsgId),(async()=>{if(d.apply(f),f.type==="manifest"){z==null||z();const x=f.botName;x&&S.setBotName(x)}f.type==="message"&&f.message.senderId!==o&&!f.message.internal&&(J(),p()),S.render(d)})()}}),m.connect(),S.render(d);const Q=t.launcher?it(t):null,v={close:()=>{i=!0,clearTimeout(n),m.close(),M==null||M.remove(),S.destroy(),U&&T&&U.removeEventListener("change",T),_&&(document.removeEventListener("keydown",_),_=null),fe.delete(t.el),Q&&ke.get(Q)===v&&ke.delete(Q)}};return fe.set(t.el,v),Q&&ke.set(Q,v),v}const De="wss://api.paramms.com/ws";function bn(t,e){const n=t.profileId??t.appId;if(!n)throw new Error("Relay: `profileId` is required (your chatroom id, e.g. 'p_...').");const i=t.subjectId??(t.listingId?`listing_${t.listingId}`:void 0),o=t.launcher??!0,s=t.contextTitle??t.listingTitle??t.subjectTitle,r=t.contextSubtitle??t.listingMeta??t.subjectMeta,w=t.contextStatus??t.listingStatus??t.subjectStatus,d=t.listingPrice??t.subjectPrice,u=s?{title:s,...r?{subtitle:r}:{},...d!=null?{tags:[`$${d.toLocaleString()}`]}:{},...w?{status:w}:{}}:void 0,g=t.subject??u,l=t.userName??t.name,y=t.userEmail??t.email,U=t.userAvatar??t.avatar,T=l||y||U?{...l?{name:l}:{},...y?{email:y}:{},...U?{avatar:U}:{}}:void 0,_=t.user??T,z=t.launcherMessage&&typeof t.launcherMessage=="object"?t.launcherMessage:t.launcherMessage?t.launcherSubtitle?{title:t.launcherMessage,subtitle:t.launcherSubtitle}:t.launcherMessage:void 0;return{el:e,url:t.url??De,profileId:n,...t.apiUrl?{apiUrl:t.apiUrl}:{},...i?{subjectId:i}:{},...t.token?{token:t.token}:{},...t.refreshToken?{refreshToken:t.refreshToken}:{},...t.userId?{userId:t.userId}:{},...g?{subject:g}:{},..._?{user:_}:{},...t.quickReplies?{quickReplies:t.quickReplies}:{},...t.i18n?{i18n:t.i18n}:{},...t.features?{features:t.features}:{},...t.accent?{accent:t.accent}:{},...t.accent2?{accent2:t.accent2}:{},...t.theme?{theme:t.theme}:{},...t.webfont===!1?{webfont:!1}:{},...t.translateLang?{translateLang:t.translateLang}:{},...z?{launcherMessage:z}:{},...rt(t)&&!o?{onBack:()=>{ge=!0,xe=!1,Se(se)}}:{},launcher:o,position:t.position??"bottom-right"}}let te=null,N=null,ie=!1,se={},ge=!1,xe=!1;function rt(t){return!!(t.inbox||t.inboxStart)}let ne=null;function vn(t,e){const n=!e&&!!t.el;if(ie&&!n&&(N.innerHTML="",N=null,ie=!1),n){const i=typeof t.el=="string"?document.querySelector(t.el):t.el;i instanceof HTMLElement?(N&&N!==i&&!ie&&N.remove(),N=i,ie=!0):console.error(`[Relay] \`el\` ("${String(t.el)}") did not match any element — falling back to an auto-created host.`)}return(!N||!ie&&!N.isConnected)&&(N=document.createElement("div"),N.id="relay-widget-root",document.body.appendChild(N),ie=!1),!e&&t.height&&(N.style.height=t.height,N.style.width||(N.style.width="100%")),N}function Se(t){try{const e=t.launcher??!0;ne==null||ne(),ne=null,te==null||te.close(),te=null;const n=vn(t,e);if(rt(t)&&!e&&ge){kn(t,n);return}te=st(bn(t,n))}catch(e){console.error("[Relay]",e instanceof Error?e.message:e)}}async function kn(t,e){const n=t.profileId??t.appId;if(!n&&!t.tenantId){console.error("[Relay] `inbox` requires `profileId` or `tenantId`.");return}e.innerHTML="";const i=document.createElement("div");i.style.cssText="position:relative;width:100%;height:100%;overflow:hidden;background:#fff";const o=document.createElement("div");o.style.cssText="position:absolute;inset:0";const s=document.createElement("div");s.style.cssText="position:absolute;inset:0;display:none";const r=document.createElement("button");r.type="button",r.setAttribute("aria-label","Close"),r.textContent="✕",r.style.cssText="position:absolute;top:8px;right:8px;z-index:20;width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.05);border:none;color:#1c1b1a;font-size:16px;line-height:1;cursor:pointer",r.onclick=()=>{ge=!1,Se(se)},i.append(o,s);const w=!xe&&!!n;w&&i.append(r),e.appendChild(i);let d=null,u=null;ne=()=>{u==null||u.close(),d==null||d.close(),e.innerHTML=""};let g;try{({mountChatList:g}=await Promise.resolve().then(()=>Ln))}catch(y){console.error("[Relay] could not load the conversation list module.",y),o.isConnected&&(o.style.cssText+=";display:flex;align-items:center;justify-content:center;padding:16px;font:13px system-ui;color:#b91c1c;text-align:center",o.textContent="Could not load conversations.");return}if(!o.isConnected)return;const l=y=>{const U=y.profileId??n;if(!U){console.error("[Relay] conversation row has no chatroom; cannot open it.",y);return}r.style.display="none",u==null||u.close(),u=st({el:s,url:t.url??De,...t.apiUrl?{apiUrl:t.apiUrl}:{},profileId:U,...y.kind==="direct"&&y.peerId?{kind:"direct",peerId:y.peerId}:y.subjectId?{subjectId:y.subjectId}:{},...t.token?{token:t.token}:{},...t.refreshToken?{refreshToken:t.refreshToken}:{},...t.userId?{userId:t.userId}:{},...t.userId||t.userName||t.userEmail||t.userAvatar?{user:{...t.userName?{name:t.userName}:{},...t.userEmail?{email:t.userEmail}:{},...t.userAvatar?{avatar:t.userAvatar}:{}}}:{},...y.subjectTitle?{subject:{title:y.subjectTitle,...y.subjectMeta?{subtitle:y.subjectMeta}:{}}}:{},...t.accent?{accent:t.accent}:{},launcher:!1,onBack:()=>{u==null||u.close(),u=null,s.style.display="none",o.style.display="",r.style.display="",d==null||d.refresh()}}),o.style.display="none",s.style.display=""};d=g({el:o,url:t.url??De,...t.apiUrl?{apiUrl:t.apiUrl}:{},...n?{profileId:n}:{},...t.tenantId?{tenantId:t.tenantId}:{},scope:t.inboxScope??"tenant",...w?{reserveCloseSpace:!0}:{},onSelect:l,onNewChat:()=>{const y=n??(d==null?void 0:d.defaultProfileId());y&&l({id:"__new__",profileId:y,state:"open",updatedAt:Date.now()})},...t.token?{token:t.token}:{},...t.userId?{userId:t.userId}:{},...t.accent?{accent:t.accent}:{}})}function at(t){xe=!!(t.inboxStart&&!(t.launcher??!0)),ge=xe,se={...t},Se(se)}function Sn(t){se={...se,...t},Se(se)}function In(){ne==null||ne(),ne=null,te==null||te.close(),te=null,N&&!ie&&N.remove(),N=null,ie=!1,ge=!1,xe=!1,se={}}function qe(t,e){switch(t){case"boot":at(e??{});break;case"update":case"identify":Sn(e??{});break;case"shutdown":In();break;default:console.warn("[Relay] unknown command:",t)}}function En(){if(typeof document>"u")return null;const t=document.querySelector("script[data-relay-app]")??document.querySelector("script[data-relay-profile-id]")??document.querySelector("script[data-relay-tenant-id]"),e=t==null?void 0:t.dataset,n=(e==null?void 0:e.relayApp)??(e==null?void 0:e.relayProfileId),i=e==null?void 0:e.relayTenantId;if(!n&&!i)return null;const o=n?{profileId:n}:{};i&&(o.tenantId=i),e.relayUser&&(o.userId=e.relayUser),e.relayToken&&(o.token=e.relayToken),e.relayListing&&(o.listingId=e.relayListing),e.relayAccent&&(o.accent=e.relayAccent),e.relayAccent2&&(o.accent2=e.relayAccent2),e.relayTheme&&(o.theme=e.relayTheme),e.relayWebfont==="false"&&(o.webfont=!1),e.relayUrl&&(o.url=e.relayUrl);const s=e.relayPosition;(s==="bottom-left"||s==="bottom-right")&&(o.position=s),e.relayLauncherMessage&&(o.launcherMessage=e.relayLauncherMessage),e.relayLauncherSubtitle&&(o.launcherSubtitle=e.relayLauncherSubtitle),e.relayLauncher==="false"&&(o.launcher=!1),e.relayUserName&&(o.userName=e.relayUserName),e.relayUserEmail&&(o.userEmail=e.relayUserEmail),e.relayUserAvatar&&(o.userAvatar=e.relayUserAvatar),e.relayContextTitle&&(o.contextTitle=e.relayContextTitle),e.relayContextSubtitle&&(o.contextSubtitle=e.relayContextSubtitle),e.relayContextStatus&&(o.contextStatus=e.relayContextStatus),e.relayListingTitle&&(o.listingTitle=e.relayListingTitle),e.relayListingMeta&&(o.listingMeta=e.relayListingMeta),e.relayListingPrice&&(o.listingPrice=Number(e.relayListingPrice)),e.relayListingStatus&&(o.listingStatus=e.relayListingStatus),e.relayTarget&&(o.el=e.relayTarget),e.relayHeight&&(o.height=e.relayHeight),e.relayInbox==="true"&&(o.inbox=!0),e.relayInbox==="false"&&(o.inbox=!1),e.relayInboxStart==="true"&&(o.inboxStart=!0),e.relayInboxStart==="false"&&(o.inboxStart=!1);const r=e.relayInboxScope;return(r==="tenant"||r==="profile")&&(o.inboxScope=r),e.relayTranslateLang&&(o.translateLang=e.relayTranslateLang),o}if(typeof window<"u"){const t=window,e=t.Relay&&t.Relay.q?t.Relay.q:[];t.Relay=qe;let n=!1;for(const i of e){const[o,s]=i;o==="boot"&&(n=!0),qe(o,s)}if(!n){const i=t.relaySettings??En();i&&at(i)}}const Tn=`
193
- .ocl { ${et("ocl")}
192
+ `,nt="objectchat-widget-styles",cn=["👍","❤️","😂","😮","😢","🙏"],ln=400,dn='<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M22 2 11 13M22 2l-7 20-4-9-9-4 20-7z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function hn(){if(typeof document>"u"||document.getElementById(nt))return;const t=document.createElement("style");t.id=nt,t.textContent=an,document.head.appendChild(t)}const it="ocw-webfont";function pn(){if(typeof document>"u"||document.getElementById(it))return;const t=document.createElement("link");t.id=it,t.rel="stylesheet",t.href="https://fonts.googleapis.com/css2?family=Baloo+2:wght@500;600;700&family=Nunito:wght@400;500;600;700&display=swap",document.head.appendChild(t)}function a(t,e,n){const o=document.createElement(t);return e&&(o.className=e),n!==void 0&&(o.textContent=n),o}function un(t){try{return new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function Pe(t){var e;switch(t.kind){case"text":return t.text;case"system":return typeof((e=t.data)==null?void 0:e.message)=="string"?String(t.data.message):t.event;case"card":return[t.title,t.body].filter(Boolean).join(" — ");case"attachment":return t.name??t.url;case"form":return t.prompt;case"appointment":return`📅 ${t.title} — ${new Date(t.startIso).toLocaleString()}`}}class fn{constructor(e,n,o,i={}){c(this,"scroll");c(this,"chips");c(this,"typing");c(this,"quick");c(this,"formHost");c(this,"csatPanel");c(this,"awayNotice");c(this,"headStatus");c(this,"reopenBtn");c(this,"preChatPanel");c(this,"deflectPanel");c(this,"preChatBuilt",!1);c(this,"preChatDone",!1);c(this,"footer");c(this,"input");c(this,"subjectCard");c(this,"e2eBadge");c(this,"statusBadge");c(this,"headerName");c(this,"connStatus");c(this,"typingTimer",null);c(this,"csatSubmitted",!1);c(this,"sendBtn");c(this,"compactObserver",null);c(this,"storeRef",null);c(this,"cfgAccent2");c(this,"scrollCleanup",null);c(this,"translationCache",new Map);c(this,"showingTranslation",new Set);c(this,"subjectBuilt",!1);var R,O,B,J,p,h,C,m,k,T,$;this.root=e,this.me=n,this.h=o,this.cfg=i,hn(),i.webfont!==!1&&pn(),e.replaceChildren(),e.classList.add("ocw"),i.accent&&e.style.setProperty("--ocw-accent",i.accent);const s=i.accent2??i.accent;s&&e.style.setProperty("--ocw-accent2",s),this.cfgAccent2=i.accent2,e.dataset.theme=i.theme??"light";const r=a("div","ocw-head");if(this.h.onBack){const b=a("button","ocw-back","‹");b.type="button",b.setAttribute("aria-label","Back"),b.addEventListener("click",()=>this.h.onBack()),r.append(b)}const w=((R=i.subject)==null?void 0:R.ownerLabel)??((O=i.subject)==null?void 0:O.title)??"",l=a("div","ocw-avatar");w.trim()&&(l.textContent=w.trim()[0].toUpperCase(),r.append(l));const u=a("div","ocw-head-main");this.headerName=a("div","ocw-head-name",((B=i.subject)==null?void 0:B.ownerLabel)??((J=i.subject)==null?void 0:J.title)??""),u.append(this.headerName),this.headStatus=a("div","ocw-head-status"),this.headStatus.style.display="none",u.append(this.headStatus),(p=i.subject)!=null&&p.subtitle&&u.append(a("div","ocw-head-meta",i.subject.subtitle)),r.append(u),this.statusBadge=a("span","ocw-badge",((h=i.subject)==null?void 0:h.status)??""),(C=i.subject)!=null&&C.status||(this.statusBadge.style.display="none"),r.append(this.statusBadge),this.e2eBadge=a("span","ocw-e2e","🔒 E2E"),this.e2eBadge.style.display="none",r.append(this.e2eBadge),this.connStatus=a("span","ocw-conn-status"),this.connStatus.style.display="none",r.append(this.connStatus),r.append(a("button","ocw-menu","⋯")),this.chips=a("div","ocw-chiprow"),this.scroll=a("div","ocw-scroll"),this.subjectCard=a("div","ocw-subject"),this.typing=a("div","ocw-typing");const x=a("div","ocw-typing-bubble");x.append(a("div","ocw-typing-dot"),a("div","ocw-typing-dot"),a("div","ocw-typing-dot")),this.typing.append(x),this.quick=a("div","ocw-quick");for(const b of i.quickReplies??[]){const S=a("button",void 0,b);S.addEventListener("click",()=>{this.h.onSend(b),this.quick.style.display="none"}),this.quick.append(S)}this.formHost=a("div","ocw-form-host"),this.csatPanel=a("div","ocw-csat"),this.csatPanel.style.display="none",this.awayNotice=a("div","ocw-away"),this.awayNotice.style.display="none",this.preChatPanel=a("div","ocw-prechat"),this.preChatPanel.style.display="none",this.deflectPanel=a("div","ocw-deflect"),this.deflectPanel.style.display="none",this.input=a("textarea",void 0),this.input.rows=1,this.input.placeholder=((m=i.i18n)==null?void 0:m.placeholder)??"Message…";const d=a("button","ocw-sendbtn");d.type="button";const g=(k=i.i18n)==null?void 0:k.send;g?(d.textContent=g,d.classList.add("ocw-sendbtn-label"),d.setAttribute("aria-label",g)):(d.innerHTML=dn,d.setAttribute("aria-label","Send message")),d.disabled=!0,this.sendBtn=d,d.addEventListener("click",()=>this.flushSend()),this.input.addEventListener("input",()=>{var b,S;this.sendBtn.disabled=this.input.value.trim().length===0,this.autoGrowInput(),this.storeRef&&!this.storeRef.messages().some(N=>N.senderRole==="guest")?(S=(b=this.h).onDeflectQuery)==null||S.call(b,this.input.value):this.hideDeflection()}),this.input.addEventListener("keydown",b=>{b.isComposing||b.keyCode===229||(b.key==="Enter"&&!b.shiftKey?(b.preventDefault(),this.flushSend()):this.signalTyping())});const U=a("button","ocw-attach","📎");U.title="Attach image or file";const E=document.createElement("input");E.type="file",E.accept="image/*,.pdf,.txt,.doc,.docx",E.style.display="none",U.addEventListener("click",()=>E.click()),E.addEventListener("change",()=>{var b;(b=E.files)!=null&&b[0]&&this.h.onAttach&&this.h.onAttach(E.files[0]),E.value=""});const _=a("div","ocw-input");_.append(U,E,this.input,d);const z=a("div","ocw-footer");((T=i.i18n)==null?void 0:T.poweredBy)!==void 0?z.textContent=i.i18n.poweredBy:z.innerHTML='Powered by <a href="https://relay.paramms.com" target="_blank" rel="noopener">Relay</a>',this.footer=z,this.reopenBtn=a("button","ocw-reopen",(($=this.cfg.i18n)==null?void 0:$.reopen)??"Reopen conversation"),this.reopenBtn.type="button",this.reopenBtn.addEventListener("click",()=>{this.reopenBtn.style.display="none";const b=this.root.querySelector(".ocw-input textarea");b==null||b.focus()}),e.append(r,this.chips,this.scroll,this.typing,this.quick,this.formHost,this.csatPanel,this.preChatPanel,this.deflectPanel,this.awayNotice,_,this.reopenBtn,this.footer);const M=b=>{e.classList.toggle("ocw-compact",b>0&&b<ln)};M(e.clientWidth),typeof ResizeObserver<"u"&&(this.compactObserver=new ResizeObserver(b=>{var N;const S=((N=b[0])==null?void 0:N.contentRect.width)??e.clientWidth;M(S)}),this.compactObserver.observe(e))}getScrollEl(){return this.scroll}setScrollCleanup(e){var n;(n=this.scrollCleanup)==null||n.call(this),this.scrollCleanup=e}destroy(){var e,n;(e=this.scrollCleanup)==null||e.call(this),this.scrollCleanup=null,this.typingTimer&&(clearTimeout(this.typingTimer),this.typingTimer=null),(n=this.compactObserver)==null||n.disconnect(),this.compactObserver=null}flushSend(){this.hideDeflection();const e=this.input.value.trim();e&&(this.input.value="",this.sendBtn.disabled=!0,this.autoGrowInput(),this.h.onTyping(!1),this.h.onSend(e))}autoGrowInput(){this.input.style.height="auto";const e=this.input.scrollHeight;e>0?this.input.style.height=`${Math.min(e,120)}px`:this.input.style.removeProperty("height")}signalTyping(){const e=this.input.value.trim().slice(0,100)||void 0;this.h.onTyping(!0,e),this.typingTimer&&clearTimeout(this.typingTimer),this.typingTimer=setTimeout(()=>this.h.onTyping(!1),2e3)}setBotName(e){this.cfg.i18n={...this.cfg.i18n??{},aiAssistant:e}}render(e){var E,_,z,M,R,O,B,J;if(this.storeRef=e,e.accent&&(this.root.style.setProperty("--ocw-accent",e.accent),this.root.style.setProperty("--ocw-accent2",this.cfgAccent2??e.accent)),this.e2eBadge.style.display=e.e2e?"inline-flex":"none",this.buildSubjectCard(e),e.subject){const p=(E=this.cfg.subject)==null?void 0:E.ownerLabel;p&&(this.headerName.textContent=p)}this.quick.style.display=e.messages().length===0?"flex":"none",this.chips.replaceChildren();const n=e.visibleActions();this.chips.style.display=n.length?"flex":"none";for(const p of n)this.chips.append(this.chipEl(p));const o=this.scroll.scrollHeight,i=this.scroll.scrollTop;if(this.scroll.replaceChildren(),this.subjectCard.childNodes.length&&this.scroll.append(this.subjectCard),e.hasMoreHistory){const p=a("div","ocw-load-more");p.textContent="↑ Loading earlier messages…",p.style.pointerEvents="none",this.scroll.append(p)}let s=0,r=null;const w=[...e.messages()];for(let p=0;p<w.length;p++){const h=w[p],C=h.senderRole!=="system"&&h.senderId!==this.me&&!h.internal&&h.senderId!==r;this.scroll.append(this.messageEl(h,e,C,p===w.length-1)),h.senderRole!=="system"&&(r=h.senderId),h.senderId!==this.me&&h.seq>s&&(s=h.seq)}i>20?this.scroll.scrollTop=this.scroll.scrollHeight-o+i:this.scroll.scrollTop=this.scroll.scrollHeight,s>0&&this.h.onReadUpTo(s);const l=[...e.typing];this.typing.classList.toggle("active",l.length>0);const u=this.typing.querySelector(".ocw-typing-bubble");u&&u.setAttribute("aria-label",l.length?"typing":""),this.footer.style.display=e.whiteLabel?"none":"block";const x=e.messages().some(p=>p.senderRole==="guest");if(!!((_=e.preChat)!=null&&_.enabled)&&!this.preChatDone&&!x&&(e.preChat.showWhen!=="offline"||e.offline))this.preChatBuilt||this.buildPreChatPanel(e.preChat),this.preChatPanel.style.display="block",this.awayNotice.style.display="none",(z=this.root.querySelector(".ocw-input"))==null||z.style.setProperty("display","none");else{if(this.preChatPanel.style.display="none",e.offline){this.awayNotice.firstChild||this.awayNotice.append(a("span","ocw-away-icon","🌙"),a("span","",""));const p=this.awayNotice.lastChild;p.textContent=e.offlineMessage||((M=this.cfg.i18n)==null?void 0:M.offline)||"We're away right now — send your message and we'll reply as soon as we're back.",this.awayNotice.style.display="flex"}else this.awayNotice.style.display="none";(R=this.root.querySelector(".ocw-input"))==null||R.style.removeProperty("display")}const g=["resolved","closed","sold","issued","checked_out"];this.h.onCsat&&!this.csatSubmitted&&g.includes(e.state)&&e.messages().length>0&&(this.csatPanel.style.display==="none"&&this.buildCsatPanel(),this.csatPanel.style.display="block");const U=g.includes(e.state);if(e.offline?(this.headStatus.textContent=`● ${e.offlineMessage||((O=this.cfg.i18n)==null?void 0:O.away)||"Away"}`,this.headStatus.className="ocw-head-status away",this.headStatus.style.display=""):e.conversationId?(this.headStatus.textContent=`● ${((B=this.cfg.i18n)==null?void 0:B.online)??"Online"}`,this.headStatus.className="ocw-head-status online",this.headStatus.style.display=""):this.headStatus.style.display="none",U&&e.messages().length>0){const p=a("div","ocw-resolved-note",`— ${((J=this.cfg.i18n)==null?void 0:J.resolved)??"Marked as resolved"} —`);this.scroll.append(p),this.reopenBtn.style.display="block"}else this.reopenBtn.style.display="none"}setConnStatus(e,n){if(e==="open"){this.connStatus.style.display="none";return}this.connStatus.style.display="";const o=e==="error";this.connStatus.className=`ocw-conn-status${o?" err":e==="reconnecting"?" warn":""}`,this.connStatus.textContent=o?`⚠ ${n??"Chat unavailable"}`:e==="reconnecting"?n??"↻ reconnecting…":"● connecting…"}buildPreChatPanel(e){var l;this.preChatBuilt=!0,this.preChatPanel.replaceChildren(),this.preChatPanel.append(a("div","ocw-prechat-title",e.title??"Before we start…"));const n=a("div","ocw-offline-form"),o={};for(const u of e.fields??["name","email"]){const x=a("input","ocw-offline-input");x.type=u==="email"?"email":u==="phone"?"tel":"text",x.placeholder=u==="name"?"Your name":u==="email"?"Your email":"Your phone number",o[u]=x,n.append(x)}let i=null;if((l=e.topics)!=null&&l.length){i=a("select",void 0);const u=document.createElement("option");u.value="",u.textContent="What is this about?",i.append(u);for(const x of e.topics){const d=document.createElement("option");d.value=x,d.textContent=x,i.append(d)}n.append(i)}let s=null,r=null;if(e.callbackOption){const u=a("label","ocw-prechat-cb");s=document.createElement("input"),s.type="checkbox",u.append(s,document.createTextNode("📞 Request a call back")),n.append(u),o.phone||(r=a("input","ocw-offline-input"),r.type="tel",r.placeholder="Phone number for the call",r.style.display="none",s.addEventListener("change",()=>r.style.setProperty("display",s.checked?"block":"none")),n.append(r))}const w=a("button","ocw-offline-submit","Start chat");w.type="button",w.addEventListener("click",()=>{var g,U,E,_,z,M,R;const u=(g=o.email)==null?void 0:g.value.trim();if(o.email&&(!u||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(u))){o.email.focus();return}const x=!!(s!=null&&s.checked),d=(((U=o.phone)==null?void 0:U.value)??(r==null?void 0:r.value)??"").trim();if(x&&!d){(E=o.phone??r)==null||E.focus();return}if(i&&((_=e.topics)!=null&&_.length)&&!i.value){i.focus();return}w.disabled=!0,this.completePreChat(),(R=(M=this.h).onPreChat)==null||R.call(M,{...(z=o.name)!=null&&z.value.trim()?{name:o.name.value.trim()}:{},...u?{email:u}:{},...d?{phone:d}:{},...i!=null&&i.value?{topic:i.value}:{},...x?{callback:!0}:{}})}),n.append(w),this.preChatPanel.append(n)}completePreChat(){this.preChatDone=!0,this.preChatPanel.style.display="none",this.storeRef&&this.render(this.storeRef)}showDeflection(e){if(!e.length)return this.hideDeflection();this.deflectPanel.replaceChildren(),this.deflectPanel.append(a("div","ocw-deflect-hint","Instant answers — tap to expand"));for(const n of e.slice(0,3)){const o=a("button","ocw-deflect-card");o.append(a("div","ocw-deflect-q",n.title),a("div","ocw-deflect-a",n.answer)),o.addEventListener("click",()=>o.classList.toggle("open")),this.deflectPanel.append(o)}this.deflectPanel.style.display="flex"}hideDeflection(){this.deflectPanel.style.display="none",this.deflectPanel.replaceChildren()}buildCsatPanel(){this.csatPanel.replaceChildren(),this.csatPanel.append(a("div","ocw-csat-title","How did we do?"));const e=a("div","ocw-csat-stars"),n=[];for(let o=1;o<=5;o++){const i=a("button","ocw-csat-star","★");i.dataset.score=String(o),i.addEventListener("mouseenter",()=>n.forEach((s,r)=>s.classList.toggle("lit",r<o))),i.addEventListener("mouseleave",()=>n.forEach(s=>s.classList.remove("lit"))),i.addEventListener("click",()=>{var s,r;this.csatSubmitted=!0,this.csatPanel.replaceChildren(a("div","ocw-csat-done",`Thanks for your ${o}★ rating!`)),(r=(s=this.h).onCsat)==null||r.call(s,o)}),n.push(i),e.append(i)}this.csatPanel.append(e)}buildSubjectCard(e){if(this.subjectBuilt)return;const n=e.subject,o=this.cfg.subject,i=(n==null?void 0:n.title)??(o==null?void 0:o.title);if(!i)return;this.subjectBuilt=!0,this.subjectCard.replaceChildren(),this.subjectCard.append(a("div","ocw-subject-title",i)),o!=null&&o.subtitle&&this.subjectCard.append(a("div","ocw-subject-sub",o.subtitle));const s=a("div","ocw-tags");if(n)for(const[w,l]of Object.entries(n.fields))s.append(a("span","ocw-tag",`${w}: ${l}`));else for(const w of(o==null?void 0:o.tags)??[])s.append(a("span","ocw-tag",w));s.childNodes.length&&this.subjectCard.append(s);const r=(n==null?void 0:n.state)??(o==null?void 0:o.status);r&&(this.statusBadge.textContent=r,this.statusBadge.style.display="inline-flex")}chipEl(e){const n=a("button","ocw-chip",e.icon?`${e.icon} ${e.label}`:e.label);return n.dataset.actionId=e.id,n.addEventListener("click",async()=>{var o;e.confirm&&!await this.confirm(e.label)||((o=e.input)!=null&&o.length?this.openForm(e):this.h.onInvoke(e.id))}),n}confirm(e){return new Promise(n=>{const o=a("div","ocw-modal"),i=a("div","ocw-modal-card");i.append(a("div","ocw-modal-title",e)),i.append(a("div","ocw-modal-body",`Confirm “${e}”?`));const s=a("div","ocw-modal-actions"),r=a("button","ocw-modal-cancel","Cancel"),w=a("button","ocw-modal-ok","Confirm"),l=u=>{o.remove(),n(u)};r.addEventListener("click",()=>l(!1)),w.addEventListener("click",()=>l(!0)),o.addEventListener("click",u=>{u.target===o&&l(!1)}),s.append(r,w),i.append(s),o.append(i),this.root.append(o),w.focus()})}openForm(e){var w,l;this.formHost.replaceChildren();const n=a("div","ocw-form");n.append(a("div","ocw-form-title",e.icon?`${e.icon} ${e.label}`:e.label));const o=new Map;for(const u of e.input??[]){const x=a("label","ocw-form-row");if(x.append(a("span","ocw-form-lbl",u.label)),u.type==="select"&&((w=u.options)!=null&&w.length)){const d=a("select","ocw-form-input");u.required||d.append(a("option",void 0,"— select —"));for(const g of u.options){const U=a("option");U.value=g,U.textContent=g,d.append(U)}u.required&&(d.required=!0),x.append(d),o.set(u.name,d)}else{const d=a("input","ocw-form-input");d.type=u.type==="number"?"number":u.type==="date"?"datetime-local":"text",u.required&&(d.required=!0),x.append(d),o.set(u.name,d)}n.append(x)}const i=a("div","ocw-form-actions"),s=a("button","ocw-form-cancel","Cancel"),r=a("button","ocw-form-submit","Send");s.addEventListener("click",()=>this.formHost.replaceChildren()),r.addEventListener("click",()=>{const u={};for(const[x,d]of o){if(d.required&&!d.value){d.style.borderColor="#e5484d";return}u[x]=d.type==="number"?Number(d.value):d.value}this.formHost.replaceChildren(),this.h.onInvoke(e.id,u)}),i.append(s,r),n.append(i),this.formHost.append(n),(l=o.values().next().value)==null||l.focus()}messageEl(e,n,o=!1,i=!1){var U,E,_,z,M,R,O,B,J;if(e.senderRole==="system"){const p=a("div","ocw-sys");return p.textContent=e.deletedAt?"message deleted":Pe(e.content),p}const s=e.senderId===this.me,r=!!e.internal,w=a("div",`ocw-row ${r?"ocw-note mine":s?"mine":"theirs"} ${e.senderRole==="bot"?"ocw-bot":""}`),l=a("div");if(o){const p=e.senderRole==="bot"?((U=this.cfg.i18n)==null?void 0:U.aiAssistant)??"AI Assistant":((E=this.cfg.subject)==null?void 0:E.ownerLabel)??((_=this.cfg.subject)==null?void 0:_.title)??"Support";l.append(a("div","ocw-msg-sender",p))}const u=a("div","ocw-bubble-wrap");if(e.replyToId){const p=a("div","ocw-reply-to","↩ replying to a message");p.style.cssText="font-size:11px;color:var(--ocw-mut);margin-bottom:2px;font-style:italic",l.append(p)}const x=a("div","ocw-bubble");let d=null;if(e.deletedAt)x.append(a("span","ocw-deleted","message deleted"));else if(e.content.kind==="attachment"){const p=e.content;if((z=p.mime)!=null&&z.startsWith("image/")){const h=document.createElement("img");h.src=p.url,h.alt=p.name??"image",h.style.cssText="max-width:220px;max-height:160px;border-radius:10px;display:block;cursor:pointer",h.addEventListener("click",()=>window.open(p.url,"_blank")),x.append(h)}else if((M=p.mime)!=null&&M.startsWith("video/")){const h=document.createElement("video");h.src=p.url,h.controls=!0,h.style.cssText="max-width:240px;max-height:180px;border-radius:10px;display:block",x.append(h)}else{const h=document.createElement("a");h.href=p.url,h.target="_blank",h.rel="noopener",h.style.cssText="display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none",h.append(a("span",void 0,"📄"),a("span",void 0,p.name??"file")),x.append(h)}}else if(e.content.kind==="appointment"){const p=e.content,h=a("div","ocw-appt");h.append(a("div","ocw-appt-title",`📅 ${p.title}`)),h.append(a("div","ocw-appt-time",new Date(p.startIso).toLocaleString()+" – "+new Date(p.endIso).toLocaleTimeString())),p.location&&h.append(a("div","ocw-appt-loc",`📍 ${p.location}`)),p.description&&h.append(a("div","ocw-appt-desc",p.description));const C=a("div","ocw-appt-links"),m=document.createElement("a");m.href=p.googleUrl,m.target="_blank",m.rel="noopener",m.className="ocw-appt-btn",m.textContent="📅 Add to Google Calendar";const k=document.createElement("a");k.href=p.icalUrl,k.download=`${p.title}.ics`,k.className="ocw-appt-btn ocw-appt-btn-sec",k.textContent="🍎 Apple / iCal",C.append(m,k),h.append(C),x.append(h)}else d=document.createTextNode(Pe(e.content)),x.append(d),e.editedAt&&x.append(a("span","ocw-edited","(edited)"));if(u.append(x),i&&!e.deletedAt&&e.content.kind==="text"&&((R=e.content.quickReplies)!=null&&R.length)){const p=a("div","ocw-flow-choices");p.style.cssText="display:flex;flex-wrap:wrap;gap:6px;margin-top:6px";for(const h of e.content.quickReplies){const C=a("button","ocw-flow-choice",h);C.type="button",C.style.cssText="border:1px solid var(--ocw-bd,rgba(0,0,0,.12));background:var(--ocw-bg,#fff);color:inherit;border-radius:14px;padding:5px 12px;font:inherit;font-size:13px;cursor:pointer",C.addEventListener("click",()=>{p.querySelectorAll("button").forEach(m=>m.disabled=!0),p.style.opacity="0.5",this.h.onSend(h)}),p.append(C)}u.append(p)}if(!s&&!r&&this.h.onTranslate&&e.content.kind==="text"&&!e.deletedAt&&e.seq>0&&d){const p=e.content.text;if(p.trim()){const h=a("button","ocw-translate-btn","🌐");h.type="button",h.title="Translate";const C=a("div","ocw-translation");C.style.display="none",x.append(C);const m=$=>{C.textContent=$,C.style.display="",this.showingTranslation.add(e.id),h.textContent="↩",h.title="Show original"},k=()=>{C.style.display="none",this.showingTranslation.delete(e.id),h.textContent="🌐",h.title="Translate"};h.addEventListener("click",$=>{if($.stopPropagation(),this.showingTranslation.has(e.id)){k();return}const b=this.translationCache.get(e.id);if(b!==void 0){m(b);return}h.textContent="⏳",this.h.onTranslate(p).then(S=>{if(S===null){h.textContent="⚠️",h.title="Translation unavailable",setTimeout(()=>{h.textContent="🌐",h.title="Translate"},1500);return}this.translationCache.set(e.id,S),m(S)})}),u.append(h);const T=this.translationCache.get(e.id);this.showingTranslation.has(e.id)&&T!==void 0&&m(T)}}if(s&&!e.deletedAt&&e.seq>0&&(this.h.onEdit??this.h.onDelete)){const p=a("div","ocw-msg-menu");if(this.h.onEdit){const h=a("button",void 0,"✏️");h.title="Edit",h.addEventListener("click",C=>{C.stopPropagation();const m=Pe(e.content),k=document.createElement("textarea");k.value=m,k.rows=Math.min(4,Math.ceil(m.length/40)+1),k.style.cssText="width:100%;resize:vertical;border:1px solid var(--ocw-accent);border-radius:8px;padding:6px 10px;font:inherit;font-size:14px;background:var(--ocw-card);color:#1c1b1a;box-sizing:border-box";const T=a("button","ocw-form-submit","Save");T.style.cssText="margin-top:6px;padding:5px 14px;font-size:13px";const $=a("button","ocw-form-cancel","Cancel");$.style.cssText="margin-top:6px;padding:5px 10px;font-size:13px";const b=a("div");b.style.cssText="display:flex;gap:6px;justify-content:flex-end",b.append($,T);const S=a("div");S.append(k,b),x.replaceChildren(S),k.focus(),k.select();const N=()=>x.replaceChildren(d??document.createTextNode(m));$.addEventListener("click",N),T.addEventListener("click",()=>{const F=k.value.trim();F&&F!==m&&this.h.onEdit(e.id,F),N()}),k.addEventListener("keydown",F=>{F.key==="Enter"&&!F.shiftKey&&(F.preventDefault(),T.click()),F.key==="Escape"&&N()})}),p.append(h)}if(this.h.onDelete){const h=a("button","del","🗑");h.title="Delete",h.addEventListener("click",C=>{C.stopPropagation(),this.h.onDelete(e.id)}),p.append(h)}u.append(p)}if(l.append(u),e.senderRole==="bot"&&!e.deletedAt&&e.seq>0&&e.content.kind==="text"){const p=e.content.citations;if(p!=null&&p.length){const h=a("div","ocw-cites");h.style.cssText="margin-top:4px;font-size:11px;color:var(--ocw-mut,#667)",h.textContent=`${((O=this.cfg.i18n)==null?void 0:O.sources)??"Sources"}: ${p.map(C=>C.source).join(", ")}`,l.append(h)}if(this.h.onReact){const h=a("div","ocw-bot-feedback");h.style.cssText="display:flex;gap:6px;margin-top:4px";const C=(m,k)=>{const T=a("button","ocw-fb-btn",m);T.type="button",T.title=k,T.style.cssText="border:1px solid var(--ocw-bd,rgba(0,0,0,.12));background:transparent;border-radius:12px;padding:1px 8px;font-size:12px;cursor:pointer;opacity:.7";const $=()=>{var b,S;return!!((S=(b=e.reactions)==null?void 0:b[m])!=null&&S.includes(this.me))};return $()&&(T.style.opacity="1"),T.addEventListener("click",()=>{var b,S;(S=(b=this.h).onReact)==null||S.call(b,e.id,m,$()),T.style.opacity="1"}),T};h.append(C("👍",((B=this.cfg.i18n)==null?void 0:B.helpful)??"Helpful"),C("👎",((J=this.cfg.i18n)==null?void 0:J.notHelpful)??"Not helpful")),l.append(h)}}if(this.h.onReact&&!e.deletedAt&&e.seq>0){const p=a("div","ocw-react-wrap"),h=a("div","ocw-react");if(e.reactions&&Object.keys(e.reactions).length)for(const[k,T]of Object.entries(e.reactions)){const $=a("button",`ocw-react-pill${T.includes(this.me)?" mine":""}`,`${k} ${T.length}`);$.addEventListener("click",()=>{var b,S;return(S=(b=this.h).onReact)==null?void 0:S.call(b,e.id,k,T.includes(this.me))}),h.append($)}const C=a("button","ocw-react-btn","+"),m=a("div","ocw-react-picker");for(const k of cn){const T=a("button",void 0,k);T.addEventListener("click",$=>{var S,N,F,Q;$.stopPropagation();const b=(N=(S=e.reactions)==null?void 0:S[k])==null?void 0:N.includes(this.me);(Q=(F=this.h).onReact)==null||Q.call(F,e.id,k,!!b),m.style.display="none"}),m.append(T)}m.style.display="none",C.addEventListener("click",k=>{k.stopPropagation();const T=m.style.display==="none";m.style.display=T?"flex":"none",T&&document.addEventListener("click",()=>{m.style.display="none"},{once:!0})}),h.append(C),p.append(h,m),l.append(p)}else e.reactions&&Object.keys(e.reactions).length&&l.append(a("div","ocw-react",Object.entries(e.reactions).map(([p,h])=>`${p}${h.length}`).join(" ")));const g=a("div","ocw-time ocw-meta",un(e.ts));if(s&&e.status){const p=a("span",`ocw-tick${e.status==="read"?" read":e.status==="delivered"?" delivered":""}`,wn(e.status));g.append(p)}return s&&e.seq>0&&n.lastReadByOthers>=e.seq&&g.append(a("span","ocw-seen"," · Seen")),l.append(g),w.append(l),w}}function wn(t){switch(t){case"read":return"✓✓";case"delivered":return"✓✓";case"sent":return"✓";default:return"🕓"}}const xn=20;function _e(t,e){var l;const n=t.trim().replace(/\/+$/,""),o=(l=n.match(/^(https|http|wss|ws):\/\//))==null?void 0:l[1],i=o?o==="https"||o==="wss":!0,s=(o?n.slice(o.length+3):n).replace(/\/ws$/,""),r=e?e.trim().replace(/\/+$/,""):`${i?"https":"http"}://${s}`;return{wsUrl:`${i?"wss":"ws"}://${s}/ws`,httpBase:r}}function gn(t){return _e(t).httpBase}function yn(t,e,n,o){const i=`beforeSeq=${n}&limit=${o}`;return[`${t}/conversations/${e}/messages?${i}`,`${t}/conversations/${e}/history?${i}`]}async function ot(t,e,n,o,i=xn){let s,r=!1;for(const w of yn(t,e,o,i))try{const l=await fetch(w,{headers:{authorization:`Bearer ${n}`}});if(r=!0,!l.ok)continue;const u=await l.json();return{messages:u.messages??[],hasMore:u.hasMore??!1}}catch(l){s=l}return r?console.error(`[chat-widget] history request to ${t} was rejected for conversation ${e}.`):console.error(`[chat-widget] could not load history from ${t} — the request never reached the server. This is almost always CORS: add this site's origin to the chatroom's allowed origins (dashboard → chatroom → allowed origins) or to the server's CORS_ORIGINS.`,s),null}async function mn(t,e,n,o,i,s){const r=s?s.replace(/\/+$/,""):gn(t),w=await ot(r,n,e,Number.MAX_SAFE_INTEGER);if(!w||(w.messages.length?(o.apply({type:"sync",conversationId:n,messages:w.messages}),o.apply({type:"history",conversationId:n,messages:[],hasMore:w.hasMore}),i.render(o)):o.apply({type:"history",conversationId:n,messages:[],hasMore:!1}),!w.hasMore))return;let l=!1;const u=async()=>{if(l||!o.hasMoreHistory)return;l=!0;const U=o.messages()[0];if(!U){l=!1;return}const E=await ot(r,n,e,U.seq);E&&(o.apply({type:"history",conversationId:n,messages:E.messages,hasMore:E.hasMore}),i.render(o)),l=!1},x=i.getScrollEl();if(!x)return;let d=!1;setTimeout(()=>{d=!0},300);const g=()=>{d&&x.scrollTop<80&&o.hasMoreHistory&&!l&&u()};x.addEventListener("scroll",g,{passive:!0}),i.setScrollCleanup(()=>x.removeEventListener("scroll",g))}const bn=`
193
+ .ocl { ${tt("ocl")}
194
194
  display:flex; flex-direction:column; height:100%; background:var(--ocl-bg);
195
195
  font-family:var(--ocl-fb); color:var(--ocl-ink); overflow:hidden; }
196
196
  @media (prefers-color-scheme: dark) { .ocl[data-theme="auto"] { ${ve("ocl")} } }
@@ -237,5 +237,5 @@ var RelayEmbedLite=function(ee){"use strict";var Mn=Object.defineProperty;var $n
237
237
  .ocl-compact .ocl-search { font-size:16px; }
238
238
  .ocl-compact .ocl-compose { width:36px; height:36px; }
239
239
  .ocl-row:focus-visible, .ocl button:focus-visible, .ocl input:focus-visible { outline:2px solid var(--ocl-accent); outline-offset:2px; border-radius:12px; }
240
- `;function Cn(t){switch(t){case"open":return{label:"Open",cls:"open"};case"awaiting_staff":return{label:"Waiting on you",cls:"waiting"};case"resolved":return{label:"Resolved",cls:"done"};case"closed":return{label:"Closed",cls:"done"};default:return null}}function Un(t){const e=Math.floor((Date.now()-t)/1e3);if(e<60)return"just now";if(e<3600)return`${Math.floor(e/60)}m`;if(e<86400)return`${Math.floor(e/3600)}h`;const n=Math.floor(e/86400);if(n<=7)return`${n}d`;try{return new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric"})}catch{return`${n}d`}}function A(t,e,n){const i=document.createElement(t);return e&&(i.className=e),n!==void 0&&(i.textContent=n),i}function Bn(t){const e=t.token??t.userId??He(),{httpBase:n,wsUrl:i}=_e(t.url,t.apiUrl),o=t.i18n??{},s=t.accent??"#6c5ce7";if(!document.getElementById("ocl-styles")){const v=document.createElement("style");v.id="ocl-styles",v.textContent=Tn,document.head.append(v)}if(t.webfont!==!1&&typeof document<"u"&&!document.getElementById("ocw-webfont")){const v=document.createElement("link");v.id="ocw-webfont",v.rel="stylesheet",v.href="https://fonts.googleapis.com/css2?family=Baloo+2:wght@500;600;700&family=Nunito:wght@400;500;600;700&display=swap",document.head.append(v)}const r=A("div","ocl");r.style.setProperty("--ocl-accent",s),r.dataset.theme=t.theme??"light",t.reserveCloseSpace&&r.classList.add("ocl-has-close");const w=A("div","ocl-head"),d=o.title??"Your conversations",u=A("span","ocl-title",d);if(u.setAttribute("aria-label",d),w.append(u),t.onNewChat){const v=A("button","ocl-compose","✎");v.title=o.newChat??"New conversation",v.addEventListener("click",()=>t.onNewChat()),w.append(v)}const g=A("div","ocl-search-wrap"),l=A("input","ocl-search");l.placeholder=o.search??"🔍 Search",l.type="search",g.append(l);const y=A("div","ocl-body");y.append(A("div","ocl-spinner","Loading…")),r.append(w,g,y),t.el.replaceChildren(r);const U=v=>{r.classList.toggle("ocl-compact",v>0&&v<400)};U(r.clientWidth);let T=null;if(typeof ResizeObserver<"u"&&(T=new ResizeObserver(v=>{var P;return U(((P=v[0])==null?void 0:P.contentRect.width)??r.clientWidth)}),T.observe(r)),!t.profileId&&!t.tenantId)throw new Error("[relay chatlist] provide profileId or tenantId");let _;const z=`ocl_seen_${t.profileId??`t_${t.tenantId}`}_${(t.userId??e).slice(-8)}`;let M={};try{M=JSON.parse(localStorage.getItem(z)??"{}")}catch{}const R=()=>{try{localStorage.setItem(z,JSON.stringify(M))}catch{}};let O=[],B=!1;const J=async()=>{const v=t.profileId?`profileId=${encodeURIComponent(t.profileId)}${t.scope==="tenant"?"&scope=tenant":""}`:`tenantId=${encodeURIComponent(t.tenantId)}`,P=`${n}/conversations/mine?${v}`,H={authorization:`Bearer ${e}`};let G;try{G=await fetch(P,{headers:H})}catch{G=await fetch(P,{headers:H})}if(!G.ok)return[];const K=await G.json();return K.defaultProfileId&&(_=K.defaultProfileId),(K.conversations??[]).sort((Z,L)=>L.updatedAt-Z.updatedAt)},p=(v,P)=>{if(B)return;const H=P?v.filter(L=>h(L).toLowerCase().includes(P)||(L.lastMessage??"").toLowerCase().includes(P)):v;if(y.replaceChildren(),!H.length){const L=A("div","ocl-empty",P?"No results.":o.empty??"No conversations yet.");if(!P&&t.onNewChat){L.append(A("br"));const ae=A("button","ocl-start",o.newChat??"Start a conversation");ae.addEventListener("click",()=>t.onNewChat()),L.append(ae)}y.append(L);return}const G=L=>(L.lastSeq??0)>(M[L.id]??0),K=H.filter(G),Z=H.filter(L=>!G(L));if(K.length){y.append(A("div","ocl-section",`${o.unread??"Unread"} (${K.length})`));for(const L of K)y.append(C(L,G(L)))}if(Z.length){y.append(A("div","ocl-section",K.length?o.all??"All conversations":""));for(const L of Z)y.append(C(L,!1))}},h=v=>v.subjectTitle??(v.kind==="direct"?v.peerId??"Direct message":"General enquiry"),C=(v,P)=>{var W;const H=h(v),G=(((W=H.match(new RegExp("\\p{L}","u")))==null?void 0:W[0])??H.trim()[0]??"?").toUpperCase(),K=v.lastSeq??0,Z=P?Math.max(1,K-(M[v.id]??0)):0,L=A("button",`ocl-row${P?" unread":""}`),ae=A("div","ocl-av",G);L.append(ae);const le=A("div","ocl-info");le.append(A("div","ocl-name",H));const f={open:"Open",awaiting_staff:"Waiting for reply…",resolved:"Resolved ✓",closed:"Closed"};le.append(A("div","ocl-preview",v.lastMessage??f[v.state]??v.state)),L.append(le);const x=A("div","ocl-right");x.append(A("div","ocl-time",Un(v.updatedAt)));const I=Cn(v.state);return I&&x.append(A("div",`ocl-status ${I.cls}`,I.label)),Z>0&&x.append(A("div","ocl-badge",String(Z>99?"99+":Z))),L.append(x),L.addEventListener("click",()=>{var re;K>0&&(M[v.id]=K,R()),L.classList.remove("unread"),(re=x.querySelector(".ocl-badge"))==null||re.remove(),t.onSelect(v)}),L},m=()=>{B||J().then(v=>{B||(O=v,p(v,l.value.trim().toLowerCase()))}).catch(v=>{if(B)return;console.error(`[chat-widget] failed to load conversations from ${n}/conversations/mine — check the apiUrl/CORS config.`,v);const P=A("div","ocl-empty",o.error??"Could not load conversations.");P.append(A("br"));const H=A("button","ocl-retry",o.retry??"Retry");H.addEventListener("click",()=>{y.replaceChildren(A("div","ocl-spinner","Loading…")),m()}),P.append(H),y.replaceChildren(P)})};l.addEventListener("input",()=>p(O,l.value.trim().toLowerCase())),m();let k=null,E,$,b=0,S=!1;const j=()=>{$||($=setTimeout(()=>{$=void 0,m()},300))},F=()=>{if(!B){try{k=new WebSocket(i)}catch{Q();return}k.binaryType="arraybuffer",k.onopen=()=>{b=0,k.send(Re({type:"auth",token:e})),k.send(Re({type:"subscribe_inbox"})),S&&j(),S=!0},k.onmessage=v=>{const P=Xe(new Uint8Array(v.data));P&&P.type==="inbox_event"&&j()},k.onclose=()=>{k=null,Q()},k.onerror=()=>{try{k==null||k.close()}catch{}}}},Q=()=>{if(B||E)return;const v=Math.min(15e3,500*2**b++)+Math.random()*250;E=setTimeout(()=>{E=void 0,F()},v)};return F(),{refresh:m,close(){B=!0,E&&clearTimeout(E),$&&clearTimeout($),T==null||T.disconnect(),T=null;try{k==null||k.close()}catch{}k=null,t.el.replaceChildren()},defaultProfileId(){return t.profileId??_}}}const Ln=Object.freeze(Object.defineProperty({__proto__:null,mountChatList:Bn},Symbol.toStringTag,{value:"Module"}));return ee.Relay=qe,Object.defineProperty(ee,Symbol.toStringTag,{value:"Module"}),ee}({});
240
+ `;function vn(t){switch(t){case"open":return{label:"Open",cls:"open"};case"awaiting_staff":return{label:"Waiting on you",cls:"waiting"};case"resolved":return{label:"Resolved",cls:"done"};case"closed":return{label:"Closed",cls:"done"};default:return null}}function kn(t){const e=Math.floor((Date.now()-t)/1e3);if(e<60)return"just now";if(e<3600)return`${Math.floor(e/60)}m`;if(e<86400)return`${Math.floor(e/3600)}h`;const n=Math.floor(e/86400);if(n<=7)return`${n}d`;try{return new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric"})}catch{return`${n}d`}}function A(t,e,n){const o=document.createElement(t);return e&&(o.className=e),n!==void 0&&(o.textContent=n),o}function st(t){const e=t.token??t.userId??We(),{httpBase:n,wsUrl:o}=_e(t.url,t.apiUrl),i=t.i18n??{},s=t.accent??"#6c5ce7";if(!document.getElementById("ocl-styles")){const v=document.createElement("style");v.id="ocl-styles",v.textContent=bn,document.head.append(v)}if(t.webfont!==!1&&typeof document<"u"&&!document.getElementById("ocw-webfont")){const v=document.createElement("link");v.id="ocw-webfont",v.rel="stylesheet",v.href="https://fonts.googleapis.com/css2?family=Baloo+2:wght@500;600;700&family=Nunito:wght@400;500;600;700&display=swap",document.head.append(v)}const r=A("div","ocl");r.style.setProperty("--ocl-accent",s),r.dataset.theme=t.theme??"light",t.reserveCloseSpace&&r.classList.add("ocl-has-close");const w=A("div","ocl-head"),l=i.title??"Your conversations",u=A("span","ocl-title",l);if(u.setAttribute("aria-label",l),w.append(u),t.onNewChat){const v=A("button","ocl-compose","✎");v.title=i.newChat??"New conversation",v.addEventListener("click",()=>t.onNewChat()),w.append(v)}const x=A("div","ocl-search-wrap"),d=A("input","ocl-search");d.placeholder=i.search??"🔍 Search",d.type="search",x.append(d);const g=A("div","ocl-body");g.append(A("div","ocl-spinner","Loading…")),r.append(w,x,g),t.el.replaceChildren(r);const U=v=>{r.classList.toggle("ocl-compact",v>0&&v<400)};U(r.clientWidth);let E=null;if(typeof ResizeObserver<"u"&&(E=new ResizeObserver(v=>{var P;return U(((P=v[0])==null?void 0:P.contentRect.width)??r.clientWidth)}),E.observe(r)),!t.profileId&&!t.tenantId)throw new Error("[relay chatlist] provide profileId or tenantId");let _;const z=`ocl_seen_${t.profileId??`t_${t.tenantId}`}_${(t.userId??e).slice(-8)}`;let M={};try{M=JSON.parse(localStorage.getItem(z)??"{}")}catch{}const R=()=>{try{localStorage.setItem(z,JSON.stringify(M))}catch{}};let O=[],B=!1;const J=async()=>{const v=t.profileId?`profileId=${encodeURIComponent(t.profileId)}${t.scope==="tenant"?"&scope=tenant":""}`:`tenantId=${encodeURIComponent(t.tenantId)}`,P=`${n}/conversations/mine?${v}`,H={authorization:`Bearer ${e}`};let G;try{G=await fetch(P,{headers:H})}catch{G=await fetch(P,{headers:H})}if(!G.ok)return[];const K=await G.json();return K.defaultProfileId&&(_=K.defaultProfileId),(K.conversations??[]).sort((Z,L)=>L.updatedAt-Z.updatedAt)},p=(v,P)=>{if(B)return;const H=P?v.filter(L=>h(L).toLowerCase().includes(P)||(L.lastMessage??"").toLowerCase().includes(P)):v;if(g.replaceChildren(),!H.length){const L=A("div","ocl-empty",P?"No results.":i.empty??"No conversations yet.");if(!P&&t.onNewChat){L.append(A("br"));const ae=A("button","ocl-start",i.newChat??"Start a conversation");ae.addEventListener("click",()=>t.onNewChat()),L.append(ae)}g.append(L);return}const G=L=>(L.lastSeq??0)>(M[L.id]??0),K=H.filter(G),Z=H.filter(L=>!G(L));if(K.length){g.append(A("div","ocl-section",`${i.unread??"Unread"} (${K.length})`));for(const L of K)g.append(C(L,G(L)))}if(Z.length){g.append(A("div","ocl-section",K.length?i.all??"All conversations":""));for(const L of Z)g.append(C(L,!1))}},h=v=>v.subjectTitle??(v.kind==="direct"?v.peerId??"Direct message":"General enquiry"),C=(v,P)=>{var W;const H=h(v),G=(((W=H.match(new RegExp("\\p{L}","u")))==null?void 0:W[0])??H.trim()[0]??"?").toUpperCase(),K=v.lastSeq??0,Z=P?Math.max(1,K-(M[v.id]??0)):0,L=A("button",`ocl-row${P?" unread":""}`),ae=A("div","ocl-av",G);L.append(ae);const le=A("div","ocl-info");le.append(A("div","ocl-name",H));const f={open:"Open",awaiting_staff:"Waiting for reply…",resolved:"Resolved ✓",closed:"Closed"};le.append(A("div","ocl-preview",v.lastMessage??f[v.state]??v.state)),L.append(le);const y=A("div","ocl-right");y.append(A("div","ocl-time",kn(v.updatedAt)));const I=vn(v.state);return I&&y.append(A("div",`ocl-status ${I.cls}`,I.label)),Z>0&&y.append(A("div","ocl-badge",String(Z>99?"99+":Z))),L.append(y),L.addEventListener("click",()=>{var re;K>0&&(M[v.id]=K,R()),L.classList.remove("unread"),(re=y.querySelector(".ocl-badge"))==null||re.remove(),t.onSelect(v)}),L},m=()=>{B||J().then(v=>{B||(O=v,p(v,d.value.trim().toLowerCase()))}).catch(v=>{if(B)return;console.error(`[chat-widget] failed to load conversations from ${n}/conversations/mine — check the apiUrl/CORS config.`,v);const P=A("div","ocl-empty",i.error??"Could not load conversations.");P.append(A("br"));const H=A("button","ocl-retry",i.retry??"Retry");H.addEventListener("click",()=>{g.replaceChildren(A("div","ocl-spinner","Loading…")),m()}),P.append(H),g.replaceChildren(P)})};d.addEventListener("input",()=>p(O,d.value.trim().toLowerCase())),m();let k=null,T,$,b=0,S=!1;const N=()=>{$||($=setTimeout(()=>{$=void 0,m()},300))},F=()=>{if(!B){try{k=new WebSocket(o)}catch{Q();return}k.binaryType="arraybuffer",k.onopen=()=>{b=0,k.send(Re({type:"auth",token:e})),k.send(Re({type:"subscribe_inbox"})),S&&N(),S=!0},k.onmessage=v=>{const P=Je(new Uint8Array(v.data));P&&P.type==="inbox_event"&&N()},k.onclose=()=>{k=null,Q()},k.onerror=()=>{try{k==null||k.close()}catch{}}}},Q=()=>{if(B||T)return;const v=Math.min(15e3,500*2**b++)+Math.random()*250;T=setTimeout(()=>{T=void 0,F()},v)};return F(),{refresh:m,close(){B=!0,T&&clearTimeout(T),$&&clearTimeout($),E==null||E.disconnect(),E=null;try{k==null||k.close()}catch{}k=null,t.el.replaceChildren()},defaultProfileId(){return t.profileId??_}}}const Sn=Object.freeze(Object.defineProperty({__proto__:null,mountChatList:st},Symbol.toStringTag,{value:"Module"})),fe=new WeakMap,ke=new Map;function rt(t){return`relay-launcher::${t.profileId}::${t.subjectId??""}`}let we=null;function In(){if(we&&we.state!=="closed")return we;try{return we=new AudioContext,we}catch{return null}}function Tn(t){const e=t.el;let n=null,o=null,i=!1;const s=()=>{n==null||n.close(),n=null,o==null||o.close(),o=null,e.innerHTML=""};function r(){i||(s(),o=st({el:e,url:t.url,...t.apiUrl?{apiUrl:t.apiUrl}:{},...t.profileId?{profileId:t.profileId}:{},scope:t.inboxScope??"tenant",...t.token?{token:t.token}:{},...t.userId?{userId:t.userId}:{},...t.accent?{accent:t.accent}:{},...t.theme?{theme:t.theme}:{},...t.webfont===!1?{webfont:!1}:{},onSelect:l=>w(l)}))}function w(l){if(i)return;s();const{subjectId:u,kind:x,peerId:d,...g}=t;n=De({...g,inbox:!1,launcher:!1,el:e,...l.profileId?{profileId:l.profileId}:{},...l.subjectId?{subjectId:l.subjectId}:{},...l.kind==="direct"&&l.peerId?{kind:"direct",peerId:l.peerId}:{},onBack:r})}return r(),{close(){i=!0,s()}}}function De(t){var P,H,G,K,Z,L,ae,le;if(t.inbox)return Tn(t);fe.has(t.el)&&(fe.get(t.el).close(),fe.delete(t.el)),t.launcher&&((P=ke.get(rt(t)))==null||P.close());const e=We();let n,o=!1;const i=t.token??t.userId??e,s=i!==e?e:void 0,{wsUrl:r,httpBase:w}=_e(t.url,t.apiUrl);let l=new Xt(i);const u=t.subjectId?`${i}::${t.subjectId}`:i,x=new nn(u);let d,g=!1,U=null,E=null,_=null,z=null;!t.launcher&&!t.el.style.height&&t.el.clientHeight===0&&(t.el.style.width=t.el.style.width||"100%",t.el.style.height="600px");for(const f of x.load())l.addOptimistic(f.clientMsgId,f.content);let M=null,R=null,O=0,B=!t.launcher;if(t.launcher){const y=(t.position??"bottom-right").includes("right");M=document.createElement("div"),M.style.cssText=`position:fixed;${y?"right:20px":"left:20px"};bottom:20px;z-index:9999;display:flex;flex-direction:column;align-items:${y?"flex-end":"flex-start"};gap:12px`;const I=document.createElement("div"),W=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(max-width: 479px)"):null,re=q=>{t.el.classList.toggle("ocw-fs",q),I.style.cssText=q?["position:fixed","inset:0","width:100%","height:100dvh","border-radius:0","overflow:hidden","box-shadow:none","display:none","flex-direction:column","background:#fff","transition:opacity .18s","opacity:0","z-index:9998"].join(";"):["width:min(380px, calc(100vw - 40px))","height:min(600px, calc(100dvh - 108px))","border-radius:28px","overflow:hidden","box-shadow:0 12px 32px rgba(108,92,231,.14)","display:none","flex-direction:column","background:#fff","transform-origin:bottom "+(y?"right":"left"),"transition:opacity .18s,transform .18s","opacity:0","transform:scale(.95)"].join(";")};re((W==null?void 0:W.matches)??!1);const ye=q=>re(q.matches);W==null||W.addEventListener("change",ye),U=W,E=ye,t.el.style.cssText="width:100%;height:100%;overflow:hidden",I.append(t.el);const Te='<svg viewBox="0 0 24 24" width="26" height="26" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',Ee='<svg viewBox="0 0 24 24" width="22" height="22" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/></svg>',Y=document.createElement("button");Y.type="button",Y.style.cssText=["width:56px;height:56px;border-radius:50%",`background:${t.accent??"#6c5ce7"}`,"color:#fff;border:none;cursor:pointer","box-shadow:0 12px 32px rgba(108,92,231,.14)","position:relative;flex:none","display:flex;align-items:center;justify-content:center","transition:transform .15s"].join(";"),Y.onmouseenter=()=>{Y.style.transform="scale(1.08)"},Y.onmouseleave=()=>{Y.style.transform="scale(1)"},R=document.createElement("span"),R.style.cssText="position:absolute;top:-4px;right:-4px;background:#4c6fff;color:#fff;border-radius:50%;width:20px;height:20px;font-size:11px;font-weight:700;display:none;align-items:center;justify-content:center";const Ce=()=>{Y.innerHTML=B?Ee:Te,Y.setAttribute("aria-label",B?"Close chat":"Open chat"),Y.setAttribute("aria-expanded",String(B)),Y.append(R)};Ce(),M.append(I,Y),document.body.append(M);const Ne=`ocw-teaser-dismissed::${t.profileId}`,Ue=typeof t.launcherMessage=="string"?{title:t.launcherMessage}:t.launcherMessage;let D=null;const zn=()=>{try{return sessionStorage.getItem(Ne)==="1"}catch{return!1}},Mn='<svg viewBox="0 0 24 24" width="15" height="15" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',lt=()=>{const q=Ue!=null&&Ue.title?Ue:l.launcherMessage??void 0;if(!(!!(q!=null&&q.title)&&!B&&!zn())){D&&(D.remove(),D=null);return}if(D)return;D=document.createElement("div"),D.setAttribute("role","button"),D.setAttribute("tabindex","0"),D.setAttribute("aria-label",q.title),D.style.cssText=["max-width:280px","background:#fff","border-radius:16px","box-shadow:0 12px 32px rgba(108,92,231,.14)","padding:14px 40px 14px 16px","position:relative","cursor:pointer","font-family:inherit",`align-self:${y?"flex-end":"flex-start"}`,"animation:ocw-teaser-in .22s ease-out"].join(";");const Fe=document.createElement("div");if(Fe.textContent=q.title,Fe.style.cssText="font-size:15px;font-weight:600;color:#111;line-height:1.35",D.append(Fe),q.subtitle){const ie=document.createElement("div");ie.style.cssText="display:flex;align-items:center;gap:6px;margin-top:6px;font-size:13px;color:#6b7280";const He=document.createElement("span");He.innerHTML=Mn,He.style.cssText=`color:${t.accent??"#6c5ce7"};display:inline-flex`;const ht=document.createElement("span");ht.textContent=q.subtitle,ie.append(He,ht),D.append(ie)}const de=document.createElement("button");de.type="button",de.setAttribute("aria-label","Dismiss"),de.innerHTML='<svg viewBox="0 0 24 24" width="14" height="14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M18 6 6 18M6 6l12 12" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/></svg>',de.style.cssText="position:absolute;top:8px;right:8px;width:24px;height:24px;border:none;border-radius:50%;background:#f3f4f6;color:#6b7280;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0",de.addEventListener("click",ie=>{ie.stopPropagation();try{sessionStorage.setItem(Ne,"1")}catch{}D&&(D.remove(),D=null)}),D.append(de);const dt=()=>{B||(B=!0,Oe(!0),Ce(),O=0,R&&(R.style.display="none"),D&&(D.remove(),D=null))};D.addEventListener("click",dt),D.addEventListener("keydown",ie=>{(ie.key==="Enter"||ie.key===" ")&&(ie.preventDefault(),dt())}),M.insertBefore(D,Y)};if(!document.getElementById("ocw-teaser-style")){const q=document.createElement("style");q.id="ocw-teaser-style",q.textContent="@keyframes ocw-teaser-in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",document.head.append(q)}z=lt,lt();const Oe=q=>{q?(I.style.display="flex",requestAnimationFrame(()=>{I.style.opacity="1",I.style.transform="scale(1)"})):(I.style.opacity="0",I.style.transform="scale(.95)",setTimeout(()=>{B||(I.style.display="none")},180))};Y.addEventListener("click",()=>{if(B=!B,Oe(B),Ce(),B){O=0,R&&(R.style.display="none");try{sessionStorage.setItem(Ne,"1")}catch{}}z==null||z()}),_=q=>{q.key==="Escape"&&B&&(B=!1,Oe(!1),Ce())},document.addEventListener("keydown",_)}const J=()=>{B||(O++,R&&(R.textContent=String(O),R.style.display="flex"))},p=()=>{try{const f=In();if(!f)return;f.state==="suspended"&&f.resume().catch(()=>{});const y=f.createOscillator(),I=f.createGain();y.connect(I),I.connect(f.destination),y.frequency.setValueAtTime(880,f.currentTime),y.frequency.exponentialRampToValueAtTime(440,f.currentTime+.15),I.gain.setValueAtTime(.3,f.currentTime),I.gain.exponentialRampToValueAtTime(.001,f.currentTime+.3),y.start(),y.stop(f.currentTime+.3)}catch{}},h=[],C=f=>{for(;h.length;){const y=h.shift();x.add({clientMsgId:y.clientMsgId,content:y.content,ts:Date.now()}),m.send({type:"send",conversationId:f,clientMsgId:y.clientMsgId,content:y.content})}};let m;const k=t.i18n??{},T=["ar","he","fa","ur"],$=typeof navigator<"u"?(navigator.language??"").slice(0,2).toLowerCase():"";T.includes($)&&!t.el.dir&&(t.el.dir="rtl",t.el.style.fontFamily=t.el.style.fontFamily||"Tahoma,Arial,system-ui,sans-serif");const b=`oc_prechat_${t.profileId}_${i.slice(-8)}`,S=new fn(t.el,i,{onSend(f){const y=`cm_${Math.random().toString(36).slice(2)}`,I={kind:"text",text:f};if(l.addOptimistic(y,I),S.render(l),l.e2e){console.error("[relay] this chat is end-to-end encrypted — use the full widget build");return}else d?(x.add({clientMsgId:y,content:I,ts:Date.now()}),m.send({type:"send",conversationId:d,clientMsgId:y,content:I})):h.push({clientMsgId:y,content:I})},async onAttach(f){if(!d)return;const y=`${w}/upload?name=${encodeURIComponent(f.name)}`,I=`cm_${Math.random().toString(36).slice(2)}`;l.addOptimistic(I,{kind:"text",text:`📎 Uploading ${f.name}…`}),S.render(l);try{const W=await fetch(y,{method:"POST",headers:{"content-type":f.type,authorization:`Bearer ${i}`},body:f});if(!W.ok)throw new Error(`Upload failed: ${W.status}`);const{url:re,name:ye,mime:Te,size:Ee}=await W.json();l.addOptimistic(I,{kind:"attachment",url:re,name:ye,mime:Te,size:Ee}),S.render(l),m.send({type:"send",conversationId:d,clientMsgId:I,content:{kind:"attachment",url:re,name:ye,mime:Te,size:Ee}})}catch(W){l.addOptimistic(I,{kind:"text",text:`⚠️ Upload failed: ${W.message}`}),S.render(l)}},onInvoke(f,y){d&&m.send({type:"invoke",conversationId:d,actionId:f,clientInvokeId:`iv_${Math.random().toString(36).slice(2)}`,...y?{inputs:y}:{}})},onTyping(f,y){d&&m.send({type:"typing",conversationId:d,isTyping:f,...y?{preview:y}:{}})},onPreChat(f){try{localStorage.setItem(b,"1")}catch{}m.send({type:"open",profileId:t.profileId,...t.subjectId?{subjectId:t.subjectId}:{},userInfo:{...f.name?{name:f.name}:{},...f.email?{email:f.email}:{},...f.phone||f.topic?{meta:{...f.phone?{phone:f.phone}:{},...f.topic?{topic:f.topic}:{}}}:{}}});const y=f.callback?`📞 Call-back requested${f.phone?`: ${f.phone}`:""}${f.topic?` — ${f.topic}`:""}`:f.topic?`Topic: ${f.topic}`:"";y&&d&&!l.e2e&&m.send({type:"send",conversationId:d,clientMsgId:`pc_${Math.random().toString(36).slice(2,12)}`,content:{kind:"text",text:y}})},...((H=t.features)==null?void 0:H.deflection)!==!1?{onDeflectQuery(f){if(o)return;clearTimeout(n);const y=f.trim();if(y.length<3){S.hideDeflection();return}n=setTimeout(()=>{fetch(`${w}/kb/search?profileId=${encodeURIComponent(t.profileId)}&q=${encodeURIComponent(y.slice(0,200))}`).then(I=>I.ok?I.json():{articles:[]}).then(I=>S.showDeflection(I.articles??[])).catch(()=>S.hideDeflection())},350)}}:{},onReadUpTo(f){d&&m.send({type:"read",conversationId:d,seq:f})},onLoadMore(){if(!d||!l.e2e)return;const f=l.messages()[0];f&&m.send({type:"history",conversationId:d,beforeSeq:f.seq,limit:20})},onEdit(f,y){d&&m.send({type:"edit",conversationId:d,messageId:f,content:{kind:"text",text:y}})},onDelete(f){d&&m.send({type:"delete",conversationId:d,messageId:f})},...((G=t.features)==null?void 0:G.reactions)!==!1?{onReact(f,y,I){d&&m.send({type:"react",conversationId:d,messageId:f,emoji:y,remove:I})}}:{},...((K=t.features)==null?void 0:K.csat)!==!1?{onCsat(f){d&&fetch(`${w}/conversations/${d}/csat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({score:f})}).catch(()=>{})}}:{},...t.translateLang?{async onTranslate(f){try{const y=await fetch(`${w}/translate`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${i}`},body:JSON.stringify({text:f,targetLang:t.translateLang})});if(!y.ok)return null;const{translated:I}=await y.json();return I}catch{return null}}}:{},...t.onBack?{onBack:t.onBack}:{}},{...t.subject?{subject:t.subject}:{},...t.quickReplies?{quickReplies:t.quickReplies}:{},...t.accent?{accent:t.accent}:{},...t.accent2?{accent2:t.accent2}:{},...t.theme?{theme:t.theme}:{},...t.webfont===!1?{webfont:!1}:{},...(Z=t.user)!=null&&Z.name||(L=t.user)!=null&&L.avatar?{userInfo:{...t.user.name?{name:t.user.name}:{},...t.user.avatar?{avatar:t.user.avatar}:{}}}:{},i18n:k});try{localStorage.getItem(b)&&S.completePreChat()}catch{}const N=t.user&&(t.user.name||t.user.email||t.user.avatar||t.user.meta)?{...t.user.name?{name:t.user.name}:{},...t.user.email?{email:t.user.email}:{},...t.user.avatar?{avatar:t.user.avatar}:{},...t.user.meta?{meta:t.user.meta}:{}}:void 0,F={type:"open",profileId:t.profileId,...t.kind==="direct"&&t.peerId?{kind:"direct",peerId:t.peerId}:t.subjectId?{subjectId:t.subjectId}:{},...s?{linkFrom:s}:{},...N?{userInfo:N}:{},...typeof location<"u"?{pageUrl:location.href}:{},...typeof document<"u"&&document.title?{pageTitle:document.title}:{},...(ae=t.subject)!=null&&ae.title?{subjectTitle:t.subject.title}:{},...(le=t.subject)!=null&&le.subtitle?{subjectMeta:t.subject.subtitle}:{}};m=new Jt({...t.refreshToken?{refreshToken:t.refreshToken}:{},url:r,token:i,open:F,getCursor:()=>l.highestSeq(),onStatusChange:(f,y)=>S.setConnStatus(f,y),onFrame(f){if(f.type==="opened"){if(d=f.conversation.id,!g){g=!0;for(const y of x.load())m.send({type:"send",conversationId:d,clientMsgId:y.clientMsgId,content:y.content})}mn(r,i,d,l,S,w),h.length&&C(d)}f.type==="ack"&&x.remove(f.clientMsgId),(async()=>{if(l.apply(f),f.type==="manifest"){z==null||z();const y=f.botName;y&&S.setBotName(y)}f.type==="message"&&f.message.senderId!==i&&!f.message.internal&&(J(),p()),S.render(l)})()}}),m.connect(),S.render(l);const Q=t.launcher?rt(t):null,v={close:()=>{o=!0,clearTimeout(n),m.close(),M==null||M.remove(),S.destroy(),U&&E&&U.removeEventListener("change",E),_&&(document.removeEventListener("keydown",_),_=null),fe.delete(t.el),Q&&ke.get(Q)===v&&ke.delete(Q)}};return fe.set(t.el,v),Q&&ke.set(Q,v),v}const qe="wss://api.paramms.com/ws";function En(t,e){const n=t.profileId??t.appId;if(!n)throw new Error("Relay: `profileId` is required (your chatroom id, e.g. 'p_...').");const o=t.subjectId??(t.listingId?`listing_${t.listingId}`:void 0),i=t.launcher??!0,s=t.contextTitle??t.listingTitle??t.subjectTitle,r=t.contextSubtitle??t.listingMeta??t.subjectMeta,w=t.contextStatus??t.listingStatus??t.subjectStatus,l=t.listingPrice??t.subjectPrice,u=s?{title:s,...r?{subtitle:r}:{},...l!=null?{tags:[`$${l.toLocaleString()}`]}:{},...w?{status:w}:{}}:void 0,x=t.subject??u,d=t.userName??t.name,g=t.userEmail??t.email,U=t.userAvatar??t.avatar,E=d||g||U?{...d?{name:d}:{},...g?{email:g}:{},...U?{avatar:U}:{}}:void 0,_=t.user??E,z=t.launcherMessage&&typeof t.launcherMessage=="object"?t.launcherMessage:t.launcherMessage?t.launcherSubtitle?{title:t.launcherMessage,subtitle:t.launcherSubtitle}:t.launcherMessage:void 0;return{el:e,url:t.url??qe,profileId:n,...t.apiUrl?{apiUrl:t.apiUrl}:{},...o?{subjectId:o}:{},...t.token?{token:t.token}:{},...t.refreshToken?{refreshToken:t.refreshToken}:{},...t.userId?{userId:t.userId}:{},...x?{subject:x}:{},..._?{user:_}:{},...t.quickReplies?{quickReplies:t.quickReplies}:{},...t.i18n?{i18n:t.i18n}:{},...t.features?{features:t.features}:{},...t.accent?{accent:t.accent}:{},...t.accent2?{accent2:t.accent2}:{},...t.theme?{theme:t.theme}:{},...t.webfont===!1?{webfont:!1}:{},...t.translateLang?{translateLang:t.translateLang}:{},...z?{launcherMessage:z}:{},...at(t)&&!i?{onBack:()=>{xe=!0,ge=!1,Se(se)}}:{},launcher:i,position:t.position??"bottom-right"}}let te=null,j=null,oe=!1,se={},xe=!1,ge=!1;function at(t){return!!(t.inbox||t.inboxStart)}let ne=null;function Cn(t,e){const n=!e&&!!t.el;if(oe&&!n&&(j.innerHTML="",j=null,oe=!1),n){const o=typeof t.el=="string"?document.querySelector(t.el):t.el;o instanceof HTMLElement?(j&&j!==o&&!oe&&j.remove(),j=o,oe=!0):console.error(`[Relay] \`el\` ("${String(t.el)}") did not match any element — falling back to an auto-created host.`)}return(!j||!oe&&!j.isConnected)&&(j=document.createElement("div"),j.id="relay-widget-root",document.body.appendChild(j),oe=!1),!e&&t.height&&(j.style.height=t.height,j.style.width||(j.style.width="100%")),j}function Se(t){try{const e=t.launcher??!0;ne==null||ne(),ne=null,te==null||te.close(),te=null;const n=Cn(t,e);if(at(t)&&!e&&xe){Un(t,n);return}te=De(En(t,n))}catch(e){console.error("[Relay]",e instanceof Error?e.message:e)}}async function Un(t,e){const n=t.profileId??t.appId;if(!n&&!t.tenantId){console.error("[Relay] `inbox` requires `profileId` or `tenantId`.");return}e.innerHTML="";const o=document.createElement("div");o.style.cssText="position:relative;width:100%;height:100%;overflow:hidden;background:#fff";const i=document.createElement("div");i.style.cssText="position:absolute;inset:0";const s=document.createElement("div");s.style.cssText="position:absolute;inset:0;display:none";const r=document.createElement("button");r.type="button",r.setAttribute("aria-label","Close"),r.textContent="✕",r.style.cssText="position:absolute;top:8px;right:8px;z-index:20;width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.05);border:none;color:#1c1b1a;font-size:16px;line-height:1;cursor:pointer",r.onclick=()=>{xe=!1,Se(se)},o.append(i,s);const w=!ge&&!!n;w&&o.append(r),e.appendChild(o);let l=null,u=null;ne=()=>{u==null||u.close(),l==null||l.close(),e.innerHTML=""};let x;try{({mountChatList:x}=await Promise.resolve().then(()=>Sn))}catch(g){console.error("[Relay] could not load the conversation list module.",g),i.isConnected&&(i.style.cssText+=";display:flex;align-items:center;justify-content:center;padding:16px;font:13px system-ui;color:#b91c1c;text-align:center",i.textContent="Could not load conversations.");return}if(!i.isConnected)return;const d=g=>{const U=g.profileId??n;if(!U){console.error("[Relay] conversation row has no chatroom; cannot open it.",g);return}r.style.display="none",u==null||u.close(),u=De({el:s,url:t.url??qe,...t.apiUrl?{apiUrl:t.apiUrl}:{},profileId:U,...g.kind==="direct"&&g.peerId?{kind:"direct",peerId:g.peerId}:g.subjectId?{subjectId:g.subjectId}:{},...t.token?{token:t.token}:{},...t.refreshToken?{refreshToken:t.refreshToken}:{},...t.userId?{userId:t.userId}:{},...t.userId||t.userName||t.userEmail||t.userAvatar?{user:{...t.userName?{name:t.userName}:{},...t.userEmail?{email:t.userEmail}:{},...t.userAvatar?{avatar:t.userAvatar}:{}}}:{},...g.subjectTitle?{subject:{title:g.subjectTitle,...g.subjectMeta?{subtitle:g.subjectMeta}:{}}}:{},...t.accent?{accent:t.accent}:{},launcher:!1,onBack:()=>{u==null||u.close(),u=null,s.style.display="none",i.style.display="",r.style.display="",l==null||l.refresh()}}),i.style.display="none",s.style.display=""};l=x({el:i,url:t.url??qe,...t.apiUrl?{apiUrl:t.apiUrl}:{},...n?{profileId:n}:{},...t.tenantId?{tenantId:t.tenantId}:{},scope:t.inboxScope??"tenant",...w?{reserveCloseSpace:!0}:{},onSelect:d,onNewChat:()=>{const g=n??(l==null?void 0:l.defaultProfileId());g&&d({id:"__new__",profileId:g,state:"open",updatedAt:Date.now()})},...t.token?{token:t.token}:{},...t.userId?{userId:t.userId}:{},...t.accent?{accent:t.accent}:{}})}function ct(t){ge=!!(t.inboxStart&&!(t.launcher??!0)),xe=ge,se={...t},Se(se)}function Bn(t){se={...se,...t},Se(se)}function Ln(){ne==null||ne(),ne=null,te==null||te.close(),te=null,j&&!oe&&j.remove(),j=null,oe=!1,xe=!1,ge=!1,se={}}function je(t,e){switch(t){case"boot":ct(e??{});break;case"update":case"identify":Bn(e??{});break;case"shutdown":Ln();break;default:console.warn("[Relay] unknown command:",t)}}function An(){if(typeof document>"u")return null;const t=document.querySelector("script[data-relay-app]")??document.querySelector("script[data-relay-profile-id]")??document.querySelector("script[data-relay-tenant-id]"),e=t==null?void 0:t.dataset,n=(e==null?void 0:e.relayApp)??(e==null?void 0:e.relayProfileId),o=e==null?void 0:e.relayTenantId;if(!n&&!o)return null;const i=n?{profileId:n}:{};o&&(i.tenantId=o),e.relayUser&&(i.userId=e.relayUser),e.relayToken&&(i.token=e.relayToken),e.relayListing&&(i.listingId=e.relayListing),e.relayAccent&&(i.accent=e.relayAccent),e.relayAccent2&&(i.accent2=e.relayAccent2),e.relayTheme&&(i.theme=e.relayTheme),e.relayWebfont==="false"&&(i.webfont=!1),e.relayUrl&&(i.url=e.relayUrl);const s=e.relayPosition;(s==="bottom-left"||s==="bottom-right")&&(i.position=s),e.relayLauncherMessage&&(i.launcherMessage=e.relayLauncherMessage),e.relayLauncherSubtitle&&(i.launcherSubtitle=e.relayLauncherSubtitle),e.relayLauncher==="false"&&(i.launcher=!1),e.relayUserName&&(i.userName=e.relayUserName),e.relayUserEmail&&(i.userEmail=e.relayUserEmail),e.relayUserAvatar&&(i.userAvatar=e.relayUserAvatar),e.relayContextTitle&&(i.contextTitle=e.relayContextTitle),e.relayContextSubtitle&&(i.contextSubtitle=e.relayContextSubtitle),e.relayContextStatus&&(i.contextStatus=e.relayContextStatus),e.relayListingTitle&&(i.listingTitle=e.relayListingTitle),e.relayListingMeta&&(i.listingMeta=e.relayListingMeta),e.relayListingPrice&&(i.listingPrice=Number(e.relayListingPrice)),e.relayListingStatus&&(i.listingStatus=e.relayListingStatus),e.relayTarget&&(i.el=e.relayTarget),e.relayHeight&&(i.height=e.relayHeight),e.relayInbox==="true"&&(i.inbox=!0),e.relayInbox==="false"&&(i.inbox=!1),e.relayInboxStart==="true"&&(i.inboxStart=!0),e.relayInboxStart==="false"&&(i.inboxStart=!1);const r=e.relayInboxScope;return(r==="tenant"||r==="profile")&&(i.inboxScope=r),e.relayTranslateLang&&(i.translateLang=e.relayTranslateLang),i}if(typeof window<"u"){const t=window,e=t.Relay&&t.Relay.q?t.Relay.q:[];t.Relay=je;let n=!1;for(const o of e){const[i,s]=o;i==="boot"&&(n=!0),je(i,s)}if(!n){const o=t.relaySettings??An();o&&ct(o)}}return ee.Relay=je,Object.defineProperty(ee,Symbol.toStringTag,{value:"Module"}),ee}({});
241
241
  //# sourceMappingURL=embed-lite.js.map