@paramms/chat-widget 1.0.37 → 1.0.39

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.
package/dist/embed.js CHANGED
@@ -1,16 +1,26 @@
1
- var RelayEmbed=function(R){"use strict";var Sn=Object.defineProperty;var Cn=(R,D,O)=>D in R?Sn(R,D,{enumerable:!0,configurable:!0,writable:!0,value:O}):R[D]=O;var a=(R,D,O)=>Cn(R,typeof D!="symbol"?D+"":D,O);const D="oc_uid";function O(i){try{const e=document.cookie.match(new RegExp(`(?:^|; )${i}=([^;]*)`));return e?decodeURIComponent(e[1]):null}catch{return null}}function Ne(i,e){try{const n=location.protocol==="https:"?"; Secure":"";document.cookie=`${i}=${encodeURIComponent(e)}; Max-Age=31536000; Path=/; SameSite=Lax${n}`}catch{}}function We(){return`g_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`}function Ve(){let i=null;try{i=localStorage.getItem(D)}catch{}i||(i=O(D));const e=i??We();try{localStorage.setItem(D,e)}catch{}return Ne(D,e),e}function Xe(i){const e=i.length;let t=0,n=0;for(;n<e;){let s=i.charCodeAt(n++);if(s&4294967168)if(!(s&4294965248))t+=2;else{if(s>=55296&&s<=56319&&n<e){const o=i.charCodeAt(n);(o&64512)===56320&&(++n,s=((s&1023)<<10)+(o&1023)+65536)}s&4294901760?t+=4:t+=3}else{t++;continue}}return t}function Ye(i,e,t){const n=i.length;let s=t,o=0;for(;o<n;){let r=i.charCodeAt(o++);if(r&4294967168)if(!(r&4294965248))e[s++]=r>>6&31|192;else{if(r>=55296&&r<=56319&&o<n){const h=i.charCodeAt(o);(h&64512)===56320&&(++o,r=((r&1023)<<10)+(h&1023)+65536)}r&4294901760?(e[s++]=r>>18&7|240,e[s++]=r>>12&63|128,e[s++]=r>>6&63|128):(e[s++]=r>>12&15|224,e[s++]=r>>6&63|128)}else{e[s++]=r;continue}e[s++]=r&63|128}}const Je=new TextEncoder,Ge=50;function Ze(i,e,t){Je.encodeInto(i,e.subarray(t))}function Qe(i,e,t){i.length>Ge?Ze(i,e,t):Ye(i,e,t)}const et=4096;function be(i,e,t){let n=e;const s=n+t,o=[];let r="";for(;n<s;){const h=i[n++];if(!(h&128))o.push(h);else if((h&224)===192){const p=i[n++]&63;o.push((h&31)<<6|p)}else if((h&240)===224){const p=i[n++]&63,f=i[n++]&63;o.push((h&31)<<12|p<<6|f)}else if((h&248)===240){const p=i[n++]&63,f=i[n++]&63,g=i[n++]&63;let l=(h&7)<<18|p<<12|f<<6|g;l>65535&&(l-=65536,o.push(l>>>10&1023|55296),l=56320|l&1023),o.push(l)}else o.push(h);o.length>=et&&(r+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(r+=String.fromCharCode(...o)),r}const tt=new TextDecoder,nt=200;function it(i,e,t){const n=i.subarray(e,e+t);return tt.decode(n)}function st(i,e,t){return t>nt?it(i,e,t):be(i,e,t)}class Q{constructor(e,t){a(this,"type");a(this,"data");this.type=e,this.data=t}}class z extends Error{constructor(e){super(e);const t=Object.create(z.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:z.name})}}const V=4294967295;function ot(i,e,t){const n=t/4294967296,s=t;i.setUint32(e,n),i.setUint32(e+4,s)}function me(i,e,t){const n=Math.floor(t/4294967296),s=t;i.setUint32(e,n),i.setUint32(e+4,s)}function ve(i,e){const t=i.getInt32(e),n=i.getUint32(e+4);return t*4294967296+n}function rt(i,e){const t=i.getUint32(e),n=i.getUint32(e+4);return t*4294967296+n}const at=-1,ct=4294967296-1,dt=17179869184-1;function lt({sec:i,nsec:e}){if(i>=0&&e>=0&&i<=dt)if(e===0&&i<=ct){const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,i),t}else{const t=i/4294967296,n=i&4294967295,s=new Uint8Array(8),o=new DataView(s.buffer);return o.setUint32(0,e<<2|t&3),o.setUint32(4,n),s}else{const t=new Uint8Array(12),n=new DataView(t.buffer);return n.setUint32(0,e),me(n,4,i),t}}function ht(i){const e=i.getTime(),t=Math.floor(e/1e3),n=(e-t*1e3)*1e6,s=Math.floor(n/1e9);return{sec:t+s,nsec:n-s*1e9}}function pt(i){if(i instanceof Date){const e=ht(i);return lt(e)}else return null}function ut(i){const e=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(i.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const t=e.getUint32(0),n=e.getUint32(4),s=(t&3)*4294967296+n,o=t>>>2;return{sec:s,nsec:o}}case 12:{const t=ve(e,4),n=e.getUint32(0);return{sec:t,nsec:n}}default:throw new z(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${i.length}`)}}function ft(i){const e=ut(i);return new Date(e.sec*1e3+e.nsec/1e6)}const wt={type:at,encode:pt,decode:ft},ie=class ie{constructor(){a(this,"__brand");a(this,"builtInEncoders",[]);a(this,"builtInDecoders",[]);a(this,"encoders",[]);a(this,"decoders",[]);this.register(wt)}register({type:e,encode:t,decode:n}){if(e>=0)this.encoders[e]=t,this.decoders[e]=n;else{const s=-1-e;this.builtInEncoders[s]=t,this.builtInDecoders[s]=n}}tryToEncode(e,t){for(let n=0;n<this.builtInEncoders.length;n++){const s=this.builtInEncoders[n];if(s!=null){const o=s(e,t);if(o!=null){const r=-1-n;return new Q(r,o)}}}for(let n=0;n<this.encoders.length;n++){const s=this.encoders[n];if(s!=null){const o=s(e,t);if(o!=null){const r=n;return new Q(r,o)}}}return e instanceof Q?e:null}decode(e,t,n){const s=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return s?s(e,t,n):new Q(t,e)}};a(ie,"defaultCodec",new ie);let ee=ie;function yt(i){return i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer}function de(i){return i instanceof Uint8Array?i:ArrayBuffer.isView(i)?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):yt(i)?new Uint8Array(i):Uint8Array.from(i)}const xt=100,gt=2048;class le{constructor(e){a(this,"extensionCodec");a(this,"context");a(this,"useBigInt64");a(this,"maxDepth");a(this,"initialBufferSize");a(this,"sortKeys");a(this,"forceFloat32");a(this,"ignoreUndefined");a(this,"forceIntegerToFloat");a(this,"pos");a(this,"view");a(this,"bytes");a(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??ee.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)??xt,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??gt,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,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);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,t)}ensureBufferSizeToWrite(e){const t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){const t=new ArrayBuffer(e),n=new Uint8Array(t),s=new DataView(t);n.set(this.bytes),this.view=s,this.bytes=n}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 n=Xe(e);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),Qe(e,this.bytes,this.pos),this.pos+=n}encodeObject(e,t){const n=this.extensionCodec.tryToEncode(e,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);const n=de(e);this.writeU8a(n)}encodeArray(e,t){const n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(const s of e)this.doEncode(s,t+1)}countWithoutUndefined(e,t){let n=0;for(const s of t)e[s]!==void 0&&n++;return n}encodeMap(e,t){const n=Object.keys(e);this.sortKeys&&n.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const o of n){const r=e[o];this.ignoreUndefined&&r===void 0||(this.encodeString(o),this.doEncode(r,t+1))}}encodeExtension(e){if(typeof e.data=="function"){const n=e.data(this.pos+6),s=n.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(n);return}const t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}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),ot(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),me(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 bt(i,e){return new le(e).encodeSharedRef(i)}function he(i){return`${i<0?"-":""}0x${Math.abs(i).toString(16).padStart(2,"0")}`}const mt=16,vt=16;class kt{constructor(e=mt,t=vt){a(this,"hit",0);a(this,"miss",0);a(this,"caches");a(this,"maxKeyLength");a(this,"maxLengthPerKey");this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let n=0;n<this.maxKeyLength;n++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,n){const s=this.caches[n-1];e:for(const o of s){const r=o.bytes;for(let h=0;h<n;h++)if(r[h]!==e[t+h])continue e;return o.str}return null}store(e,t){const n=this.caches[e.length-1],s={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=s:n.push(s)}decode(e,t,n){const s=this.find(e,t,n);if(s!=null)return this.hit++,s;this.miss++;const o=be(e,t,n),r=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(r,o),o}}const pe="array",X="map_key",ke="map_value",St=i=>{if(typeof i=="string"||typeof i=="number")return i;throw new z("The type of key must be string or number but "+typeof i)};class Ct{constructor(){a(this,"stack",[]);a(this,"stackHeadPosition",-1)}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const t=this.getUninitializedStateFromPool();t.type=pe,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=X,t.readCount=0,t.size=e,t.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===pe){const n=e;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(e.type===X||e.type===ke){const n=e;n.size=0,n.map=void 0,n.readCount=0,n.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Y=-1,ue=new DataView(new ArrayBuffer(0)),It=new Uint8Array(ue.buffer);try{ue.getInt8(0)}catch(i){if(!(i 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 Se=new RangeError("Insufficient data"),Et=new kt;class fe{constructor(e){a(this,"extensionCodec");a(this,"context");a(this,"useBigInt64");a(this,"rawStrings");a(this,"maxStrLength");a(this,"maxBinLength");a(this,"maxArrayLength");a(this,"maxMapLength");a(this,"maxExtLength");a(this,"keyDecoder");a(this,"mapKeyConverter");a(this,"totalPos",0);a(this,"pos",0);a(this,"view",ue);a(this,"bytes",It);a(this,"headByte",Y);a(this,"stack",new Ct);a(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??ee.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)??V,this.maxBinLength=(e==null?void 0:e.maxBinLength)??V,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??V,this.maxMapLength=(e==null?void 0:e.maxMapLength)??V,this.maxExtLength=(e==null?void 0:e.maxExtLength)??V,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:Et,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??St}clone(){return new fe({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=Y,this.stack.reset()}setBuffer(e){const t=de(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Y&&!this.hasRemaining(1))this.setBuffer(e);else{const t=this.bytes.subarray(this.pos),n=de(e),s=new Uint8Array(t.length+n.length);s.set(t),s.set(n,t.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:t,pos:n}=this;return new RangeError(`Extra ${t.byteLength-n} of ${t.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 t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}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 t=!1,n;for await(const h of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(h);try{n=this.doDecodeSync(),t=!0}catch(p){if(!(p instanceof RangeError))throw p}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}const{headByte:s,pos:o,totalPos:r}=this;throw new RangeError(`Insufficient data in parsing ${he(s)} at ${r} (${o} 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,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let n=t,s=-1;for await(const o of e){if(t&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),n&&(s=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==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 t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else{const s=e-160;t=this.decodeString(s,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){const s=this.lookU8();t=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();t=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();t=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e===196){const s=this.lookU8();t=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();t=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();t=this.decodeBinary(s,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();t=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();t=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();t=this.decodeExtension(s,4)}else throw new z(`Unrecognized type byte: ${he(e)}`);this.complete();const n=this.stack;for(;n.length>0;){const s=n.top();if(s.type===pe)if(s.array[s.position]=t,s.position++,s.position===s.size)t=s.array,n.release(s);else continue e;else if(s.type===X){if(t==="__proto__")throw new z("The key __proto__ is not allowed");s.key=this.mapKeyConverter(t),s.type=ke;continue e}else if(s.map[s.key]=t,s.readCount++,s.readCount===s.size)t=s.map,n.release(s);else{s.key=null,s.type=X;continue e}}return t}}readHeadByte(){return this.headByte===Y&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Y}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 z(`Unrecognized array type byte: ${he(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new z(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new z(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){var o;if(e>this.maxStrLength)throw new z(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw Se;const n=this.pos+t;let s;return this.stateIsMapKey()&&((o=this.keyDecoder)!=null&&o.canBeCached(e))?s=this.keyDecoder.decode(this.bytes,n,e):s=st(this.bytes,n,e),this.pos+=t+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===X:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new z(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw Se;const n=this.pos+t,s=this.bytes.subarray(n,n+e);return this.pos+=t+e,s}decodeExtension(e,t){if(e>this.maxExtLength)throw new z(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const n=this.view.getInt8(this.pos+t),s=this.decodeBinary(e,t+1);return this.extensionCodec.decode(s,n,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=rt(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 Tt(i,e){return new fe(e).decode(i)}const Pt=new Set(["auth","open","send","sync","history","read","typing","react","edit","delete","invoke","pubkey","ping","annotate","annotate_clear","uploadPrekeys","fetchPrekey","assign","tag","note","agent_status","subscribe_inbox","unsubscribe_inbox"]);function Ut(i){return Pt.has(i.type)}function At(i){return bt(i)}function Bt(i){let e;try{e=Tt(i)}catch{return null}return typeof e!="object"||e===null||typeof e.type!="string"?null:e}class Kt{constructor(e){a(this,"conversationId");a(this,"state","");a(this,"version",0);a(this,"hasMoreHistory",!1);a(this,"lastReadByOthers",0);a(this,"assignedAgentId");a(this,"accent");a(this,"subject");a(this,"name");a(this,"e2e",!1);a(this,"offline",!1);a(this,"offlineMessage","");a(this,"preChat",null);a(this,"whiteLabel",!1);a(this,"typing",new Set);a(this,"online",new Set);a(this,"annotations",[]);a(this,"annotationVersion",0);a(this,"sentiment");a(this,"sentimentScore");a(this,"actions",[]);a(this,"byId",new Map);a(this,"keyByClient",new Map);a(this,"_maxSeq",0);a(this,"_sorted",null);this.me=e}messages(){return this._sorted||(this._sorted=[...this.byId.values()].sort((e,t)=>{const n=e.status==="pending",s=t.status==="pending";return n!==s?n?1:-1:n&&s?e.ts-t.ts:e.seq-t.seq})),this._sorted}visibleActions(){return this.actions.filter(e=>!e.availableInStates||e.availableInStates.includes(this.state))}highestSeq(){return this._maxSeq}addOptimistic(e,t){const n={id:e,conversationId:this.conversationId,seq:0,senderId:this.me,senderRole:"guest",content:t,ts:Date.now(),clientMsgId:e,status:"pending"};return this.byId.set(e,n),this.keyByClient.set(e,e),this._sorted=null,n}apply(e){var t;switch(e.type){case"opened":this.conversationId=e.conversation.id,this.state=e.conversation.state,e.subject&&(this.subject=e.subject),e.annotations&&(this.annotations=e.annotations,this.annotationVersion++);return;case"manifest":this.actions=e.actions,this.version=e.version,e.name&&(this.name=e.name),(t=e.theme)!=null&&t.accent&&(this.accent=e.theme.accent),e.e2e&&(this.e2e=!0),e.offline&&(this.offline=!0),e.offlineMessage&&(this.offlineMessage=e.offlineMessage),e.whiteLabel&&(this.whiteLabel=!0),e.preChat&&(this.preChat=e.preChat);return;case"message":this.upsert({...e.message});return;case"ack":{const n=this.keyByClient.get(e.clientMsgId),s=n?this.byId.get(n):void 0;if(s&&n){this.byId.delete(n);const o={...s,id:e.messageId,seq:e.seq,ts:e.ts,status:"sent"};this.byId.set(e.messageId,o),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 n of e.messages)this.upsert({...n});return;case"history":for(const n of e.messages)this.upsert({...n});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 n=this.byId.get(e.messageId);if(!n)return;const s={...n.reactions??{}},o=(s[e.emoji]??[]).filter(r=>r!==e.by);e.removed||o.push(e.by),o.length?s[e.emoji]=o:delete s[e.emoji],this.byId.set(e.messageId,{...n,reactions:s}),this._sorted=null;return}case"edited":{const n=this.byId.get(e.messageId);n&&(this.byId.set(e.messageId,{...n,content:e.content,editedAt:e.editedAt}),this._sorted=null);return}case"deleted":{const n=this.byId.get(e.messageId);n&&(this.byId.set(e.messageId,{...n,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"annotation":this.annotations=[...this.annotations,e.stroke],this.annotationVersion++;return;case"annotation_clear":this.annotations=[],this.annotationVersion++;return;case"sentiment":this.sentiment=e.label,this.sentimentScore=e.score;return;default:return}}upsert(e){const t=this.byId.get(e.id);this.byId.set(e.id,t?{...t,...e}:e),e.seq>this._maxSeq&&(this._maxSeq=e.seq),this._sorted=null}markOwnStatus(e,t){const n=Ce(t);let s=!1;for(const[o,r]of this.byId)r.senderId!==this.me||r.seq<=0||r.seq>e||Ce(r.status)>=n||(this.byId.set(o,{...r,status:t}),s=!0);s&&(this._sorted=null)}}function Ce(i){switch(i){case"read":return 3;case"delivered":return 2;case"sent":return 1;default:return 0}}const Ie="http://www.w3.org/2000/svg",zt=8e3;class Lt{constructor(){a(this,"svg",null);a(this,"timers",new Set)}apply(e){var t;if(e.type==="annotation")this.draw(e.stroke);else if(e.type==="annotation_clear")this.clear();else if(e.type==="opened"&&((t=e.annotations)!=null&&t.length))for(const n of e.annotations)this.draw(n)}ensureSvg(){var t;if((t=this.svg)!=null&&t.isConnected)return this.svg;const e=document.createElementNS(Ie,"svg");return e.setAttribute("data-relay-annotations",""),e.setAttribute("aria-hidden","true"),e.setAttribute("style","position:fixed;inset:0;width:100vw;height:100vh;pointer-events:none;z-index:2147483000;"),document.body.append(e),this.svg=e,e}draw(e){var h;if(typeof document>"u"||!((h=e.points)!=null&&h.length))return;const t=this.ensureSvg(),n=window.innerWidth,s=window.innerHeight,o=document.createElementNS(Ie,"polyline");o.setAttribute("points",e.points.map(p=>`${(p.x*n).toFixed(1)},${(p.y*s).toFixed(1)}`).join(" ")),o.setAttribute("fill","none"),o.setAttribute("stroke",e.color||"#ff3b30"),o.setAttribute("stroke-width",String(e.width||3)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("data-stroke-id",e.id),t.append(o);const r=setTimeout(()=>{o.style.transition="opacity 600ms",o.style.opacity="0";const p=setTimeout(()=>{o.remove(),this.timers.delete(p)},650);this.timers.add(p),this.timers.delete(r)},zt);this.timers.add(r)}clear(){var e;(e=this.svg)==null||e.replaceChildren()}destroy(){var e;for(const t of this.timers)clearTimeout(t);this.timers.clear(),(e=this.svg)==null||e.remove(),this.svg=null}}class Mt{constructor(e){a(this,"socket",null);a(this,"state","idle");a(this,"authed",!1);a(this,"everAuthed",!1);a(this,"attempt",0);a(this,"outbox",[]);a(this,"stopped",!1);a(this,"timer",null);a(this,"refreshing",!1);this.opts=e}connect(){var n,s;if(this.state==="connecting"||this.state==="open")return;this.stopped=!1,this.state="connecting",this.authed=!1,(s=(n=this.opts).onStatusChange)==null||s.call(n,this.attempt>0?"reconnecting":"connecting");const t=(this.opts.socketFactory??Rt)(this.opts.url);t.binaryType="arraybuffer",this.socket=t,t.onopen=()=>{this.raw({type:"auth",token:this.opts.token})},t.onmessage=o=>{const r=Bt(new Uint8Array(o.data));!r||Ut(r)||this.handle(r)},t.onclose=()=>this.onClosed(),t.onerror=()=>{try{t.close()}catch{}}}send(e){if(this.state==="open"&&this.authed){this.raw(e);return}const t=this.opts.maxOutbox??1e3;this.outbox.length>=t&&(this.outbox=this.outbox.slice(this.outbox.length-(t>>1))),this.outbox.push(e)}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 t,n,s,o;if(e.type==="authed"&&(this.attempt=0,this.state="open",this.authed=!0,this.everAuthed=!0,(n=(t=this.opts).onStatusChange)==null||n.call(t,"open"),this.raw(this.opts.open),this.flush()),e.type==="opened"&&this.raw({type:"sync",conversationId:e.conversation.id,sinceSeq:this.opts.getCursor()}),e.type==="error"&&Dt.has(e.code)){if(e.code==="UNAUTHORIZED"&&this.opts.refreshToken&&!this.refreshing){this.refreshing=!0,(o=(s=this.opts).onStatusChange)==null||o.call(s,"reconnecting","Renewing session…"),this.opts.refreshToken().then(r=>{var h;if(this.refreshing=!1,!r){this.fatal(e);return}this.opts.token=r;try{(h=this.socket)==null||h.close()}catch{}}).catch(()=>{this.refreshing=!1,this.fatal(e)});return}this.fatal(e);return}this.opts.onFrame(e)}fatal(e){var t,n,s;this.stopped=!0;try{(t=this.socket)==null||t.close()}catch{}this.state="closed",(s=(n=this.opts).onStatusChange)==null||s.call(n,"error",$t(e.code)),this.opts.onFrame(e)}flush(){const e=this.outbox;this.outbox=[];for(const t of e)this.raw(t)}raw(e){var t;try{(t=this.socket)==null||t.send(At(e))}catch{this.outbox.push(e)}}onClosed(){var s,o;if(this.authed=!1,this.socket=null,this.stopped){this.state="closed";return}this.state="idle";const e=this.opts.backoffBaseMs??500,t=this.opts.backoffMaxMs??15e3,n=Math.min(t,e*2**this.attempt)*(.5+Math.random()*.5);this.attempt++,this.attempt>=3&&!this.everAuthed&&((o=(s=this.opts).onStatusChange)==null||o.call(s,"reconnecting","Can't reach chat — retrying…")),this.timer=setTimeout(()=>this.connect(),n)}}const Dt=new Set(["UNAUTHORIZED"]);function $t(i){switch(i){case"UNAUTHORIZED":return"Chat unavailable — sign-in/token was rejected";default:return"Chat unavailable"}}function Rt(i){return new WebSocket(i)}const Ee=200,_t=7*864e5;class Ht{constructor(e){a(this,"key");this.key=`ocw_outbox_${e}`}load(){try{const e=localStorage.getItem(this.key);if(!e)return[];const t=JSON.parse(e),n=Date.now()-_t,s=t.filter(o=>o.ts>=n);return s.length!==t.length&&this.save(s),s}catch{return[]}}add(e){try{const t=this.load();t.push(e),this.save(t.length>Ee?t.slice(t.length-Ee):t)}catch{}}remove(e){try{const t=this.load().filter(n=>n.clientMsgId!==e);this.save(t)}catch{}}save(e){try{localStorage.setItem(this.key,JSON.stringify(e))}catch{}}}const C=()=>globalThis.crypto.subtle;function te(i){const e=i instanceof Uint8Array?i:new Uint8Array(i);let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t)}function we(i){const e=atob(i),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return n}async function J(){const i=await C().generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]);return{publicKey:i.publicKey,privateKey:i.privateKey}}async function _(i){return te(await C().exportKey("raw",i))}async function N(i){return C().importKey("raw",we(i),{name:"ECDH",namedCurve:"P-256"},!1,[])}async function jt(i,e){const t=await N(e);return C().deriveKey({name:"ECDH",public:t},i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function qt(i,e){const t=globalThis.crypto.getRandomValues(new Uint8Array(12)),n=new TextEncoder().encode(e),s=await C().encrypt({name:"AES-GCM",iv:t},i,n);return{ct:te(s),iv:te(t)}}async function Ft(i,e,t){const n=await C().decrypt({name:"AES-GCM",iv:we(t)},i,we(e));return new TextDecoder().decode(n)}async function Ot(i){var t,n;try{const s=(t=globalThis.localStorage)==null?void 0:t.getItem(i);if(s){const{pub:o,priv:r}=JSON.parse(s),h=await C().importKey("jwk",o,{name:"ECDH",namedCurve:"P-256"},!0,[]),p=await C().importKey("jwk",r,{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]);return{publicKey:h,privateKey:p}}}catch{}const e=await J();try{const s=await C().exportKey("jwk",e.publicKey),o=await C().exportKey("jwk",e.privateKey);(n=globalThis.localStorage)==null||n.setItem(i,JSON.stringify({pub:s,priv:o}))}catch{}return e}async function Nt(i,e){const t=await C().exportKey("raw",e),n=await C().sign({name:"ECDSA",hash:"SHA-256"},i,t);return te(n)}async function Wt(){const i=await J(),e=await C().generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]);return{ecdhKP:i,ecdsaKP:{publicKey:e.publicKey,privateKey:e.privateKey},publicKeyB64:await _(i.publicKey),sigPublicKeyB64:await _(e.publicKey)}}async function Te(i){var t,n;try{const s=(t=globalThis.localStorage)==null?void 0:t.getItem(`${i}-identity`);if(s){const o=JSON.parse(s),r=await C().importKey("jwk",o.ecdhPub,{name:"ECDH",namedCurve:"P-256"},!0,[]),h=await C().importKey("jwk",o.ecdhPriv,{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]),p=await C().importKey("jwk",o.ecdsaPub,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),f=await C().importKey("jwk",o.ecdsaPriv,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"]);return{ecdhKP:{publicKey:r,privateKey:h},ecdsaKP:{publicKey:p,privateKey:f},publicKeyB64:await _(r),sigPublicKeyB64:await _(p)}}}catch{}const e=await Wt();try{const s=await C().exportKey("jwk",e.ecdhKP.publicKey),o=await C().exportKey("jwk",e.ecdhKP.privateKey),r=await C().exportKey("jwk",e.ecdsaKP.publicKey),h=await C().exportKey("jwk",e.ecdsaKP.privateKey);(n=globalThis.localStorage)==null||n.setItem(`${i}-identity`,JSON.stringify({ecdhPub:s,ecdhPriv:o,ecdsaPub:r,ecdsaPriv:h}))}catch{}return e}async function Vt(i,e){const t=await J(),n=await _(t.publicKey),s=await N(e.identityKey),o=await N(e.signedPrekey),r=e.oneTimePrekey?await N(e.oneTimePrekey):null,h=await H(i.privateKey,o),p=await H(t.privateKey,s),f=await H(t.privateKey,o),g=r?await H(t.privateKey,r):null,l=Pe(h,p,f,...g?[g]:[]);return{sharedKey:await Ue(l),ephemeralPublicKey:n}}async function Xt(i,e,t,n,s){const o=await N(t),r=await N(n),h=await H(e.privateKey,o),p=await H(i.privateKey,r),f=await H(e.privateKey,r),g=s?await H(s.privateKey,r):null,l=Pe(h,p,f,...g?[g]:[]);return Ue(l)}async function H(i,e){return C().deriveBits({name:"ECDH",public:e},i,256)}function Pe(...i){const e=i.reduce((s,o)=>s+o.byteLength,0),t=new Uint8Array(e);let n=0;for(const s of i)t.set(new Uint8Array(s),n),n+=s.byteLength;return t.buffer}async function Ue(i){const e=await C().importKey("raw",i,"HKDF",!1,["deriveKey"]);return C().deriveKey({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(32),info:new TextEncoder().encode("ObjectChat X3DH v1")},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}const Yt=20;class Jt{constructor(e){a(this,"kp");a(this,"shared");a(this,"identityKP");a(this,"signedPreKP");a(this,"signedPrekeyId");a(this,"otpKeys",[]);a(this,"x3dhShared");a(this,"pendingX3DH");this.storageKey=e}get ready(){return!!(this.shared??this.x3dhShared)}async begin(){return this.kp=await Ot(this.storageKey),_(this.kp.publicKey)}async onPeerKey(e){this.kp&&(this.shared=await jt(this.kp.privateKey,e))}async initX3DH(){this.identityKP=await Te(this.storageKey),this.signedPreKP=await J(),this.signedPrekeyId=`spk-${Date.now()}-${Math.random().toString(36).slice(2)}`;for(let s=0;s<Yt;s++)this.otpKeys.push(await J());const e=await _(this.signedPreKP.publicKey),t=await Nt(this.identityKP.ecdsaKP.privateKey,this.signedPreKP.publicKey),n=await Promise.all(this.otpKeys.map(s=>_(s.publicKey)));return{identityKey:this.identityKP.publicKeyB64,signedPrekey:e,signedPrekeyId:this.signedPrekeyId,signature:t,oneTimePrekeys:n}}async x3dhSendTo(e){this.identityKP||(this.identityKP=await Te(this.storageKey));const{sharedKey:t,ephemeralPublicKey:n}=await Vt(this.identityKP.ecdhKP,e);return this.x3dhShared=t,{ephemeralKey:n,spkId:e.signedPrekeyId,usedOTP:!!e.oneTimePrekey,senderIK:this.identityKP.publicKeyB64}}async x3dhReceiveFrom(e,t,n){if(!this.identityKP||!this.signedPreKP){this.pendingX3DH={senderIK:e,ephemeralKey:t,spkId:n};return}const s=this.otpKeys.shift();this.x3dhShared=await Xt(this.identityKP.ecdhKP,this.signedPreKP,e,t,s)}async flushPendingX3DH(){if(!this.pendingX3DH)return;const{senderIK:e,ephemeralKey:t,spkId:n}=this.pendingX3DH;this.pendingX3DH=void 0,await this.x3dhReceiveFrom(e,t,n)}async sealText(e,t){const n=this.x3dhShared??this.shared;if(!n)throw new Error("secure channel not ready");const{ct:s,iv:o}=await qt(n,e);return{kind:"text",text:s,enc:!0,iv:o,...t?{x3dhEK:t.ephemeralKey,x3dhSPK:t.spkId,x3dhIK:t.senderIK}:{}}}async openContent(e){if(e.kind!=="text"||!e.enc||!e.iv)return e;const t=this.x3dhShared??this.shared;if(!t)return{kind:"text",text:"🔒 encrypted"};try{return{kind:"text",text:await Ft(t,e.text,e.iv)}}catch{return{kind:"text",text:"🔒 unable to decrypt"}}}async openFrame(e){if(e.type==="message")e.message.content=await this.openContent(e.message.content);else if(e.type==="sync")for(const t of e.messages)t.content=await this.openContent(t.content)}}function Gt(i){if(i.kind!=="text"||!i.enc)return null;const e=i;return!e.x3dhEK||!e.x3dhSPK||!e.x3dhIK?null:{x3dhEK:e.x3dhEK,x3dhSPK:e.x3dhSPK,x3dhIK:e.x3dhIK}}const Ae="objectchat-widget-styles",Zt=["👍","❤️","😂","😮","😢","🙏"],Qt=`
1
+ var RelayEmbed=function(q){"use strict";var On=Object.defineProperty;var Nn=(q,R,X)=>R in q?On(q,R,{enumerable:!0,configurable:!0,writable:!0,value:X}):q[R]=X;var a=(q,R,X)=>Nn(q,typeof R!="symbol"?R+"":R,X);const R="oc_uid";function X(n){try{const e=document.cookie.match(new RegExp(`(?:^|; )${n}=([^;]*)`));return e?decodeURIComponent(e[1]):null}catch{return null}}function at(n,e){try{const i=location.protocol==="https:"?"; Secure":"";document.cookie=`${n}=${encodeURIComponent(e)}; Max-Age=31536000; Path=/; SameSite=Lax${i}`}catch{}}function ct(){return`g_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`}function lt(){let n=null;try{n=localStorage.getItem(R)}catch{}n||(n=X(R));const e=n??ct();try{localStorage.setItem(R,e)}catch{}return at(R,e),e}function dt(n){const e=n.length;let t=0,i=0;for(;i<e;){let s=n.charCodeAt(i++);if(s&4294967168)if(!(s&4294965248))t+=2;else{if(s>=55296&&s<=56319&&i<e){const o=n.charCodeAt(i);(o&64512)===56320&&(++i,s=((s&1023)<<10)+(o&1023)+65536)}s&4294901760?t+=4:t+=3}else{t++;continue}}return t}function ht(n,e,t){const i=n.length;let s=t,o=0;for(;o<i;){let r=n.charCodeAt(o++);if(r&4294967168)if(!(r&4294965248))e[s++]=r>>6&31|192;else{if(r>=55296&&r<=56319&&o<i){const d=n.charCodeAt(o);(d&64512)===56320&&(++o,r=((r&1023)<<10)+(d&1023)+65536)}r&4294901760?(e[s++]=r>>18&7|240,e[s++]=r>>12&63|128,e[s++]=r>>6&63|128):(e[s++]=r>>12&15|224,e[s++]=r>>6&63|128)}else{e[s++]=r;continue}e[s++]=r&63|128}}const pt=new TextEncoder,ut=50;function ft(n,e,t){pt.encodeInto(n,e.subarray(t))}function wt(n,e,t){n.length>ut?ft(n,e,t):ht(n,e,t)}const gt=4096;function Ke(n,e,t){let i=e;const s=i+t,o=[];let r="";for(;i<s;){const d=n[i++];if(!(d&128))o.push(d);else if((d&224)===192){const h=n[i++]&63;o.push((d&31)<<6|h)}else if((d&240)===224){const h=n[i++]&63,u=n[i++]&63;o.push((d&31)<<12|h<<6|u)}else if((d&248)===240){const h=n[i++]&63,u=n[i++]&63,x=n[i++]&63;let p=(d&7)<<18|h<<12|u<<6|x;p>65535&&(p-=65536,o.push(p>>>10&1023|55296),p=56320|p&1023),o.push(p)}else o.push(d);o.length>=gt&&(r+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(r+=String.fromCharCode(...o)),r}const yt=new TextDecoder,xt=200;function bt(n,e,t){const i=n.subarray(e,e+t);return yt.decode(i)}function mt(n,e,t){return t>xt?bt(n,e,t):Ke(n,e,t)}class oe{constructor(e,t){a(this,"type");a(this,"data");this.type=e,this.data=t}}class D extends Error{constructor(e){super(e);const t=Object.create(D.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:D.name})}}const Z=4294967295;function vt(n,e,t){const i=t/4294967296,s=t;n.setUint32(e,i),n.setUint32(e+4,s)}function Le(n,e,t){const i=Math.floor(t/4294967296),s=t;n.setUint32(e,i),n.setUint32(e+4,s)}function Me(n,e){const t=n.getInt32(e),i=n.getUint32(e+4);return t*4294967296+i}function kt(n,e){const t=n.getUint32(e),i=n.getUint32(e+4);return t*4294967296+i}const St=-1,Ct=4294967296-1,It=17179869184-1;function Et({sec:n,nsec:e}){if(n>=0&&e>=0&&n<=It)if(e===0&&n<=Ct){const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n),t}else{const t=n/4294967296,i=n&4294967295,s=new Uint8Array(8),o=new DataView(s.buffer);return o.setUint32(0,e<<2|t&3),o.setUint32(4,i),s}else{const t=new Uint8Array(12),i=new DataView(t.buffer);return i.setUint32(0,e),Le(i,4,n),t}}function Tt(n){const e=n.getTime(),t=Math.floor(e/1e3),i=(e-t*1e3)*1e6,s=Math.floor(i/1e9);return{sec:t+s,nsec:i-s*1e9}}function Pt(n){if(n instanceof Date){const e=Tt(n);return Et(e)}else return null}function Ut(n){const e=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const t=e.getUint32(0),i=e.getUint32(4),s=(t&3)*4294967296+i,o=t>>>2;return{sec:s,nsec:o}}case 12:{const t=Me(e,4),i=e.getUint32(0);return{sec:t,nsec:i}}default:throw new D(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${n.length}`)}}function At(n){const e=Ut(n);return new Date(e.sec*1e3+e.nsec/1e6)}const Bt={type:St,encode:Pt,decode:At},le=class le{constructor(){a(this,"__brand");a(this,"builtInEncoders",[]);a(this,"builtInDecoders",[]);a(this,"encoders",[]);a(this,"decoders",[]);this.register(Bt)}register({type:e,encode:t,decode:i}){if(e>=0)this.encoders[e]=t,this.decoders[e]=i;else{const s=-1-e;this.builtInEncoders[s]=t,this.builtInDecoders[s]=i}}tryToEncode(e,t){for(let i=0;i<this.builtInEncoders.length;i++){const s=this.builtInEncoders[i];if(s!=null){const o=s(e,t);if(o!=null){const r=-1-i;return new oe(r,o)}}}for(let i=0;i<this.encoders.length;i++){const s=this.encoders[i];if(s!=null){const o=s(e,t);if(o!=null){const r=i;return new oe(r,o)}}}return e instanceof oe?e:null}decode(e,t,i){const s=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return s?s(e,t,i):new oe(t,e)}};a(le,"defaultCodec",new le);let re=le;function Kt(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function ge(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):Kt(n)?new Uint8Array(n):Uint8Array.from(n)}const Lt=100,Mt=2048;class ye{constructor(e){a(this,"extensionCodec");a(this,"context");a(this,"useBigInt64");a(this,"maxDepth");a(this,"initialBufferSize");a(this,"sortKeys");a(this,"forceFloat32");a(this,"ignoreUndefined");a(this,"forceIntegerToFloat");a(this,"pos");a(this,"view");a(this,"bytes");a(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??re.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)??Lt,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??Mt,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 ye({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,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);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,t)}ensureBufferSizeToWrite(e){const t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){const t=new ArrayBuffer(e),i=new Uint8Array(t),s=new DataView(t);i.set(this.bytes),this.view=s,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=dt(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),wt(e,this.bytes,this.pos),this.pos+=i}encodeObject(e,t){const i=this.extensionCodec.tryToEncode(e,this.context);if(i!=null)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);const i=ge(e);this.writeU8a(i)}encodeArray(e,t){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 s of e)this.doEncode(s,t+1)}countWithoutUndefined(e,t){let i=0;for(const s of t)e[s]!==void 0&&i++;return i}encodeMap(e,t){const i=Object.keys(e);this.sortKeys&&i.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const o of i){const r=e[o];this.ignoreUndefined&&r===void 0||(this.encodeString(o),this.doEncode(r,t+1))}}encodeExtension(e){if(typeof e.data=="function"){const i=e.data(this.pos+6),s=i.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(i);return}const t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}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),vt(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Le(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 zt(n,e){return new ye(e).encodeSharedRef(n)}function xe(n){return`${n<0?"-":""}0x${Math.abs(n).toString(16).padStart(2,"0")}`}const Dt=16,$t=16;class Rt{constructor(e=Dt,t=$t){a(this,"hit",0);a(this,"miss",0);a(this,"caches");a(this,"maxKeyLength");a(this,"maxLengthPerKey");this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let i=0;i<this.maxKeyLength;i++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,i){const s=this.caches[i-1];e:for(const o of s){const r=o.bytes;for(let d=0;d<i;d++)if(r[d]!==e[t+d])continue e;return o.str}return null}store(e,t){const i=this.caches[e.length-1],s={bytes:e,str:t};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=s:i.push(s)}decode(e,t,i){const s=this.find(e,t,i);if(s!=null)return this.hit++,s;this.miss++;const o=Ke(e,t,i),r=Uint8Array.prototype.slice.call(e,t,t+i);return this.store(r,o),o}}const be="array",Q="map_key",ze="map_value",_t=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new D("The type of key must be string or number but "+typeof n)};class Ht{constructor(){a(this,"stack",[]);a(this,"stackHeadPosition",-1)}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const t=this.getUninitializedStateFromPool();t.type=be,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=Q,t.readCount=0,t.size=e,t.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===be){const i=e;i.size=0,i.array=void 0,i.position=0,i.type=void 0}if(e.type===Q||e.type===ze){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 ee=-1,me=new DataView(new ArrayBuffer(0)),jt=new Uint8Array(me.buffer);try{me.getInt8(0)}catch(n){if(!(n 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 De=new RangeError("Insufficient data"),Ft=new Rt;class ve{constructor(e){a(this,"extensionCodec");a(this,"context");a(this,"useBigInt64");a(this,"rawStrings");a(this,"maxStrLength");a(this,"maxBinLength");a(this,"maxArrayLength");a(this,"maxMapLength");a(this,"maxExtLength");a(this,"keyDecoder");a(this,"mapKeyConverter");a(this,"totalPos",0);a(this,"pos",0);a(this,"view",me);a(this,"bytes",jt);a(this,"headByte",ee);a(this,"stack",new Ht);a(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??re.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)??Z,this.maxBinLength=(e==null?void 0:e.maxBinLength)??Z,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??Z,this.maxMapLength=(e==null?void 0:e.maxMapLength)??Z,this.maxExtLength=(e==null?void 0:e.maxExtLength)??Z,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:Ft,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??_t}clone(){return new ve({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=ee,this.stack.reset()}setBuffer(e){const t=ge(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===ee&&!this.hasRemaining(1))this.setBuffer(e);else{const t=this.bytes.subarray(this.pos),i=ge(e),s=new Uint8Array(t.length+i.length);s.set(t),s.set(i,t.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:t,pos:i}=this;return new RangeError(`Extra ${t.byteLength-i} of ${t.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 t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}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 t=!1,i;for await(const d of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(d);try{i=this.doDecodeSync(),t=!0}catch(h){if(!(h instanceof RangeError))throw h}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return i}const{headByte:s,pos:o,totalPos:r}=this;throw new RangeError(`Insufficient data in parsing ${xe(s)} at ${r} (${o} 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,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let i=t,s=-1;for await(const o of e){if(t&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),i&&(s=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==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 t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else{const s=e-160;t=this.decodeString(s,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){const s=this.lookU8();t=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();t=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();t=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e===196){const s=this.lookU8();t=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();t=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();t=this.decodeBinary(s,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();t=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();t=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();t=this.decodeExtension(s,4)}else throw new D(`Unrecognized type byte: ${xe(e)}`);this.complete();const i=this.stack;for(;i.length>0;){const s=i.top();if(s.type===be)if(s.array[s.position]=t,s.position++,s.position===s.size)t=s.array,i.release(s);else continue e;else if(s.type===Q){if(t==="__proto__")throw new D("The key __proto__ is not allowed");s.key=this.mapKeyConverter(t),s.type=ze;continue e}else if(s.map[s.key]=t,s.readCount++,s.readCount===s.size)t=s.map,i.release(s);else{s.key=null,s.type=Q;continue e}}return t}}readHeadByte(){return this.headByte===ee&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=ee}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 D(`Unrecognized array type byte: ${xe(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new D(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new D(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){var o;if(e>this.maxStrLength)throw new D(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw De;const i=this.pos+t;let s;return this.stateIsMapKey()&&((o=this.keyDecoder)!=null&&o.canBeCached(e))?s=this.keyDecoder.decode(this.bytes,i,e):s=mt(this.bytes,i,e),this.pos+=t+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Q:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new D(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw De;const i=this.pos+t,s=this.bytes.subarray(i,i+e);return this.pos+=t+e,s}decodeExtension(e,t){if(e>this.maxExtLength)throw new D(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const i=this.view.getInt8(this.pos+t),s=this.decodeBinary(e,t+1);return this.extensionCodec.decode(s,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=kt(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Me(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 qt(n,e){return new ve(e).decode(n)}const Ot=new Set(["auth","open","send","sync","history","read","typing","react","edit","delete","invoke","pubkey","ping","annotate","annotate_clear","uploadPrekeys","fetchPrekey","assign","tag","note","agent_status","subscribe_inbox","unsubscribe_inbox"]);function Nt(n){return Ot.has(n.type)}function Wt(n){return zt(n)}function Vt(n){let e;try{e=qt(n)}catch{return null}return typeof e!="object"||e===null||typeof e.type!="string"?null:e}class Xt{constructor(e){a(this,"conversationId");a(this,"state","");a(this,"version",0);a(this,"hasMoreHistory",!1);a(this,"lastReadByOthers",0);a(this,"assignedAgentId");a(this,"accent");a(this,"subject");a(this,"name");a(this,"e2e",!1);a(this,"offline",!1);a(this,"offlineMessage","");a(this,"launcherMessage",null);a(this,"preChat",null);a(this,"whiteLabel",!1);a(this,"typing",new Set);a(this,"online",new Set);a(this,"annotations",[]);a(this,"annotationVersion",0);a(this,"sentiment");a(this,"sentimentScore");a(this,"actions",[]);a(this,"byId",new Map);a(this,"keyByClient",new Map);a(this,"_maxSeq",0);a(this,"_sorted",null);this.me=e}messages(){return this._sorted||(this._sorted=[...this.byId.values()].sort((e,t)=>{const i=e.status==="pending",s=t.status==="pending";return i!==s?i?1:-1:i&&s?e.ts-t.ts:e.seq-t.seq})),this._sorted}visibleActions(){return this.actions.filter(e=>!e.availableInStates||e.availableInStates.includes(this.state))}highestSeq(){return this._maxSeq}addOptimistic(e,t){const i={id:e,conversationId:this.conversationId,seq:0,senderId:this.me,senderRole:"guest",content:t,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 t;switch(e.type){case"opened":this.conversationId=e.conversation.id,this.state=e.conversation.state,e.subject&&(this.subject=e.subject),e.annotations&&(this.annotations=e.annotations,this.annotationVersion++);return;case"manifest":this.actions=e.actions,this.version=e.version,e.name&&(this.name=e.name),(t=e.theme)!=null&&t.accent&&(this.accent=e.theme.accent),e.e2e&&(this.e2e=!0),e.offline&&(this.offline=!0),e.offlineMessage&&(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),s=i?this.byId.get(i):void 0;if(s&&i){this.byId.delete(i);const o={...s,id:e.messageId,seq:e.seq,ts:e.ts,status:"sent"};this.byId.set(e.messageId,o),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 s={...i.reactions??{}},o=(s[e.emoji]??[]).filter(r=>r!==e.by);e.removed||o.push(e.by),o.length?s[e.emoji]=o:delete s[e.emoji],this.byId.set(e.messageId,{...i,reactions:s}),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"annotation":this.annotations=[...this.annotations,e.stroke],this.annotationVersion++;return;case"annotation_clear":this.annotations=[],this.annotationVersion++;return;case"sentiment":this.sentiment=e.label,this.sentimentScore=e.score;return;default:return}}upsert(e){const t=this.byId.get(e.id);this.byId.set(e.id,t?{...t,...e}:e),e.seq>this._maxSeq&&(this._maxSeq=e.seq),this._sorted=null}markOwnStatus(e,t){const i=$e(t);let s=!1;for(const[o,r]of this.byId)r.senderId!==this.me||r.seq<=0||r.seq>e||$e(r.status)>=i||(this.byId.set(o,{...r,status:t}),s=!0);s&&(this._sorted=null)}}function $e(n){switch(n){case"read":return 3;case"delivered":return 2;case"sent":return 1;default:return 0}}const Re="http://www.w3.org/2000/svg",Yt=8e3;class Gt{constructor(){a(this,"svg",null);a(this,"timers",new Set)}apply(e){var t;if(e.type==="annotation")this.draw(e.stroke);else if(e.type==="annotation_clear")this.clear();else if(e.type==="opened"&&((t=e.annotations)!=null&&t.length))for(const i of e.annotations)this.draw(i)}ensureSvg(){var t;if((t=this.svg)!=null&&t.isConnected)return this.svg;const e=document.createElementNS(Re,"svg");return e.setAttribute("data-relay-annotations",""),e.setAttribute("aria-hidden","true"),e.setAttribute("style","position:fixed;inset:0;width:100vw;height:100vh;pointer-events:none;z-index:2147483000;"),document.body.append(e),this.svg=e,e}draw(e){var d;if(typeof document>"u"||!((d=e.points)!=null&&d.length))return;const t=this.ensureSvg(),i=window.innerWidth,s=window.innerHeight,o=document.createElementNS(Re,"polyline");o.setAttribute("points",e.points.map(h=>`${(h.x*i).toFixed(1)},${(h.y*s).toFixed(1)}`).join(" ")),o.setAttribute("fill","none"),o.setAttribute("stroke",e.color||"#ff3b30"),o.setAttribute("stroke-width",String(e.width||3)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("data-stroke-id",e.id),t.append(o);const r=setTimeout(()=>{o.style.transition="opacity 600ms",o.style.opacity="0";const h=setTimeout(()=>{o.remove(),this.timers.delete(h)},650);this.timers.add(h),this.timers.delete(r)},Yt);this.timers.add(r)}clear(){var e;(e=this.svg)==null||e.replaceChildren()}destroy(){var e;for(const t of this.timers)clearTimeout(t);this.timers.clear(),(e=this.svg)==null||e.remove(),this.svg=null}}class Jt{constructor(e){a(this,"socket",null);a(this,"state","idle");a(this,"authed",!1);a(this,"everAuthed",!1);a(this,"attempt",0);a(this,"outbox",[]);a(this,"stopped",!1);a(this,"timer",null);a(this,"refreshing",!1);this.opts=e}connect(){var i,s;if(this.state==="connecting"||this.state==="open")return;this.stopped=!1,this.state="connecting",this.authed=!1,(s=(i=this.opts).onStatusChange)==null||s.call(i,this.attempt>0?"reconnecting":"connecting");const t=(this.opts.socketFactory??en)(this.opts.url);t.binaryType="arraybuffer",this.socket=t,t.onopen=()=>{this.raw({type:"auth",token:this.opts.token})},t.onmessage=o=>{const r=Vt(new Uint8Array(o.data));!r||Nt(r)||this.handle(r)},t.onclose=()=>this.onClosed(),t.onerror=()=>{try{t.close()}catch{}}}send(e){if(this.state==="open"&&this.authed){this.raw(e);return}const t=this.opts.maxOutbox??1e3;this.outbox.length>=t&&(this.outbox=this.outbox.slice(this.outbox.length-(t>>1))),this.outbox.push(e)}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 t,i,s,o;if(e.type==="authed"&&(this.attempt=0,this.state="open",this.authed=!0,this.everAuthed=!0,(i=(t=this.opts).onStatusChange)==null||i.call(t,"open"),this.raw(this.opts.open),this.flush()),e.type==="opened"&&this.raw({type:"sync",conversationId:e.conversation.id,sinceSeq:this.opts.getCursor()}),e.type==="error"&&Zt.has(e.code)){if(e.code==="UNAUTHORIZED"&&this.opts.refreshToken&&!this.refreshing){this.refreshing=!0,(o=(s=this.opts).onStatusChange)==null||o.call(s,"reconnecting","Renewing session…"),this.opts.refreshToken().then(r=>{var d;if(this.refreshing=!1,!r){this.fatal(e);return}this.opts.token=r;try{(d=this.socket)==null||d.close()}catch{}}).catch(()=>{this.refreshing=!1,this.fatal(e)});return}this.fatal(e);return}this.opts.onFrame(e)}fatal(e){var t,i,s;this.stopped=!0;try{(t=this.socket)==null||t.close()}catch{}this.state="closed",(s=(i=this.opts).onStatusChange)==null||s.call(i,"error",Qt(e.code)),this.opts.onFrame(e)}flush(){const e=this.outbox;this.outbox=[];for(const t of e)this.raw(t)}raw(e){var t;try{(t=this.socket)==null||t.send(Wt(e))}catch{this.outbox.push(e)}}onClosed(){var s,o;if(this.authed=!1,this.socket=null,this.stopped){this.state="closed";return}this.state="idle";const e=this.opts.backoffBaseMs??500,t=this.opts.backoffMaxMs??15e3,i=Math.min(t,e*2**this.attempt)*(.5+Math.random()*.5);this.attempt++,this.attempt>=3&&!this.everAuthed&&((o=(s=this.opts).onStatusChange)==null||o.call(s,"reconnecting","Can't reach chat — retrying…")),this.timer=setTimeout(()=>this.connect(),i)}}const Zt=new Set(["UNAUTHORIZED"]);function Qt(n){switch(n){case"UNAUTHORIZED":return"Chat unavailable — sign-in/token was rejected";default:return"Chat unavailable"}}function en(n){return new WebSocket(n)}const _e=200,tn=7*864e5;class nn{constructor(e){a(this,"key");this.key=`ocw_outbox_${e}`}load(){try{const e=localStorage.getItem(this.key);if(!e)return[];const t=JSON.parse(e),i=Date.now()-tn,s=t.filter(o=>o.ts>=i);return s.length!==t.length&&this.save(s),s}catch{return[]}}add(e){try{const t=this.load();t.push(e),this.save(t.length>_e?t.slice(t.length-_e):t)}catch{}}remove(e){try{const t=this.load().filter(i=>i.clientMsgId!==e);this.save(t)}catch{}}save(e){try{localStorage.setItem(this.key,JSON.stringify(e))}catch{}}}const T=()=>globalThis.crypto.subtle;function ae(n){const e=n instanceof Uint8Array?n:new Uint8Array(n);let t="";for(const i of e)t+=String.fromCharCode(i);return btoa(t)}function ke(n){const e=atob(n),t=new ArrayBuffer(e.length),i=new Uint8Array(t);for(let s=0;s<e.length;s++)i[s]=e.charCodeAt(s);return i}async function te(){const n=await T().generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]);return{publicKey:n.publicKey,privateKey:n.privateKey}}async function N(n){return ae(await T().exportKey("raw",n))}async function Y(n){return T().importKey("raw",ke(n),{name:"ECDH",namedCurve:"P-256"},!1,[])}async function sn(n,e){const t=await Y(e);return T().deriveKey({name:"ECDH",public:t},n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function on(n,e){const t=globalThis.crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(e),s=await T().encrypt({name:"AES-GCM",iv:t},n,i);return{ct:ae(s),iv:ae(t)}}async function rn(n,e,t){const i=await T().decrypt({name:"AES-GCM",iv:ke(t)},n,ke(e));return new TextDecoder().decode(i)}async function an(n){var t,i;try{const s=(t=globalThis.localStorage)==null?void 0:t.getItem(n);if(s){const{pub:o,priv:r}=JSON.parse(s),d=await T().importKey("jwk",o,{name:"ECDH",namedCurve:"P-256"},!0,[]),h=await T().importKey("jwk",r,{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]);return{publicKey:d,privateKey:h}}}catch{}const e=await te();try{const s=await T().exportKey("jwk",e.publicKey),o=await T().exportKey("jwk",e.privateKey);(i=globalThis.localStorage)==null||i.setItem(n,JSON.stringify({pub:s,priv:o}))}catch{}return e}async function cn(n,e){const t=await T().exportKey("raw",e),i=await T().sign({name:"ECDSA",hash:"SHA-256"},n,t);return ae(i)}async function ln(){const n=await te(),e=await T().generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]);return{ecdhKP:n,ecdsaKP:{publicKey:e.publicKey,privateKey:e.privateKey},publicKeyB64:await N(n.publicKey),sigPublicKeyB64:await N(e.publicKey)}}async function He(n){var t,i;try{const s=(t=globalThis.localStorage)==null?void 0:t.getItem(`${n}-identity`);if(s){const o=JSON.parse(s),r=await T().importKey("jwk",o.ecdhPub,{name:"ECDH",namedCurve:"P-256"},!0,[]),d=await T().importKey("jwk",o.ecdhPriv,{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]),h=await T().importKey("jwk",o.ecdsaPub,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),u=await T().importKey("jwk",o.ecdsaPriv,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"]);return{ecdhKP:{publicKey:r,privateKey:d},ecdsaKP:{publicKey:h,privateKey:u},publicKeyB64:await N(r),sigPublicKeyB64:await N(h)}}}catch{}const e=await ln();try{const s=await T().exportKey("jwk",e.ecdhKP.publicKey),o=await T().exportKey("jwk",e.ecdhKP.privateKey),r=await T().exportKey("jwk",e.ecdsaKP.publicKey),d=await T().exportKey("jwk",e.ecdsaKP.privateKey);(i=globalThis.localStorage)==null||i.setItem(`${n}-identity`,JSON.stringify({ecdhPub:s,ecdhPriv:o,ecdsaPub:r,ecdsaPriv:d}))}catch{}return e}async function dn(n,e){const t=await te(),i=await N(t.publicKey),s=await Y(e.identityKey),o=await Y(e.signedPrekey),r=e.oneTimePrekey?await Y(e.oneTimePrekey):null,d=await W(n.privateKey,o),h=await W(t.privateKey,s),u=await W(t.privateKey,o),x=r?await W(t.privateKey,r):null,p=je(d,h,u,...x?[x]:[]);return{sharedKey:await Fe(p),ephemeralPublicKey:i}}async function hn(n,e,t,i,s){const o=await Y(t),r=await Y(i),d=await W(e.privateKey,o),h=await W(n.privateKey,r),u=await W(e.privateKey,r),x=s?await W(s.privateKey,r):null,p=je(d,h,u,...x?[x]:[]);return Fe(p)}async function W(n,e){return T().deriveBits({name:"ECDH",public:e},n,256)}function je(...n){const e=n.reduce((s,o)=>s+o.byteLength,0),t=new Uint8Array(e);let i=0;for(const s of n)t.set(new Uint8Array(s),i),i+=s.byteLength;return t.buffer}async function Fe(n){const e=await T().importKey("raw",n,"HKDF",!1,["deriveKey"]);return T().deriveKey({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(32),info:new TextEncoder().encode("ObjectChat X3DH v1")},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}const pn=20;class un{constructor(e){a(this,"kp");a(this,"shared");a(this,"identityKP");a(this,"signedPreKP");a(this,"signedPrekeyId");a(this,"otpKeys",[]);a(this,"x3dhShared");a(this,"pendingX3DH");this.storageKey=e}get ready(){return!!(this.shared??this.x3dhShared)}async begin(){return this.kp=await an(this.storageKey),N(this.kp.publicKey)}async onPeerKey(e){this.kp&&(this.shared=await sn(this.kp.privateKey,e))}async initX3DH(){this.identityKP=await He(this.storageKey),this.signedPreKP=await te(),this.signedPrekeyId=`spk-${Date.now()}-${Math.random().toString(36).slice(2)}`;for(let s=0;s<pn;s++)this.otpKeys.push(await te());const e=await N(this.signedPreKP.publicKey),t=await cn(this.identityKP.ecdsaKP.privateKey,this.signedPreKP.publicKey),i=await Promise.all(this.otpKeys.map(s=>N(s.publicKey)));return{identityKey:this.identityKP.publicKeyB64,signedPrekey:e,signedPrekeyId:this.signedPrekeyId,signature:t,oneTimePrekeys:i}}async x3dhSendTo(e){this.identityKP||(this.identityKP=await He(this.storageKey));const{sharedKey:t,ephemeralPublicKey:i}=await dn(this.identityKP.ecdhKP,e);return this.x3dhShared=t,{ephemeralKey:i,spkId:e.signedPrekeyId,usedOTP:!!e.oneTimePrekey,senderIK:this.identityKP.publicKeyB64}}async x3dhReceiveFrom(e,t,i){if(!this.identityKP||!this.signedPreKP){this.pendingX3DH={senderIK:e,ephemeralKey:t,spkId:i};return}const s=this.otpKeys.shift();this.x3dhShared=await hn(this.identityKP.ecdhKP,this.signedPreKP,e,t,s)}async flushPendingX3DH(){if(!this.pendingX3DH)return;const{senderIK:e,ephemeralKey:t,spkId:i}=this.pendingX3DH;this.pendingX3DH=void 0,await this.x3dhReceiveFrom(e,t,i)}async sealText(e,t){const i=this.x3dhShared??this.shared;if(!i)throw new Error("secure channel not ready");const{ct:s,iv:o}=await on(i,e);return{kind:"text",text:s,enc:!0,iv:o,...t?{x3dhEK:t.ephemeralKey,x3dhSPK:t.spkId,x3dhIK:t.senderIK}:{}}}async openContent(e){if(e.kind!=="text"||!e.enc||!e.iv)return e;const t=this.x3dhShared??this.shared;if(!t)return{kind:"text",text:"🔒 encrypted"};try{return{kind:"text",text:await rn(t,e.text,e.iv)}}catch{return{kind:"text",text:"🔒 unable to decrypt"}}}async openFrame(e){if(e.type==="message")e.message.content=await this.openContent(e.message.content);else if(e.type==="sync")for(const t of e.messages)t.content=await this.openContent(t.content)}}function fn(n){if(n.kind!=="text"||!n.enc)return null;const e=n;return!e.x3dhEK||!e.x3dhSPK||!e.x3dhIK?null:{x3dhEK:e.x3dhEK,x3dhSPK:e.x3dhSPK,x3dhIK:e.x3dhIK}}const qe="objectchat-widget-styles",wn=["👍","❤️","😂","😮","😢","🙏"],gn=400,yn='<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>',xn=`
2
2
  .ocw { --ocw-accent:#4F63F5; --ocw-bg:#f3efe9; --ocw-card:#fff; --ocw-line:#ececec; --ocw-ink:#1c1b1a; --ocw-mut:#9b9690;
3
3
  position:relative;
4
4
  display:flex; flex-direction:column; height:100%; min-height:320px; background:var(--ocw-bg);
5
5
  font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif; color:var(--ocw-ink); overflow:hidden; }
6
- @media (max-width:480px) {
7
- .ocw { min-height:100dvh; border-radius:0 !important; }
8
- .ocw-bubble { font-size:15px; }
9
- .ocw-input textarea { font-size:16px; } /* prevent iOS zoom on focus */
10
- .ocw-chip { padding:9px 14px; font-size:14px; }
11
- .ocw-modal-card { width:90%; }
12
- .ocw-row { max-width:94%; }
13
- }
6
+ /* ── Responsive sizing ──────────────────────────────────────────────────────
7
+ * Sizing is driven by the WIDGET'S OWN width (ResizeObserver toggles
8
+ * .ocw-compact below 400px), not the viewport — so a widget embedded in a
9
+ * narrow desktop sidebar sizes the same as one on a phone, and a tablet in
10
+ * landscape keeps comfortable desktop sizing. A viewport query alone can't
11
+ * see the container. Fullscreen (launcher on mobile) additionally gets
12
+ * .ocw-fs from the launcher, which is the only case that should remove the
13
+ * corner radius — an INLINE embed on a phone must NOT take over the page
14
+ * (the old blanket min-height:100dvh rule did exactly that). */
15
+ .ocw.ocw-fs { border-radius:0 !important; }
16
+ .ocw-compact .ocw-bubble { font-size:15px; }
17
+ .ocw-compact.ocw .ocw-input textarea { font-size:16px; } /* ≥16px prevents iOS zoom on focus */
18
+ .ocw-compact .ocw-chip { padding:9px 14px; font-size:14px; }
19
+ .ocw-compact .ocw-modal-card { width:90%; }
20
+ .ocw-compact .ocw-row { max-width:94%; }
21
+ .ocw-compact .ocw-sendbtn { min-width:44px; height:44px; }
22
+ .ocw-compact .ocw-back { width:34px; height:34px; }
23
+ .ocw-compact .ocw-quick button { padding:9px 15px; font-size:14px; }
14
24
  /* RTL support: when the host element has dir=rtl, flip layout direction */
15
25
  [dir="rtl"] .ocw-row.mine { flex-direction:row; }
16
26
  [dir="rtl"] .ocw-row.theirs { flex-direction:row-reverse; }
@@ -59,7 +69,6 @@ var RelayEmbed=function(R){"use strict";var Sn=Object.defineProperty;var Cn=(R,D
59
69
  .ocw-react-pill { display:inline-flex; align-items:center; gap:3px; border:1px solid #e3ded7; border-radius:999px; padding:2px 7px; background:#fff; font-size:12px; cursor:pointer; }
60
70
  .ocw-react-pill:hover { border-color:var(--ocw-accent); }
61
71
  .ocw-react-pill.mine { border-color:var(--ocw-accent); background:#fff8f5; }
62
- .ocw-react-add { display:none; position:absolute; bottom:100%; left:0; margin-bottom:4px; background:#fff; border:1px solid #e3ded7; border-radius:14px; padding:6px 8px; box-shadow:0 4px 16px rgba(0,0,0,.12); display:flex; gap:4px; z-index:10; }
63
72
  .ocw-react-wrap { position:relative; }
64
73
  .ocw-react-wrap:not(:hover) .ocw-react-picker { display:none; }
65
74
  .ocw-react-picker { position:absolute; bottom:calc(100% + 4px); left:0; background:#fff; border:1px solid #e3ded7; border-radius:14px; padding:6px 8px; box-shadow:0 4px 16px rgba(0,0,0,.12); display:flex; gap:4px; z-index:10; white-space:nowrap; }
@@ -148,10 +157,19 @@ var RelayEmbed=function(R){"use strict";var Sn=Object.defineProperty;var Cn=(R,D
148
157
  .ocw-footer a:hover { color:var(--ocw-accent); }
149
158
  .ocw-attach { background:none;border:none;cursor:pointer;font-size:18px;padding:4px 6px;opacity:.6;flex-none; }
150
159
  .ocw-attach:hover { opacity:1; }
151
- .ocw-input textarea { flex:1; resize:none; border:1px solid #e3ded7; border-radius:22px; padding:11px 16px; font:inherit; font-size:14px; background:#fff; outline:none; max-height:96px; }
160
+ .ocw-input textarea { flex:1; min-width:0; resize:none; border:1px solid #e3ded7; border-radius:22px; padding:11px 16px; font:inherit; font-size:14px; line-height:1.4; background:#fff; outline:none; max-height:120px; overflow-y:auto; }
152
161
  .ocw-input textarea:focus { border-color:var(--ocw-accent); }
153
- .ocw-sendbtn { width:42px; height:42px; border-radius:50%; border:none; background:var(--ocw-accent); color:#fff; font-size:18px; cursor:pointer; flex:none; display:flex; align-items:center; justify-content:center; }
162
+ /* Send button auto-sizes to its label: the default is a fixed circle around an
163
+ * inline SVG; a TEXT label (i18n.send: "Send", "보내기", "Enviar"…) switches to
164
+ * .ocw-sendbtn-label — a pill whose width follows the text. A fixed 42px
165
+ * circle with 18px type overflowed the moment anyone localized the label. */
166
+ .ocw-sendbtn { min-width:42px; height:42px; border-radius:999px; border:none; background:var(--ocw-accent); color:#fff; font:inherit; font-size:14px; font-weight:600; cursor:pointer; flex:none; display:flex; align-items:center; justify-content:center; padding:0; transition:opacity .15s, transform .1s; }
167
+ .ocw-sendbtn-label { padding:0 16px; white-space:nowrap; }
168
+ .ocw-sendbtn svg { width:19px; height:19px; display:block; }
169
+ .ocw-sendbtn:not(:disabled):hover { transform:scale(1.05); }
170
+ .ocw-sendbtn:not(:disabled):active { transform:scale(.96); }
154
171
  .ocw-sendbtn:disabled { opacity:.5; cursor:default; }
172
+ .ocw-sendbtn:focus-visible, .ocw-back:focus-visible, .ocw-chip:focus-visible { outline:2px solid var(--ocw-accent); outline-offset:2px; }
155
173
  .ocw-cobrowse-btn { display:none; }
156
174
  .ocw-cobrowse-btn.show { display:inline-flex; }
157
175
  .ocw-cobrowse-btn.on { color:var(--ocw-accent); border-color:var(--ocw-accent); }
@@ -170,8 +188,8 @@ var RelayEmbed=function(R){"use strict";var Sn=Object.defineProperty;var Cn=(R,D
170
188
  .ocw-row.theirs .ocw-translate-btn { right:auto; left:-26px; }
171
189
  .ocw-bubble-wrap:hover .ocw-translate-btn { opacity:1; }
172
190
  .ocw-translated-tag { font-size:10px; color:var(--ocw-mut); margin-top:2px; }
173
- `;function en(){if(typeof document>"u"||document.getElementById(Ae))return;const i=document.createElement("style");i.id=Ae,i.textContent=Qt,document.head.appendChild(i)}function c(i,e,t){const n=document.createElement(i);return e&&(n.className=e),t!==void 0&&(n.textContent=t),n}function tn(i){try{return new Date(i).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function ye(i){var e;switch(i.kind){case"text":return i.text;case"system":return typeof((e=i.data)==null?void 0:e.message)=="string"?String(i.data.message):i.event;case"card":return[i.title,i.body].filter(Boolean).join(" — ");case"attachment":return i.name??i.url;case"form":return i.prompt;case"appointment":return`📅 ${i.title} — ${new Date(i.startIso).toLocaleString()}`}}class nn{constructor(e,t,n,s={}){a(this,"scroll");a(this,"chips");a(this,"typing");a(this,"quick");a(this,"formHost");a(this,"csatPanel");a(this,"offlinePanel");a(this,"preChatPanel");a(this,"deflectPanel");a(this,"preChatBuilt",!1);a(this,"preChatDone",!1);a(this,"footer");a(this,"input");a(this,"subjectCard");a(this,"e2eBadge");a(this,"statusBadge");a(this,"headerName");a(this,"connStatus");a(this,"typingTimer",null);a(this,"csatSubmitted",!1);a(this,"cobrowseBtn");a(this,"cobrowseCanvas");a(this,"cobrowseToolbar");a(this,"cobrowseHint");a(this,"cobrowseActive",!1);a(this,"cobrowseColor","#f5713c");a(this,"lastAnnotationVersion",-1);a(this,"storeRef",null);a(this,"scrollCleanup",null);a(this,"translationCache",new Map);a(this,"showingTranslation",new Set);a(this,"subjectBuilt",!1);var v,y,E,I,L,M,A,U,k;this.root=e,this.me=t,this.h=n,this.cfg=s,en(),e.replaceChildren(),e.classList.add("ocw"),s.accent&&e.style.setProperty("--ocw-accent",s.accent);const o=c("div","ocw-head");if(this.h.onBack){const b=c("button","ocw-back","‹");b.type="button",b.setAttribute("aria-label","Back"),b.addEventListener("click",()=>this.h.onBack()),o.append(b)}const r=c("div","ocw-avatar");if((v=s.userInfo)!=null&&v.avatar){const b=document.createElement("img");b.src=s.userInfo.avatar,b.alt=s.userInfo.name??"You",b.style.cssText="width:100%;height:100%;border-radius:50%;object-fit:cover",r.append(b)}else r.textContent=(y=s.userInfo)!=null&&y.name?s.userInfo.name[0].toUpperCase():"🧑";o.append(r);const h=c("div","ocw-head-main");this.headerName=c("div","ocw-head-name",((E=s.subject)==null?void 0:E.ownerLabel)??((I=s.subject)==null?void 0:I.title)??""),h.append(this.headerName),(L=s.subject)!=null&&L.subtitle&&h.append(c("div","ocw-head-meta",s.subject.subtitle)),o.append(h),this.statusBadge=c("span","ocw-badge",((M=s.subject)==null?void 0:M.status)??""),(A=s.subject)!=null&&A.status||(this.statusBadge.style.display="none"),o.append(this.statusBadge),this.e2eBadge=c("span","ocw-e2e","🔒 E2E"),this.e2eBadge.style.display="none",o.append(this.e2eBadge),this.connStatus=c("span","ocw-conn-status"),this.connStatus.style.display="none",o.append(this.connStatus),this.cobrowseBtn=c("button","ocw-menu ocw-cobrowse-btn","🖍"),this.cobrowseBtn.title="Shared whiteboard — draw to point things out together",this.cobrowseBtn.addEventListener("click",()=>{this.cobrowseActive=!this.cobrowseActive,this.updateCobrowseUI()}),o.append(this.cobrowseBtn),o.append(c("button","ocw-menu","⋯")),this.chips=c("div","ocw-chiprow"),this.scroll=c("div","ocw-scroll"),this.subjectCard=c("div","ocw-subject"),this.typing=c("div","ocw-typing");const p=c("div","ocw-typing-bubble");p.append(c("div","ocw-typing-dot"),c("div","ocw-typing-dot"),c("div","ocw-typing-dot")),this.typing.append(c("div","ocw-dot","🧑"),p),this.quick=c("div","ocw-quick");for(const b of s.quickReplies??[]){const T=c("button",void 0,b);T.addEventListener("click",()=>{this.h.onSend(b),this.quick.style.display="none"}),this.quick.append(T)}this.formHost=c("div","ocw-form-host"),this.csatPanel=c("div","ocw-csat"),this.csatPanel.style.display="none",this.offlinePanel=c("div","ocw-offline"),this.offlinePanel.style.display="none",this.preChatPanel=c("div","ocw-prechat"),this.preChatPanel.style.display="none",this.deflectPanel=c("div","ocw-deflect"),this.deflectPanel.style.display="none",this.input=c("textarea",void 0),this.input.rows=1,this.input.placeholder="Message…";const f=c("button","ocw-sendbtn",((U=s.i18n)==null?void 0:U.send)??"➤");f.addEventListener("click",()=>this.flushSend()),this.input.addEventListener("input",()=>{var b,T;this.storeRef&&!this.storeRef.messages().some(q=>q.senderRole==="guest")?(T=(b=this.h).onDeflectQuery)==null||T.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 g=c("button","ocw-attach","📎");g.title="Attach image or file";const l=document.createElement("input");l.type="file",l.accept="image/*,.pdf,.txt,.doc,.docx",l.style.display="none",g.addEventListener("click",()=>l.click()),l.addEventListener("change",()=>{var b;(b=l.files)!=null&&b[0]&&this.h.onAttach&&this.h.onAttach(l.files[0]),l.value=""});const x=c("div","ocw-input");x.append(g,l,this.input,f);const u=c("div","ocw-footer");((k=s.i18n)==null?void 0:k.poweredBy)!==void 0?u.textContent=s.i18n.poweredBy:u.innerHTML='Powered by <a href="https://relay.paramms.com" target="_blank" rel="noopener">Relay</a>',this.footer=u,e.append(o,this.chips,this.scroll,this.typing,this.quick,this.formHost,this.csatPanel,this.offlinePanel,this.preChatPanel,this.deflectPanel,x,this.footer),this.cobrowseCanvas=c("canvas","ocw-cobrowse-canvas"),this.cobrowseToolbar=c("div","ocw-cobrowse-toolbar");for(const b of["#f5713c","#1c1b1a","#2563eb","#16a34a","#dc2626"]){const T=c("button","ocw-cobrowse-swatch");T.style.background=b,T.type="button",b===this.cobrowseColor&&T.classList.add("sel"),T.addEventListener("click",()=>{this.cobrowseColor=b;for(const q of this.cobrowseToolbar.querySelectorAll(".ocw-cobrowse-swatch"))q.classList.remove("sel");T.classList.add("sel")}),this.cobrowseToolbar.append(T)}const S=c("button","ocw-cobrowse-clear","Clear");S.addEventListener("click",()=>{var b,T;return(T=(b=this.h).onAnnotateClear)==null?void 0:T.call(b)}),this.cobrowseToolbar.append(S),this.cobrowseHint=c("div","ocw-cobrowse-hint","🖍 Draw to point things out — visible to both sides"),e.append(this.cobrowseCanvas,this.cobrowseToolbar,this.cobrowseHint),this.bindCobrowsePointerEvents()}getScrollEl(){return this.scroll}setScrollCleanup(e){var t;(t=this.scrollCleanup)==null||t.call(this),this.scrollCleanup=e}destroy(){var e;(e=this.scrollCleanup)==null||e.call(this),this.scrollCleanup=null,this.typingTimer&&(clearTimeout(this.typingTimer),this.typingTimer=null)}flushSend(){this.hideDeflection();const e=this.input.value.trim();e&&(this.input.value="",this.h.onTyping(!1),this.h.onSend(e))}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)}render(e){var l,x,u,S,v;if(this.storeRef=e,this.cobrowseBtn.classList.toggle("show",!!e.subject),!e.subject&&this.cobrowseActive&&(this.cobrowseActive=!1,this.updateCobrowseUI()),this.cobrowseActive&&e.annotationVersion!==this.lastAnnotationVersion&&(this.lastAnnotationVersion=e.annotationVersion,this.resizeCobrowseCanvas(),this.redrawCobrowse()),e.accent&&this.root.style.setProperty("--ocw-accent",e.accent),this.e2eBadge.style.display=e.e2e?"inline-flex":"none",this.buildSubjectCard(e),e.subject){const y=(l=this.cfg.subject)==null?void 0:l.ownerLabel;y&&(this.headerName.textContent=y)}this.quick.style.display=e.messages().length===0?"flex":"none",this.chips.replaceChildren();const t=e.visibleActions();this.chips.style.display=t.length?"flex":"none";for(const y of t)this.chips.append(this.chipEl(y));const n=this.scroll.scrollHeight,s=this.scroll.scrollTop;if(this.scroll.replaceChildren(),this.subjectCard.childNodes.length&&this.scroll.append(this.subjectCard),e.hasMoreHistory){const y=c("div","ocw-load-more");y.textContent="↑ Loading earlier messages…",y.style.pointerEvents="none",this.scroll.append(y)}let o=0;for(const y of e.messages())this.scroll.append(this.messageEl(y,e)),y.senderId!==this.me&&y.seq>o&&(o=y.seq);s>20?this.scroll.scrollTop=this.scroll.scrollHeight-n+s:this.scroll.scrollTop=this.scroll.scrollHeight,o>0&&this.h.onReadUpTo(o);const r=[...e.typing];this.typing.classList.toggle("active",r.length>0);const h=this.typing.querySelector(".ocw-typing-bubble");h&&h.setAttribute("aria-label",r.length?"typing":""),this.footer.style.display=e.whiteLabel?"none":"block";const p=e.messages().some(y=>y.senderRole==="guest");!!((x=e.preChat)!=null&&x.enabled)&&!this.preChatDone&&!p&&(e.preChat.showWhen!=="offline"||e.offline)?(this.preChatBuilt||this.buildPreChatPanel(e.preChat),this.preChatPanel.style.display="block",this.offlinePanel.style.display="none",(u=this.root.querySelector(".ocw-input"))==null||u.style.setProperty("display","none")):(this.preChatPanel.style.display="none",e.offline?(this.offlinePanel.style.display==="none"&&this.buildOfflinePanel(e.offlineMessage),this.offlinePanel.style.display="block",(S=this.root.querySelector(".ocw-input"))==null||S.style.setProperty("display","none")):(this.offlinePanel.style.display="none",(v=this.root.querySelector(".ocw-input"))==null||v.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")}setConnStatus(e,t){if(e==="open"){this.connStatus.style.display="none";return}this.connStatus.style.display="";const n=e==="error";this.connStatus.className=`ocw-conn-status${n?" err":e==="reconnecting"?" warn":""}`,this.connStatus.textContent=n?`⚠ ${t??"Chat unavailable"}`:e==="reconnecting"?t??"↻ reconnecting…":"● connecting…"}buildOfflinePanel(e){var h;this.offlinePanel.replaceChildren(),this.offlinePanel.append(c("div","ocw-offline-icon","🌙")),this.offlinePanel.append(c("div","ocw-offline-title",((h=this.cfg.i18n)==null?void 0:h.offline)??"We're offline right now")),this.offlinePanel.append(c("div","ocw-offline-msg",e||"Leave your details and we'll get back to you soon."));const t=c("div","ocw-offline-form"),n=c("input","ocw-offline-input");n.placeholder="Your name",n.type="text";const s=c("input","ocw-offline-input");s.placeholder="Your email",s.type="email";const o=c("textarea","ocw-offline-input");o.placeholder="Your message",o.rows=3;const r=c("button","ocw-offline-submit","Send message");r.addEventListener("click",()=>{!s.value.trim()||!o.value.trim()||(this.h.onSend(`[Offline form]
174
- Name: ${n.value||"Anonymous"}
191
+ `;function bn(){if(typeof document>"u"||document.getElementById(qe))return;const n=document.createElement("style");n.id=qe,n.textContent=xn,document.head.appendChild(n)}function c(n,e,t){const i=document.createElement(n);return e&&(i.className=e),t!==void 0&&(i.textContent=t),i}function mn(n){try{return new Date(n).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function Se(n){var e;switch(n.kind){case"text":return n.text;case"system":return typeof((e=n.data)==null?void 0:e.message)=="string"?String(n.data.message):n.event;case"card":return[n.title,n.body].filter(Boolean).join(" — ");case"attachment":return n.name??n.url;case"form":return n.prompt;case"appointment":return`📅 ${n.title} — ${new Date(n.startIso).toLocaleString()}`}}class vn{constructor(e,t,i,s={}){a(this,"scroll");a(this,"chips");a(this,"typing");a(this,"quick");a(this,"formHost");a(this,"csatPanel");a(this,"offlinePanel");a(this,"preChatPanel");a(this,"deflectPanel");a(this,"preChatBuilt",!1);a(this,"preChatDone",!1);a(this,"footer");a(this,"input");a(this,"subjectCard");a(this,"e2eBadge");a(this,"statusBadge");a(this,"headerName");a(this,"connStatus");a(this,"typingTimer",null);a(this,"csatSubmitted",!1);a(this,"sendBtn");a(this,"compactObserver",null);a(this,"cobrowseBtn");a(this,"cobrowseCanvas");a(this,"cobrowseToolbar");a(this,"cobrowseHint");a(this,"cobrowseActive",!1);a(this,"cobrowseColor","#f5713c");a(this,"lastAnnotationVersion",-1);a(this,"storeRef",null);a(this,"scrollCleanup",null);a(this,"translationCache",new Map);a(this,"showingTranslation",new Set);a(this,"subjectBuilt",!1);var S,E,K,C,_,L,F,de,I,z;this.root=e,this.me=t,this.h=i,this.cfg=s,bn(),e.replaceChildren(),e.classList.add("ocw"),s.accent&&e.style.setProperty("--ocw-accent",s.accent);const o=c("div","ocw-head");if(this.h.onBack){const m=c("button","ocw-back","‹");m.type="button",m.setAttribute("aria-label","Back"),m.addEventListener("click",()=>this.h.onBack()),o.append(m)}const r=c("div","ocw-avatar");if((S=s.userInfo)!=null&&S.avatar){const m=document.createElement("img");m.src=s.userInfo.avatar,m.alt=s.userInfo.name??"You",m.style.cssText="width:100%;height:100%;border-radius:50%;object-fit:cover",r.append(m)}else r.textContent=(E=s.userInfo)!=null&&E.name?s.userInfo.name[0].toUpperCase():"🧑";o.append(r);const d=c("div","ocw-head-main");this.headerName=c("div","ocw-head-name",((K=s.subject)==null?void 0:K.ownerLabel)??((C=s.subject)==null?void 0:C.title)??""),d.append(this.headerName),(_=s.subject)!=null&&_.subtitle&&d.append(c("div","ocw-head-meta",s.subject.subtitle)),o.append(d),this.statusBadge=c("span","ocw-badge",((L=s.subject)==null?void 0:L.status)??""),(F=s.subject)!=null&&F.status||(this.statusBadge.style.display="none"),o.append(this.statusBadge),this.e2eBadge=c("span","ocw-e2e","🔒 E2E"),this.e2eBadge.style.display="none",o.append(this.e2eBadge),this.connStatus=c("span","ocw-conn-status"),this.connStatus.style.display="none",o.append(this.connStatus),this.cobrowseBtn=c("button","ocw-menu ocw-cobrowse-btn","🖍"),this.cobrowseBtn.title="Shared whiteboard — draw to point things out together",this.cobrowseBtn.addEventListener("click",()=>{this.cobrowseActive=!this.cobrowseActive,this.updateCobrowseUI()}),o.append(this.cobrowseBtn),o.append(c("button","ocw-menu","⋯")),this.chips=c("div","ocw-chiprow"),this.scroll=c("div","ocw-scroll"),this.subjectCard=c("div","ocw-subject"),this.typing=c("div","ocw-typing");const h=c("div","ocw-typing-bubble");h.append(c("div","ocw-typing-dot"),c("div","ocw-typing-dot"),c("div","ocw-typing-dot")),this.typing.append(c("div","ocw-dot","🧑"),h),this.quick=c("div","ocw-quick");for(const m of s.quickReplies??[]){const P=c("button",void 0,m);P.addEventListener("click",()=>{this.h.onSend(m),this.quick.style.display="none"}),this.quick.append(P)}this.formHost=c("div","ocw-form-host"),this.csatPanel=c("div","ocw-csat"),this.csatPanel.style.display="none",this.offlinePanel=c("div","ocw-offline"),this.offlinePanel.style.display="none",this.preChatPanel=c("div","ocw-prechat"),this.preChatPanel.style.display="none",this.deflectPanel=c("div","ocw-deflect"),this.deflectPanel.style.display="none",this.input=c("textarea",void 0),this.input.rows=1,this.input.placeholder=((de=s.i18n)==null?void 0:de.placeholder)??"Message…";const u=c("button","ocw-sendbtn");u.type="button";const x=(I=s.i18n)==null?void 0:I.send;x?(u.textContent=x,u.classList.add("ocw-sendbtn-label"),u.setAttribute("aria-label",x)):(u.innerHTML=yn,u.setAttribute("aria-label","Send message")),u.disabled=!0,this.sendBtn=u,u.addEventListener("click",()=>this.flushSend()),this.input.addEventListener("input",()=>{var m,P;this.sendBtn.disabled=this.input.value.trim().length===0,this.autoGrowInput(),this.storeRef&&!this.storeRef.messages().some(H=>H.senderRole==="guest")?(P=(m=this.h).onDeflectQuery)==null||P.call(m,this.input.value):this.hideDeflection()}),this.input.addEventListener("keydown",m=>{m.isComposing||m.keyCode===229||(m.key==="Enter"&&!m.shiftKey?(m.preventDefault(),this.flushSend()):this.signalTyping())});const p=c("button","ocw-attach","📎");p.title="Attach image or file";const w=document.createElement("input");w.type="file",w.accept="image/*,.pdf,.txt,.doc,.docx",w.style.display="none",p.addEventListener("click",()=>w.click()),w.addEventListener("change",()=>{var m;(m=w.files)!=null&&m[0]&&this.h.onAttach&&this.h.onAttach(w.files[0]),w.value=""});const f=c("div","ocw-input");f.append(p,w,this.input,u);const k=c("div","ocw-footer");((z=s.i18n)==null?void 0:z.poweredBy)!==void 0?k.textContent=s.i18n.poweredBy:k.innerHTML='Powered by <a href="https://relay.paramms.com" target="_blank" rel="noopener">Relay</a>',this.footer=k,e.append(o,this.chips,this.scroll,this.typing,this.quick,this.formHost,this.csatPanel,this.offlinePanel,this.preChatPanel,this.deflectPanel,f,this.footer),this.cobrowseCanvas=c("canvas","ocw-cobrowse-canvas"),this.cobrowseToolbar=c("div","ocw-cobrowse-toolbar");for(const m of["#f5713c","#1c1b1a","#2563eb","#16a34a","#dc2626"]){const P=c("button","ocw-cobrowse-swatch");P.style.background=m,P.type="button",m===this.cobrowseColor&&P.classList.add("sel"),P.addEventListener("click",()=>{this.cobrowseColor=m;for(const H of this.cobrowseToolbar.querySelectorAll(".ocw-cobrowse-swatch"))H.classList.remove("sel");P.classList.add("sel")}),this.cobrowseToolbar.append(P)}const v=c("button","ocw-cobrowse-clear","Clear");v.addEventListener("click",()=>{var m,P;return(P=(m=this.h).onAnnotateClear)==null?void 0:P.call(m)}),this.cobrowseToolbar.append(v),this.cobrowseHint=c("div","ocw-cobrowse-hint","🖍 Draw to point things out — visible to both sides"),e.append(this.cobrowseCanvas,this.cobrowseToolbar,this.cobrowseHint),this.bindCobrowsePointerEvents();const y=m=>{e.classList.toggle("ocw-compact",m>0&&m<gn)};y(e.clientWidth),typeof ResizeObserver<"u"&&(this.compactObserver=new ResizeObserver(m=>{var H;const P=((H=m[0])==null?void 0:H.contentRect.width)??e.clientWidth;y(P)}),this.compactObserver.observe(e))}getScrollEl(){return this.scroll}setScrollCleanup(e){var t;(t=this.scrollCleanup)==null||t.call(this),this.scrollCleanup=e}destroy(){var e,t;(e=this.scrollCleanup)==null||e.call(this),this.scrollCleanup=null,this.typingTimer&&(clearTimeout(this.typingTimer),this.typingTimer=null),(t=this.compactObserver)==null||t.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)}render(e){var p,w,f,k,v;if(this.storeRef=e,this.cobrowseBtn.classList.toggle("show",!!e.subject),!e.subject&&this.cobrowseActive&&(this.cobrowseActive=!1,this.updateCobrowseUI()),this.cobrowseActive&&e.annotationVersion!==this.lastAnnotationVersion&&(this.lastAnnotationVersion=e.annotationVersion,this.resizeCobrowseCanvas(),this.redrawCobrowse()),e.accent&&this.root.style.setProperty("--ocw-accent",e.accent),this.e2eBadge.style.display=e.e2e?"inline-flex":"none",this.buildSubjectCard(e),e.subject){const y=(p=this.cfg.subject)==null?void 0:p.ownerLabel;y&&(this.headerName.textContent=y)}this.quick.style.display=e.messages().length===0?"flex":"none",this.chips.replaceChildren();const t=e.visibleActions();this.chips.style.display=t.length?"flex":"none";for(const y of t)this.chips.append(this.chipEl(y));const i=this.scroll.scrollHeight,s=this.scroll.scrollTop;if(this.scroll.replaceChildren(),this.subjectCard.childNodes.length&&this.scroll.append(this.subjectCard),e.hasMoreHistory){const y=c("div","ocw-load-more");y.textContent="↑ Loading earlier messages…",y.style.pointerEvents="none",this.scroll.append(y)}let o=0;for(const y of e.messages())this.scroll.append(this.messageEl(y,e)),y.senderId!==this.me&&y.seq>o&&(o=y.seq);s>20?this.scroll.scrollTop=this.scroll.scrollHeight-i+s:this.scroll.scrollTop=this.scroll.scrollHeight,o>0&&this.h.onReadUpTo(o);const r=[...e.typing];this.typing.classList.toggle("active",r.length>0);const d=this.typing.querySelector(".ocw-typing-bubble");d&&d.setAttribute("aria-label",r.length?"typing":""),this.footer.style.display=e.whiteLabel?"none":"block";const h=e.messages().some(y=>y.senderRole==="guest");!!((w=e.preChat)!=null&&w.enabled)&&!this.preChatDone&&!h&&(e.preChat.showWhen!=="offline"||e.offline)?(this.preChatBuilt||this.buildPreChatPanel(e.preChat),this.preChatPanel.style.display="block",this.offlinePanel.style.display="none",(f=this.root.querySelector(".ocw-input"))==null||f.style.setProperty("display","none")):(this.preChatPanel.style.display="none",e.offline?(this.offlinePanel.style.display==="none"&&this.buildOfflinePanel(e.offlineMessage),this.offlinePanel.style.display="block",(k=this.root.querySelector(".ocw-input"))==null||k.style.setProperty("display","none")):(this.offlinePanel.style.display="none",(v=this.root.querySelector(".ocw-input"))==null||v.style.removeProperty("display")));const x=["resolved","closed","sold","issued","checked_out"];this.h.onCsat&&!this.csatSubmitted&&x.includes(e.state)&&e.messages().length>0&&(this.csatPanel.style.display==="none"&&this.buildCsatPanel(),this.csatPanel.style.display="block")}setConnStatus(e,t){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?`⚠ ${t??"Chat unavailable"}`:e==="reconnecting"?t??"↻ reconnecting…":"● connecting…"}buildOfflinePanel(e){var d;this.offlinePanel.replaceChildren(),this.offlinePanel.append(c("div","ocw-offline-icon","🌙")),this.offlinePanel.append(c("div","ocw-offline-title",((d=this.cfg.i18n)==null?void 0:d.offline)??"We're offline right now")),this.offlinePanel.append(c("div","ocw-offline-msg",e||"Leave your details and we'll get back to you soon."));const t=c("div","ocw-offline-form"),i=c("input","ocw-offline-input");i.placeholder="Your name",i.type="text";const s=c("input","ocw-offline-input");s.placeholder="Your email",s.type="email";const o=c("textarea","ocw-offline-input");o.placeholder="Your message",o.rows=3;const r=c("button","ocw-offline-submit","Send message");r.type="button",r.addEventListener("click",()=>{!s.value.trim()||!o.value.trim()||(r.disabled=!0,this.h.onSend(`[Offline form]
192
+ Name: ${i.value||"Anonymous"}
175
193
  Email: ${s.value}
176
- Message: ${o.value}`),this.offlinePanel.replaceChildren(c("div","ocw-offline-thanks","✓ Message sent! We'll reply to your email.")))}),t.append(n,s,o,r),this.offlinePanel.append(t)}buildPreChatPanel(e){var p;this.preChatBuilt=!0,this.preChatPanel.replaceChildren(),this.preChatPanel.append(c("div","ocw-prechat-title",e.title??"Before we start…"));const t=c("div","ocw-offline-form"),n={};for(const f of e.fields??["name","email"]){const g=c("input","ocw-offline-input");g.type=f==="email"?"email":f==="phone"?"tel":"text",g.placeholder=f==="name"?"Your name":f==="email"?"Your email":"Your phone number",n[f]=g,t.append(g)}let s=null;if((p=e.topics)!=null&&p.length){s=c("select",void 0);const f=document.createElement("option");f.value="",f.textContent="What is this about?",s.append(f);for(const g of e.topics){const l=document.createElement("option");l.value=g,l.textContent=g,s.append(l)}t.append(s)}let o=null,r=null;if(e.callbackOption){const f=c("label","ocw-prechat-cb");o=document.createElement("input"),o.type="checkbox",f.append(o,document.createTextNode("📞 Request a call back")),t.append(f),n.phone||(r=c("input","ocw-offline-input"),r.type="tel",r.placeholder="Phone number for the call",r.style.display="none",o.addEventListener("change",()=>r.style.setProperty("display",o.checked?"block":"none")),t.append(r))}const h=c("button","ocw-offline-submit","Start chat");h.addEventListener("click",()=>{var x,u,S,v,y,E,I;const f=(x=n.email)==null?void 0:x.value.trim();if(n.email&&(!f||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f))){n.email.focus();return}const g=!!(o!=null&&o.checked),l=(((u=n.phone)==null?void 0:u.value)??(r==null?void 0:r.value)??"").trim();if(g&&!l){(S=n.phone??r)==null||S.focus();return}if(s&&((v=e.topics)!=null&&v.length)&&!s.value){s.focus();return}this.completePreChat(),(I=(E=this.h).onPreChat)==null||I.call(E,{...(y=n.name)!=null&&y.value.trim()?{name:n.name.value.trim()}:{},...f?{email:f}:{},...l?{phone:l}:{},...s!=null&&s.value?{topic:s.value}:{},...g?{callback:!0}:{}})}),t.append(h),this.preChatPanel.append(t)}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(c("div","ocw-deflect-hint","Instant answers — tap to expand"));for(const t of e.slice(0,3)){const n=c("button","ocw-deflect-card");n.append(c("div","ocw-deflect-q",t.title),c("div","ocw-deflect-a",t.answer)),n.addEventListener("click",()=>n.classList.toggle("open")),this.deflectPanel.append(n)}this.deflectPanel.style.display="flex"}hideDeflection(){this.deflectPanel.style.display="none",this.deflectPanel.replaceChildren()}buildCsatPanel(){this.csatPanel.replaceChildren(),this.csatPanel.append(c("div","ocw-csat-title","How did we do?"));const e=c("div","ocw-csat-stars"),t=[];for(let n=1;n<=5;n++){const s=c("button","ocw-csat-star","★");s.dataset.score=String(n),s.addEventListener("mouseenter",()=>t.forEach((o,r)=>o.classList.toggle("lit",r<n))),s.addEventListener("mouseleave",()=>t.forEach(o=>o.classList.remove("lit"))),s.addEventListener("click",()=>{var o,r;this.csatSubmitted=!0,this.csatPanel.replaceChildren(c("div","ocw-csat-done",`Thanks for your ${n}★ rating!`)),(r=(o=this.h).onCsat)==null||r.call(o,n)}),t.push(s),e.append(s)}this.csatPanel.append(e)}updateCobrowseUI(){this.cobrowseCanvas.classList.toggle("active",this.cobrowseActive),this.cobrowseToolbar.classList.toggle("active",this.cobrowseActive),this.cobrowseHint.classList.toggle("active",this.cobrowseActive),this.cobrowseBtn.classList.toggle("on",this.cobrowseActive),this.cobrowseActive&&(this.resizeCobrowseCanvas(),this.redrawCobrowse())}resizeCobrowseCanvas(){this.cobrowseCanvas.width=this.root.clientWidth||1,this.cobrowseCanvas.height=this.root.clientHeight||1}drawStroke(e){const t=this.cobrowseCanvas.getContext("2d");if(!t||e.points.length<2)return;const n=this.cobrowseCanvas.width,s=this.cobrowseCanvas.height;t.strokeStyle=e.color,t.lineWidth=Math.max(1,e.width*Math.min(n,s)),t.lineJoin="round",t.lineCap="round",t.beginPath(),t.moveTo(e.points[0].x*n,e.points[0].y*s);for(const o of e.points.slice(1))t.lineTo(o.x*n,o.y*s);t.stroke()}redrawCobrowse(){var t;const e=this.cobrowseCanvas.getContext("2d");if(e){e.clearRect(0,0,this.cobrowseCanvas.width,this.cobrowseCanvas.height);for(const n of((t=this.storeRef)==null?void 0:t.annotations)??[])this.drawStroke(n)}}bindCobrowsePointerEvents(){let e=!1,t=[];const n=r=>{const h=this.cobrowseCanvas.getBoundingClientRect(),p=h.width>0?(r.clientX-h.left)/h.width:0,f=h.height>0?(r.clientY-h.top)/h.height:0;return{x:Math.min(1,Math.max(0,p)),y:Math.min(1,Math.max(0,f))}},s=.006;this.cobrowseCanvas.addEventListener("pointerdown",r=>{this.cobrowseActive&&(e=!0,t=[n(r)],this.cobrowseCanvas.setPointerCapture(r.pointerId))}),this.cobrowseCanvas.addEventListener("pointermove",r=>{e&&(t.push(n(r)),this.redrawCobrowse(),this.drawStroke({points:t,color:this.cobrowseColor,width:s}))});const o=r=>{var h,p;if(e){e=!1,t.length>1&&((p=(h=this.h).onAnnotate)==null||p.call(h,{id:`an_${Date.now()}_${Math.random().toString(36).slice(2)}`,points:t,color:this.cobrowseColor,width:s})),t=[];try{this.cobrowseCanvas.releasePointerCapture(r.pointerId)}catch{}}};this.cobrowseCanvas.addEventListener("pointerup",o),this.cobrowseCanvas.addEventListener("pointercancel",o)}buildSubjectCard(e){if(this.subjectBuilt)return;const t=e.subject,n=this.cfg.subject,s=(t==null?void 0:t.title)??(n==null?void 0:n.title);if(!s)return;this.subjectBuilt=!0,this.subjectCard.replaceChildren(),this.subjectCard.append(c("div","ocw-subject-title",s)),n!=null&&n.subtitle&&this.subjectCard.append(c("div","ocw-subject-sub",n.subtitle));const o=c("div","ocw-tags");if(t)for(const[h,p]of Object.entries(t.fields))o.append(c("span","ocw-tag",`${h}: ${p}`));else for(const h of(n==null?void 0:n.tags)??[])o.append(c("span","ocw-tag",h));o.childNodes.length&&this.subjectCard.append(o);const r=(t==null?void 0:t.state)??(n==null?void 0:n.status);r&&(this.statusBadge.textContent=r,this.statusBadge.style.display="inline-flex")}chipEl(e){const t=c("button","ocw-chip",e.icon?`${e.icon} ${e.label}`:e.label);return t.dataset.actionId=e.id,t.addEventListener("click",async()=>{var n;e.confirm&&!await this.confirm(e.label)||((n=e.input)!=null&&n.length?this.openForm(e):this.h.onInvoke(e.id))}),t}confirm(e){return new Promise(t=>{const n=c("div","ocw-modal"),s=c("div","ocw-modal-card");s.append(c("div","ocw-modal-title",e)),s.append(c("div","ocw-modal-body",`Confirm “${e}”?`));const o=c("div","ocw-modal-actions"),r=c("button","ocw-modal-cancel","Cancel"),h=c("button","ocw-modal-ok","Confirm"),p=f=>{n.remove(),t(f)};r.addEventListener("click",()=>p(!1)),h.addEventListener("click",()=>p(!0)),n.addEventListener("click",f=>{f.target===n&&p(!1)}),o.append(r,h),s.append(o),n.append(s),this.root.append(n),h.focus()})}openForm(e){var h,p;this.formHost.replaceChildren();const t=c("div","ocw-form");t.append(c("div","ocw-form-title",e.icon?`${e.icon} ${e.label}`:e.label));const n=new Map;for(const f of e.input??[]){const g=c("label","ocw-form-row");if(g.append(c("span","ocw-form-lbl",f.label)),f.type==="select"&&((h=f.options)!=null&&h.length)){const l=c("select","ocw-form-input");f.required||l.append(c("option",void 0,"— select —"));for(const x of f.options){const u=c("option");u.value=x,u.textContent=x,l.append(u)}f.required&&(l.required=!0),g.append(l),n.set(f.name,l)}else{const l=c("input","ocw-form-input");l.type=f.type==="number"?"number":f.type==="date"?"datetime-local":"text",f.required&&(l.required=!0),g.append(l),n.set(f.name,l)}t.append(g)}const s=c("div","ocw-form-actions"),o=c("button","ocw-form-cancel","Cancel"),r=c("button","ocw-form-submit","Send");o.addEventListener("click",()=>this.formHost.replaceChildren()),r.addEventListener("click",()=>{const f={};for(const[g,l]of n){if(l.required&&!l.value){l.style.borderColor="#e5484d";return}f[g]=l.type==="number"?Number(l.value):l.value}this.formHost.replaceChildren(),this.h.onInvoke(e.id,f)}),s.append(o,r),t.append(s),this.formHost.append(t),(p=n.values().next().value)==null||p.focus()}messageEl(e,t){var l;if(e.senderRole==="system"){const x=c("div","ocw-sys");return x.textContent=e.deletedAt?"message deleted":ye(e.content),x}const n=e.senderId===this.me,s=!!e.internal,o=c("div",`ocw-row ${s?"ocw-note mine":n?"mine":"theirs"} ${e.senderRole==="bot"?"ocw-bot":""}`);!n&&!s&&o.append(c("div","ocw-dot",e.senderRole==="bot"?"🤖":"🧑"));const r=c("div"),h=c("div","ocw-bubble-wrap");if(e.replyToId){const x=c("div","ocw-reply-to","↩ replying to a message");x.style.cssText="font-size:11px;color:var(--ocw-mut);margin-bottom:2px;font-style:italic",r.append(x)}const p=c("div","ocw-bubble");let f=null;if(e.deletedAt)p.append(c("span","ocw-deleted","message deleted"));else if(e.content.kind==="attachment"){const x=e.content;if((l=x.mime)!=null&&l.startsWith("image/")){const u=document.createElement("img");u.src=x.url,u.alt=x.name??"image",u.style.cssText="max-width:220px;max-height:160px;border-radius:10px;display:block;cursor:pointer",u.addEventListener("click",()=>window.open(x.url,"_blank")),p.append(u)}else{const u=document.createElement("a");u.href=x.url,u.target="_blank",u.rel="noopener",u.style.cssText="display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none",u.append(c("span",void 0,"📄"),c("span",void 0,x.name??"file")),p.append(u)}}else if(e.content.kind==="appointment"){const x=e.content,u=c("div","ocw-appt");u.append(c("div","ocw-appt-title",`📅 ${x.title}`)),u.append(c("div","ocw-appt-time",new Date(x.startIso).toLocaleString()+" – "+new Date(x.endIso).toLocaleTimeString())),x.location&&u.append(c("div","ocw-appt-loc",`📍 ${x.location}`)),x.description&&u.append(c("div","ocw-appt-desc",x.description));const S=c("div","ocw-appt-links"),v=document.createElement("a");v.href=x.googleUrl,v.target="_blank",v.rel="noopener",v.className="ocw-appt-btn",v.textContent="📅 Add to Google Calendar";const y=document.createElement("a");y.href=x.icalUrl,y.download=`${x.title}.ics`,y.className="ocw-appt-btn ocw-appt-btn-sec",y.textContent="🍎 Apple / iCal",S.append(v,y),u.append(S),p.append(u)}else f=document.createTextNode(ye(e.content)),p.append(f),e.editedAt&&p.append(c("span","ocw-edited","(edited)"));if(h.append(p),!n&&!s&&this.h.onTranslate&&e.content.kind==="text"&&!e.deletedAt&&e.seq>0&&f){const x=e.content.text;if(x.trim()){const u=c("button","ocw-translate-btn","🌐");u.type="button",u.title="Translate",u.addEventListener("click",S=>{if(S.stopPropagation(),this.showingTranslation.has(e.id)){this.showingTranslation.delete(e.id),f.textContent=x,u.textContent="🌐",u.title="Translate";return}const v=this.translationCache.get(e.id);if(v!==void 0){this.showingTranslation.add(e.id),f.textContent=v,u.textContent="↩",u.title="Show original";return}u.textContent="⏳",this.h.onTranslate(x).then(y=>{if(y===null){u.textContent="⚠️",u.title="Translation unavailable",setTimeout(()=>{u.textContent="🌐",u.title="Translate"},1500);return}this.translationCache.set(e.id,y),this.showingTranslation.add(e.id),f.textContent=y,u.textContent="↩",u.title="Show original"})}),h.append(u)}}if(n&&!e.deletedAt&&e.seq>0&&(this.h.onEdit??this.h.onDelete)){const x=c("div","ocw-msg-menu");if(this.h.onEdit){const u=c("button",void 0,"✏️");u.title="Edit",u.addEventListener("click",S=>{S.stopPropagation();const v=ye(e.content),y=document.createElement("textarea");y.value=v,y.rows=Math.min(4,Math.ceil(v.length/40)+1),y.style.cssText="width:100%;resize:vertical;border:1px solid var(--ocw-accent);border-radius:8px;padding:6px 10px;font:inherit;font-size:14px;background:#fff;color:#1c1b1a;box-sizing:border-box";const E=c("button","ocw-form-submit","Save");E.style.cssText="margin-top:6px;padding:5px 14px;font-size:13px";const I=c("button","ocw-form-cancel","Cancel");I.style.cssText="margin-top:6px;padding:5px 10px;font-size:13px";const L=c("div");L.style.cssText="display:flex;gap:6px;justify-content:flex-end",L.append(I,E);const M=c("div");M.append(y,L),p.replaceChildren(M),y.focus(),y.select();const A=()=>p.replaceChildren(f??document.createTextNode(v));I.addEventListener("click",A),E.addEventListener("click",()=>{const U=y.value.trim();U&&U!==v&&this.h.onEdit(e.id,U),A()}),y.addEventListener("keydown",U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),E.click()),U.key==="Escape"&&A()})}),x.append(u)}if(this.h.onDelete){const u=c("button","del","🗑");u.title="Delete",u.addEventListener("click",S=>{S.stopPropagation(),this.h.onDelete(e.id)}),x.append(u)}h.append(x)}if(r.append(h),this.h.onReact&&!e.deletedAt&&e.seq>0){const x=c("div","ocw-react-wrap"),u=c("div","ocw-react");if(e.reactions&&Object.keys(e.reactions).length)for(const[y,E]of Object.entries(e.reactions)){const I=c("button",`ocw-react-pill${E.includes(this.me)?" mine":""}`,`${y} ${E.length}`);I.addEventListener("click",()=>{var L,M;return(M=(L=this.h).onReact)==null?void 0:M.call(L,e.id,y,E.includes(this.me))}),u.append(I)}const S=c("button","ocw-react-btn","+"),v=c("div","ocw-react-picker");for(const y of Zt){const E=c("button",void 0,y);E.addEventListener("click",I=>{var M,A,U,k;I.stopPropagation();const L=(A=(M=e.reactions)==null?void 0:M[y])==null?void 0:A.includes(this.me);(k=(U=this.h).onReact)==null||k.call(U,e.id,y,!!L),v.style.display="none"}),v.append(E)}v.style.display="none",S.addEventListener("click",y=>{y.stopPropagation(),v.style.display=v.style.display==="none"?"flex":"none"}),document.addEventListener("click",()=>{v.style.display="none"},{once:!0}),u.append(S),x.append(u,v),r.append(x)}else e.reactions&&Object.keys(e.reactions).length&&r.append(c("div","ocw-react",Object.entries(e.reactions).map(([x,u])=>`${x}${u.length}`).join(" ")));const g=c("div","ocw-time ocw-meta",tn(e.ts));if(n&&e.status){const x=c("span",`ocw-tick${e.status==="read"?" read":e.status==="delivered"?" delivered":""}`,sn(e.status));g.append(x)}return n&&e.seq>0&&t.lastReadByOthers>=e.seq&&g.append(c("span","ocw-seen"," · Seen")),r.append(g),o.append(r),o}}function sn(i){switch(i){case"read":return"✓✓";case"delivered":return"✓✓";case"sent":return"✓";default:return"🕓"}}const on=20;function Be(i,e){var p;const t=i.trim().replace(/\/+$/,""),n=(p=t.match(/^(https|http|wss|ws):\/\//))==null?void 0:p[1],s=n?n==="https"||n==="wss":!0,o=(n?t.slice(n.length+3):t).replace(/\/ws$/,""),r=e?e.trim().replace(/\/+$/,""):`${s?"https":"http"}://${o}`;return{wsUrl:`${s?"wss":"ws"}://${o}/ws`,httpBase:r}}function rn(i){return Be(i).httpBase}function an(i,e,t,n){const s=`beforeSeq=${t}&limit=${n}`;return[`${i}/conversations/${e}/messages?${s}`,`${i}/conversations/${e}/history?${s}`]}async function Ke(i,e,t,n,s=on){for(const o of an(i,e,n,s))try{const r=await fetch(o,{headers:{authorization:`Bearer ${t}`}});if(!r.ok)continue;const h=await r.json();return{messages:h.messages??[],hasMore:h.hasMore??!1}}catch{}return null}async function cn(i,e,t,n,s,o){const r=o?o.replace(/\/+$/,""):rn(i),h=await Ke(r,t,e,Number.MAX_SAFE_INTEGER);if(!h||(h.messages.length?(n.apply({type:"sync",conversationId:t,messages:h.messages}),n.apply({type:"history",conversationId:t,messages:[],hasMore:h.hasMore}),s.render(n)):n.apply({type:"history",conversationId:t,messages:[],hasMore:!1}),!h.hasMore))return;let p=!1;const f=async()=>{if(p||!n.hasMoreHistory)return;p=!0;const u=n.messages()[0];if(!u){p=!1;return}const S=await Ke(r,t,e,u.seq);S&&(n.apply({type:"history",conversationId:t,messages:S.messages,hasMore:S.hasMore}),s.render(n)),p=!1},g=s.getScrollEl();if(!g)return;let l=!1;setTimeout(()=>{l=!0},300);const x=()=>{l&&g.scrollTop<80&&n.hasMoreHistory&&!p&&f()};g.addEventListener("scroll",x,{passive:!0}),s.setScrollCleanup(()=>g.removeEventListener("scroll",x))}const G=new WeakMap,ne=new Map;function ze(i){return`relay-launcher::${i.profileId}::${i.subjectId??""}`}function dn(i){var He,je,qe,Fe,Oe;G.has(i.el)&&(G.get(i.el).close(),G.delete(i.el)),i.launcher&&((He=ne.get(ze(i)))==null||He.close());const e=Ve();let t,n=!1;const s=i.token??i.userId??e,o=s!==e?e:void 0,{wsUrl:r,httpBase:h}=Be(i.url,i.apiUrl);let p=new Kt(s);const f=i.subjectId?`${s}::${i.subjectId}`:s,g=new Ht(f);let l,x=!1,u=null,S=null;!i.launcher&&!i.el.style.height&&i.el.clientHeight===0&&(i.el.style.width=i.el.style.width||"100%",i.el.style.height="600px");for(const d of g.load())p.addOptimistic(d.clientMsgId,d.content);let v=null,y=null,E=0,I=!i.launcher;if(i.launcher){const w=(i.position??"bottom-right").includes("right");v=document.createElement("div"),v.style.cssText=`position:fixed;${w?"right:20px":"left:20px"};bottom:20px;z-index:9999;display:flex;flex-direction:column;align-items:${w?"flex-end":"flex-start"};gap:12px`;const m=document.createElement("div"),P=typeof window<"u"?window.matchMedia("(max-width: 479px)"):null,re=F=>{m.style.cssText=F?["position:fixed","inset:0","width:100%","height:100%","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:380px","height:600px","border-radius:16px","overflow:hidden","box-shadow:0 8px 40px rgba(0,0,0,.18)","display:none","flex-direction:column","background:#fff","transform-origin:bottom "+(w?"right":"left"),"transition:opacity .18s,transform .18s","opacity:0","transform:scale(.95)"].join(";")};re((P==null?void 0:P.matches)??!1);const ae=F=>re(F.matches);P==null||P.addEventListener("change",ae),u=P,S=ae,i.el.style.cssText="width:100%;height:100%;overflow:hidden",m.append(i.el);const K=document.createElement("button");K.style.cssText=["width:56px;height:56px;border-radius:50%",`background:${i.accent??"#4F63F5"}`,"color:#fff;border:none;font-size:24px;cursor:pointer","box-shadow:0 4px 16px rgba(0,0,0,.25)","position:relative;flex:none","transition:transform .15s"].join(";"),K.textContent="💬",K.onmouseenter=()=>{K.style.transform="scale(1.08)"},K.onmouseleave=()=>{K.style.transform="scale(1)"},y=document.createElement("span"),y.style.cssText="position:absolute;top:-4px;right:-4px;background:#ef4444;color:#fff;border-radius:50%;width:20px;height:20px;font-size:11px;font-weight:700;display:none;align-items:center;justify-content:center",K.append(y),v.append(m,K),document.body.append(v);const ce=F=>{F?(m.style.display="flex",requestAnimationFrame(()=>{m.style.opacity="1",m.style.transform="scale(1)"})):(m.style.opacity="0",m.style.transform="scale(.95)",setTimeout(()=>{I||(m.style.display="none")},180))};K.addEventListener("click",()=>{I=!I,ce(I),K.textContent=I?"✕":"💬",K.append(y),I&&(E=0,y&&(y.style.display="none"))}),document.addEventListener("keydown",F=>{F.key==="Escape"&&I&&(I=!1,ce(!1),K.textContent="💬",K.append(y))})}const L=()=>{I||(E++,y&&(y.textContent=String(E),y.style.display="flex"))},M=()=>{try{const d=new AudioContext,w=d.createOscillator(),m=d.createGain();w.connect(m),m.connect(d.destination),w.frequency.setValueAtTime(880,d.currentTime),w.frequency.exponentialRampToValueAtTime(440,d.currentTime+.15),m.gain.setValueAtTime(.3,d.currentTime),m.gain.exponentialRampToValueAtTime(.001,d.currentTime+.3),w.start(),w.stop(d.currentTime+.3)}catch{}},A=[],U=d=>{for(;A.length;){const w=A.shift();g.add({clientMsgId:w.clientMsgId,content:w.content,ts:Date.now()}),k.send({type:"send",conversationId:d,clientMsgId:w.clientMsgId,content:w.content})}};let k;const b=new Jt(`ocw-e2e-${i.profileId}`);let T=!1;const q=[],se=[];let De=!1;const ge=(d,w)=>{b.sealText(w).then(m=>{l&&k.send({type:"send",conversationId:l,clientMsgId:d,content:m})})},yn=(d,w,m)=>{b.sealText(w,m).then(P=>{l&&k.send({type:"send",conversationId:l,clientMsgId:d,content:P})})},xn=()=>{for(;q.length;){const d=q.shift();ge(d.clientMsgId,d.text)}for(;se.length;){const d=se.shift();ge(d.clientMsgId,d.text)}},gn=d=>{k.send({type:"fetchPrekey",targetUserId:d})},bn=i.i18n??{},mn=["ar","he","fa","ur"],vn=typeof navigator<"u"?(navigator.language??"").slice(0,2).toLowerCase():"";mn.includes(vn)&&!i.el.dir&&(i.el.dir="rtl",i.el.style.fontFamily=i.el.style.fontFamily||"Tahoma,Arial,system-ui,sans-serif");const $e=new Lt,Re=`oc_prechat_${i.profileId}_${s.slice(-8)}`,B=new nn(i.el,s,{onSend(d){const w=`cm_${Math.random().toString(36).slice(2)}`,m={kind:"text",text:d};p.addOptimistic(w,m),B.render(p),p.e2e?b.ready?ge(w,d):De?se.push({clientMsgId:w,text:d}):(q.push({clientMsgId:w,text:d}),p.assignedAgentId&&gn(p.assignedAgentId)):l?(g.add({clientMsgId:w,content:m,ts:Date.now()}),k.send({type:"send",conversationId:l,clientMsgId:w,content:m})):A.push({clientMsgId:w,content:m})},async onAttach(d){if(!l)return;const w=`${h}/upload?name=${encodeURIComponent(d.name)}`,m=`cm_${Math.random().toString(36).slice(2)}`;p.addOptimistic(m,{kind:"text",text:`📎 Uploading ${d.name}…`}),B.render(p);try{const P=await fetch(w,{method:"POST",headers:{"content-type":d.type,authorization:`Bearer ${s}`},body:d});if(!P.ok)throw new Error(`Upload failed: ${P.status}`);const{url:re,name:ae,mime:K,size:ce}=await P.json();k.send({type:"send",conversationId:l,clientMsgId:m,content:{kind:"attachment",url:re,name:ae,mime:K,size:ce}})}catch(P){p.addOptimistic(m,{kind:"text",text:`⚠️ Upload failed: ${P.message}`}),B.render(p)}},onInvoke(d,w){l&&k.send({type:"invoke",conversationId:l,actionId:d,clientInvokeId:`iv_${Math.random().toString(36).slice(2)}`,...w?{inputs:w}:{}})},onTyping(d,w){l&&k.send({type:"typing",conversationId:l,isTyping:d,...w?{preview:w}:{}})},onPreChat(d){try{localStorage.setItem(Re,"1")}catch{}k.send({type:"open",profileId:i.profileId,...i.subjectId?{subjectId:i.subjectId}:{},userInfo:{...d.name?{name:d.name}:{},...d.email?{email:d.email}:{},...d.phone||d.topic?{meta:{...d.phone?{phone:d.phone}:{},...d.topic?{topic:d.topic}:{}}}:{}}});const w=d.callback?`📞 Call-back requested${d.phone?`: ${d.phone}`:""}${d.topic?` — ${d.topic}`:""}`:d.topic?`Topic: ${d.topic}`:"";w&&l&&!p.e2e&&k.send({type:"send",conversationId:l,clientMsgId:`pc_${Math.random().toString(36).slice(2,12)}`,content:{kind:"text",text:w}})},onDeflectQuery(d){if(n)return;clearTimeout(t);const w=d.trim();if(w.length<3){B.hideDeflection();return}t=setTimeout(()=>{fetch(`${h}/kb/search?profileId=${encodeURIComponent(i.profileId)}&q=${encodeURIComponent(w.slice(0,200))}`).then(m=>m.ok?m.json():{articles:[]}).then(m=>B.showDeflection(m.articles??[])).catch(()=>B.hideDeflection())},350)},onReadUpTo(d){l&&k.send({type:"read",conversationId:l,seq:d})},onLoadMore(){if(!l||!p.e2e)return;const d=p.messages()[0];d&&k.send({type:"history",conversationId:l,beforeSeq:d.seq,limit:20})},onEdit(d,w){l&&k.send({type:"edit",conversationId:l,messageId:d,content:{kind:"text",text:w}})},onDelete(d){l&&k.send({type:"delete",conversationId:l,messageId:d})},onReact(d,w,m){l&&k.send({type:"react",conversationId:l,messageId:d,emoji:w,remove:m})},onCsat(d){l&&fetch(`${h}/conversations/${l}/csat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({score:d})}).catch(()=>{})},onAnnotate(d){l&&k.send({type:"annotate",conversationId:l,stroke:d})},onAnnotateClear(){l&&k.send({type:"annotate_clear",conversationId:l})},...i.translateLang?{async onTranslate(d){try{const w=await fetch(`${h}/translate`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${s}`},body:JSON.stringify({text:d,targetLang:i.translateLang})});if(!w.ok)return null;const{translated:m}=await w.json();return m}catch{return null}}}:{},...i.onBack?{onBack:i.onBack}:{}},{...i.subject?{subject:i.subject}:{},...i.quickReplies?{quickReplies:i.quickReplies}:{},...i.accent?{accent:i.accent}:{},...(je=i.user)!=null&&je.name||(qe=i.user)!=null&&qe.avatar?{userInfo:{...i.user.name?{name:i.user.name}:{},...i.user.avatar?{avatar:i.user.avatar}:{}}}:{},i18n:bn});try{localStorage.getItem(Re)&&B.completePreChat()}catch{}const _e=i.user&&(i.user.name||i.user.email||i.user.avatar||i.user.meta)?{...i.user.name?{name:i.user.name}:{},...i.user.email?{email:i.user.email}:{},...i.user.avatar?{avatar:i.user.avatar}:{},...i.user.meta?{meta:i.user.meta}:{}}:void 0,kn={type:"open",profileId:i.profileId,...i.kind==="direct"&&i.peerId?{kind:"direct",peerId:i.peerId}:i.subjectId?{subjectId:i.subjectId}:{},...o?{linkFrom:o}:{},..._e?{userInfo:_e}:{},...typeof location<"u"?{pageUrl:location.href}:{},...typeof document<"u"&&document.title?{pageTitle:document.title}:{},...(Fe=i.subject)!=null&&Fe.title?{subjectTitle:i.subject.title}:{},...(Oe=i.subject)!=null&&Oe.subtitle?{subjectMeta:i.subject.subtitle}:{}};k=new Mt({...i.refreshToken?{refreshToken:i.refreshToken}:{},url:r,token:s,open:kn,getCursor:()=>p.highestSeq(),onStatusChange:(d,w)=>B.setConnStatus(d,w),onFrame(d){if($e.apply(d),d.type==="opened"){if(l=d.conversation.id,!x){x=!0;for(const w of g.load())k.send({type:"send",conversationId:l,clientMsgId:w.clientMsgId,content:w.content})}cn(r,s,l,p,B,h),A.length&&U(l)}if(d.type==="ack"&&g.remove(d.clientMsgId),d.type==="prekeyBundle"){d.bundle&&(De=!0,b.x3dhSendTo(d.bundle).then(w=>{const m=[...q.splice(0),...se.splice(0)];for(const P of m)yn(P.clientMsgId,P.text,w);B.render(p)}));return}if(d.type==="message"&&p.e2e){const w=Gt(d.message.content);if(w&&!b.ready){b.x3dhReceiveFrom(w.x3dhIK,w.x3dhEK,w.x3dhSPK).then(async()=>{await b.openFrame(d),p.apply(d),B.render(p)});return}}if(d.type==="peerkey"){b.onPeerKey(d.key).then(()=>{xn(),B.render(p)});return}(async()=>{if(p.e2e&&await b.openFrame(d),p.apply(d),d.type==="message"&&d.message.senderId!==s&&!d.message.internal&&(L(),M()),p.e2e&&l&&!T){T=!0;const w=await b.initX3DH();k.send({type:"uploadPrekeys",...w});const m=await b.begin();k.send({type:"pubkey",conversationId:l,key:m})}B.render(p)})()}}),k.connect(),B.render(p);const Z=i.launcher?ze(i):null,oe={close:()=>{n=!0,clearTimeout(t),k.close(),v==null||v.remove(),B.destroy(),$e.destroy(),u&&S&&u.removeEventListener("change",S),G.delete(i.el),Z&&ne.get(Z)===oe&&ne.delete(Z)}};return G.set(i.el,oe),Z&&ne.set(Z,oe),oe}const ln="wss://api.paramms.com/ws";let j=null,$=null,W={};function hn(i,e){const t=i.profileId??i.appId;if(!t)throw new Error("Relay: `appId` is required (your chatroom id, e.g. 'p_...').");const n=i.subjectId??(i.listingId?`listing_${i.listingId}`:void 0),s=i.subjectTitle?{title:i.subjectTitle,...i.subjectMeta?{subtitle:i.subjectMeta}:{},...i.subjectPrice!=null?{tags:[`$${i.subjectPrice.toLocaleString()}`]}:{},...i.subjectStatus?{status:i.subjectStatus}:{}}:void 0,o=i.name||i.email||i.avatar?{...i.name?{name:i.name}:{},...i.email?{email:i.email}:{},...i.avatar?{avatar:i.avatar}:{}}:void 0;return{el:e,url:i.url??ln,profileId:t,...i.apiUrl?{apiUrl:i.apiUrl}:{},...n?{subjectId:n}:{},...i.token?{token:i.token}:{},...i.userId?{userId:i.userId}:{},...s?{subject:s}:{},...o?{user:o}:{},...i.accent?{accent:i.accent}:{},...i.translateLang?{translateLang:i.translateLang}:{},launcher:i.launcher??!0,position:i.position??"bottom-right"}}function pn(){return(!$||!$.isConnected)&&($=document.createElement("div"),$.id="relay-widget-root",document.body.appendChild($)),$}function Le(i){try{j==null||j.close(),j=dn(hn(i,pn()))}catch(e){console.error("[Relay]",e instanceof Error?e.message:e)}}function Me(i){W={...i},Le(W)}function un(i){W={...W,...i},Le(W)}function fn(){j==null||j.close(),j=null,$==null||$.remove(),$=null,W={}}function xe(i,e){switch(i){case"boot":Me(e??{});break;case"update":case"identify":un(e??{});break;case"shutdown":fn();break;default:console.warn("[Relay] unknown command:",i)}}function wn(){if(typeof document>"u")return null;const i=document.querySelector("script[data-relay-app]"),e=i==null?void 0:i.dataset.relayApp;if(!e)return null;const t=i.dataset,n={appId:e};t.relayUser&&(n.userId=t.relayUser),t.relayToken&&(n.token=t.relayToken),t.relayListing&&(n.listingId=t.relayListing),t.relayAccent&&(n.accent=t.relayAccent),t.relayUrl&&(n.url=t.relayUrl);const s=t.relayPosition;return(s==="bottom-left"||s==="bottom-right")&&(n.position=s),t.relayLauncher==="false"&&(n.launcher=!1),n}if(typeof window<"u"){const i=window,e=i.Relay&&i.Relay.q?i.Relay.q:[];i.Relay=xe;let t=!1;for(const n of e){const[s,o]=n;s==="boot"&&(t=!0),xe(s,o)}if(!t){const n=i.relaySettings??wn();n&&Me(n)}}return R.Relay=xe,Object.defineProperty(R,Symbol.toStringTag,{value:"Module"}),R}({});
194
+ Message: ${o.value}`),this.offlinePanel.replaceChildren(c("div","ocw-offline-thanks","✓ Message sent! We'll reply to your email.")))}),t.append(i,s,o,r),this.offlinePanel.append(t)}buildPreChatPanel(e){var h;this.preChatBuilt=!0,this.preChatPanel.replaceChildren(),this.preChatPanel.append(c("div","ocw-prechat-title",e.title??"Before we start…"));const t=c("div","ocw-offline-form"),i={};for(const u of e.fields??["name","email"]){const x=c("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",i[u]=x,t.append(x)}let s=null;if((h=e.topics)!=null&&h.length){s=c("select",void 0);const u=document.createElement("option");u.value="",u.textContent="What is this about?",s.append(u);for(const x of e.topics){const p=document.createElement("option");p.value=x,p.textContent=x,s.append(p)}t.append(s)}let o=null,r=null;if(e.callbackOption){const u=c("label","ocw-prechat-cb");o=document.createElement("input"),o.type="checkbox",u.append(o,document.createTextNode("📞 Request a call back")),t.append(u),i.phone||(r=c("input","ocw-offline-input"),r.type="tel",r.placeholder="Phone number for the call",r.style.display="none",o.addEventListener("change",()=>r.style.setProperty("display",o.checked?"block":"none")),t.append(r))}const d=c("button","ocw-offline-submit","Start chat");d.type="button",d.addEventListener("click",()=>{var w,f,k,v,y,S,E;const u=(w=i.email)==null?void 0:w.value.trim();if(i.email&&(!u||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(u))){i.email.focus();return}const x=!!(o!=null&&o.checked),p=(((f=i.phone)==null?void 0:f.value)??(r==null?void 0:r.value)??"").trim();if(x&&!p){(k=i.phone??r)==null||k.focus();return}if(s&&((v=e.topics)!=null&&v.length)&&!s.value){s.focus();return}d.disabled=!0,this.completePreChat(),(E=(S=this.h).onPreChat)==null||E.call(S,{...(y=i.name)!=null&&y.value.trim()?{name:i.name.value.trim()}:{},...u?{email:u}:{},...p?{phone:p}:{},...s!=null&&s.value?{topic:s.value}:{},...x?{callback:!0}:{}})}),t.append(d),this.preChatPanel.append(t)}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(c("div","ocw-deflect-hint","Instant answers — tap to expand"));for(const t of e.slice(0,3)){const i=c("button","ocw-deflect-card");i.append(c("div","ocw-deflect-q",t.title),c("div","ocw-deflect-a",t.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(c("div","ocw-csat-title","How did we do?"));const e=c("div","ocw-csat-stars"),t=[];for(let i=1;i<=5;i++){const s=c("button","ocw-csat-star","★");s.dataset.score=String(i),s.addEventListener("mouseenter",()=>t.forEach((o,r)=>o.classList.toggle("lit",r<i))),s.addEventListener("mouseleave",()=>t.forEach(o=>o.classList.remove("lit"))),s.addEventListener("click",()=>{var o,r;this.csatSubmitted=!0,this.csatPanel.replaceChildren(c("div","ocw-csat-done",`Thanks for your ${i}★ rating!`)),(r=(o=this.h).onCsat)==null||r.call(o,i)}),t.push(s),e.append(s)}this.csatPanel.append(e)}updateCobrowseUI(){this.cobrowseCanvas.classList.toggle("active",this.cobrowseActive),this.cobrowseToolbar.classList.toggle("active",this.cobrowseActive),this.cobrowseHint.classList.toggle("active",this.cobrowseActive),this.cobrowseBtn.classList.toggle("on",this.cobrowseActive),this.cobrowseActive&&(this.resizeCobrowseCanvas(),this.redrawCobrowse())}resizeCobrowseCanvas(){this.cobrowseCanvas.width=this.root.clientWidth||1,this.cobrowseCanvas.height=this.root.clientHeight||1}drawStroke(e){const t=this.cobrowseCanvas.getContext("2d");if(!t||e.points.length<2)return;const i=this.cobrowseCanvas.width,s=this.cobrowseCanvas.height;t.strokeStyle=e.color,t.lineWidth=Math.max(1,e.width*Math.min(i,s)),t.lineJoin="round",t.lineCap="round",t.beginPath(),t.moveTo(e.points[0].x*i,e.points[0].y*s);for(const o of e.points.slice(1))t.lineTo(o.x*i,o.y*s);t.stroke()}redrawCobrowse(){var t;const e=this.cobrowseCanvas.getContext("2d");if(e){e.clearRect(0,0,this.cobrowseCanvas.width,this.cobrowseCanvas.height);for(const i of((t=this.storeRef)==null?void 0:t.annotations)??[])this.drawStroke(i)}}bindCobrowsePointerEvents(){let e=!1,t=[];const i=r=>{const d=this.cobrowseCanvas.getBoundingClientRect(),h=d.width>0?(r.clientX-d.left)/d.width:0,u=d.height>0?(r.clientY-d.top)/d.height:0;return{x:Math.min(1,Math.max(0,h)),y:Math.min(1,Math.max(0,u))}},s=.006;this.cobrowseCanvas.addEventListener("pointerdown",r=>{this.cobrowseActive&&(e=!0,t=[i(r)],this.cobrowseCanvas.setPointerCapture(r.pointerId))}),this.cobrowseCanvas.addEventListener("pointermove",r=>{e&&(t.push(i(r)),this.redrawCobrowse(),this.drawStroke({points:t,color:this.cobrowseColor,width:s}))});const o=r=>{var d,h;if(e){e=!1,t.length>1&&((h=(d=this.h).onAnnotate)==null||h.call(d,{id:`an_${Date.now()}_${Math.random().toString(36).slice(2)}`,points:t,color:this.cobrowseColor,width:s})),t=[];try{this.cobrowseCanvas.releasePointerCapture(r.pointerId)}catch{}}};this.cobrowseCanvas.addEventListener("pointerup",o),this.cobrowseCanvas.addEventListener("pointercancel",o)}buildSubjectCard(e){if(this.subjectBuilt)return;const t=e.subject,i=this.cfg.subject,s=(t==null?void 0:t.title)??(i==null?void 0:i.title);if(!s)return;this.subjectBuilt=!0,this.subjectCard.replaceChildren(),this.subjectCard.append(c("div","ocw-subject-title",s)),i!=null&&i.subtitle&&this.subjectCard.append(c("div","ocw-subject-sub",i.subtitle));const o=c("div","ocw-tags");if(t)for(const[d,h]of Object.entries(t.fields))o.append(c("span","ocw-tag",`${d}: ${h}`));else for(const d of(i==null?void 0:i.tags)??[])o.append(c("span","ocw-tag",d));o.childNodes.length&&this.subjectCard.append(o);const r=(t==null?void 0:t.state)??(i==null?void 0:i.status);r&&(this.statusBadge.textContent=r,this.statusBadge.style.display="inline-flex")}chipEl(e){const t=c("button","ocw-chip",e.icon?`${e.icon} ${e.label}`:e.label);return t.dataset.actionId=e.id,t.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))}),t}confirm(e){return new Promise(t=>{const i=c("div","ocw-modal"),s=c("div","ocw-modal-card");s.append(c("div","ocw-modal-title",e)),s.append(c("div","ocw-modal-body",`Confirm “${e}”?`));const o=c("div","ocw-modal-actions"),r=c("button","ocw-modal-cancel","Cancel"),d=c("button","ocw-modal-ok","Confirm"),h=u=>{i.remove(),t(u)};r.addEventListener("click",()=>h(!1)),d.addEventListener("click",()=>h(!0)),i.addEventListener("click",u=>{u.target===i&&h(!1)}),o.append(r,d),s.append(o),i.append(s),this.root.append(i),d.focus()})}openForm(e){var d,h;this.formHost.replaceChildren();const t=c("div","ocw-form");t.append(c("div","ocw-form-title",e.icon?`${e.icon} ${e.label}`:e.label));const i=new Map;for(const u of e.input??[]){const x=c("label","ocw-form-row");if(x.append(c("span","ocw-form-lbl",u.label)),u.type==="select"&&((d=u.options)!=null&&d.length)){const p=c("select","ocw-form-input");u.required||p.append(c("option",void 0,"— select —"));for(const w of u.options){const f=c("option");f.value=w,f.textContent=w,p.append(f)}u.required&&(p.required=!0),x.append(p),i.set(u.name,p)}else{const p=c("input","ocw-form-input");p.type=u.type==="number"?"number":u.type==="date"?"datetime-local":"text",u.required&&(p.required=!0),x.append(p),i.set(u.name,p)}t.append(x)}const s=c("div","ocw-form-actions"),o=c("button","ocw-form-cancel","Cancel"),r=c("button","ocw-form-submit","Send");o.addEventListener("click",()=>this.formHost.replaceChildren()),r.addEventListener("click",()=>{const u={};for(const[x,p]of i){if(p.required&&!p.value){p.style.borderColor="#e5484d";return}u[x]=p.type==="number"?Number(p.value):p.value}this.formHost.replaceChildren(),this.h.onInvoke(e.id,u)}),s.append(o,r),t.append(s),this.formHost.append(t),(h=i.values().next().value)==null||h.focus()}messageEl(e,t){var p;if(e.senderRole==="system"){const w=c("div","ocw-sys");return w.textContent=e.deletedAt?"message deleted":Se(e.content),w}const i=e.senderId===this.me,s=!!e.internal,o=c("div",`ocw-row ${s?"ocw-note mine":i?"mine":"theirs"} ${e.senderRole==="bot"?"ocw-bot":""}`);!i&&!s&&o.append(c("div","ocw-dot",e.senderRole==="bot"?"🤖":"🧑"));const r=c("div"),d=c("div","ocw-bubble-wrap");if(e.replyToId){const w=c("div","ocw-reply-to","↩ replying to a message");w.style.cssText="font-size:11px;color:var(--ocw-mut);margin-bottom:2px;font-style:italic",r.append(w)}const h=c("div","ocw-bubble");let u=null;if(e.deletedAt)h.append(c("span","ocw-deleted","message deleted"));else if(e.content.kind==="attachment"){const w=e.content;if((p=w.mime)!=null&&p.startsWith("image/")){const f=document.createElement("img");f.src=w.url,f.alt=w.name??"image",f.style.cssText="max-width:220px;max-height:160px;border-radius:10px;display:block;cursor:pointer",f.addEventListener("click",()=>window.open(w.url,"_blank")),h.append(f)}else{const f=document.createElement("a");f.href=w.url,f.target="_blank",f.rel="noopener",f.style.cssText="display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none",f.append(c("span",void 0,"📄"),c("span",void 0,w.name??"file")),h.append(f)}}else if(e.content.kind==="appointment"){const w=e.content,f=c("div","ocw-appt");f.append(c("div","ocw-appt-title",`📅 ${w.title}`)),f.append(c("div","ocw-appt-time",new Date(w.startIso).toLocaleString()+" – "+new Date(w.endIso).toLocaleTimeString())),w.location&&f.append(c("div","ocw-appt-loc",`📍 ${w.location}`)),w.description&&f.append(c("div","ocw-appt-desc",w.description));const k=c("div","ocw-appt-links"),v=document.createElement("a");v.href=w.googleUrl,v.target="_blank",v.rel="noopener",v.className="ocw-appt-btn",v.textContent="📅 Add to Google Calendar";const y=document.createElement("a");y.href=w.icalUrl,y.download=`${w.title}.ics`,y.className="ocw-appt-btn ocw-appt-btn-sec",y.textContent="🍎 Apple / iCal",k.append(v,y),f.append(k),h.append(f)}else u=document.createTextNode(Se(e.content)),h.append(u),e.editedAt&&h.append(c("span","ocw-edited","(edited)"));if(d.append(h),!i&&!s&&this.h.onTranslate&&e.content.kind==="text"&&!e.deletedAt&&e.seq>0&&u){const w=e.content.text;if(w.trim()){const f=c("button","ocw-translate-btn","🌐");f.type="button",f.title="Translate",f.addEventListener("click",k=>{if(k.stopPropagation(),this.showingTranslation.has(e.id)){this.showingTranslation.delete(e.id),u.textContent=w,f.textContent="🌐",f.title="Translate";return}const v=this.translationCache.get(e.id);if(v!==void 0){this.showingTranslation.add(e.id),u.textContent=v,f.textContent="↩",f.title="Show original";return}f.textContent="⏳",this.h.onTranslate(w).then(y=>{if(y===null){f.textContent="⚠️",f.title="Translation unavailable",setTimeout(()=>{f.textContent="🌐",f.title="Translate"},1500);return}this.translationCache.set(e.id,y),this.showingTranslation.add(e.id),u.textContent=y,f.textContent="↩",f.title="Show original"})}),d.append(f)}}if(i&&!e.deletedAt&&e.seq>0&&(this.h.onEdit??this.h.onDelete)){const w=c("div","ocw-msg-menu");if(this.h.onEdit){const f=c("button",void 0,"✏️");f.title="Edit",f.addEventListener("click",k=>{k.stopPropagation();const v=Se(e.content),y=document.createElement("textarea");y.value=v,y.rows=Math.min(4,Math.ceil(v.length/40)+1),y.style.cssText="width:100%;resize:vertical;border:1px solid var(--ocw-accent);border-radius:8px;padding:6px 10px;font:inherit;font-size:14px;background:#fff;color:#1c1b1a;box-sizing:border-box";const S=c("button","ocw-form-submit","Save");S.style.cssText="margin-top:6px;padding:5px 14px;font-size:13px";const E=c("button","ocw-form-cancel","Cancel");E.style.cssText="margin-top:6px;padding:5px 10px;font-size:13px";const K=c("div");K.style.cssText="display:flex;gap:6px;justify-content:flex-end",K.append(E,S);const C=c("div");C.append(y,K),h.replaceChildren(C),y.focus(),y.select();const _=()=>h.replaceChildren(u??document.createTextNode(v));E.addEventListener("click",_),S.addEventListener("click",()=>{const L=y.value.trim();L&&L!==v&&this.h.onEdit(e.id,L),_()}),y.addEventListener("keydown",L=>{L.key==="Enter"&&!L.shiftKey&&(L.preventDefault(),S.click()),L.key==="Escape"&&_()})}),w.append(f)}if(this.h.onDelete){const f=c("button","del","🗑");f.title="Delete",f.addEventListener("click",k=>{k.stopPropagation(),this.h.onDelete(e.id)}),w.append(f)}d.append(w)}if(r.append(d),this.h.onReact&&!e.deletedAt&&e.seq>0){const w=c("div","ocw-react-wrap"),f=c("div","ocw-react");if(e.reactions&&Object.keys(e.reactions).length)for(const[y,S]of Object.entries(e.reactions)){const E=c("button",`ocw-react-pill${S.includes(this.me)?" mine":""}`,`${y} ${S.length}`);E.addEventListener("click",()=>{var K,C;return(C=(K=this.h).onReact)==null?void 0:C.call(K,e.id,y,S.includes(this.me))}),f.append(E)}const k=c("button","ocw-react-btn","+"),v=c("div","ocw-react-picker");for(const y of wn){const S=c("button",void 0,y);S.addEventListener("click",E=>{var C,_,L,F;E.stopPropagation();const K=(_=(C=e.reactions)==null?void 0:C[y])==null?void 0:_.includes(this.me);(F=(L=this.h).onReact)==null||F.call(L,e.id,y,!!K),v.style.display="none"}),v.append(S)}v.style.display="none",k.addEventListener("click",y=>{y.stopPropagation();const S=v.style.display==="none";v.style.display=S?"flex":"none",S&&document.addEventListener("click",()=>{v.style.display="none"},{once:!0})}),f.append(k),w.append(f,v),r.append(w)}else e.reactions&&Object.keys(e.reactions).length&&r.append(c("div","ocw-react",Object.entries(e.reactions).map(([w,f])=>`${w}${f.length}`).join(" ")));const x=c("div","ocw-time ocw-meta",mn(e.ts));if(i&&e.status){const w=c("span",`ocw-tick${e.status==="read"?" read":e.status==="delivered"?" delivered":""}`,kn(e.status));x.append(w)}return i&&e.seq>0&&t.lastReadByOthers>=e.seq&&x.append(c("span","ocw-seen"," · Seen")),r.append(x),o.append(r),o}}function kn(n){switch(n){case"read":return"✓✓";case"delivered":return"✓✓";case"sent":return"✓";default:return"🕓"}}const Sn=20;function Oe(n,e){var h;const t=n.trim().replace(/\/+$/,""),i=(h=t.match(/^(https|http|wss|ws):\/\//))==null?void 0:h[1],s=i?i==="https"||i==="wss":!0,o=(i?t.slice(i.length+3):t).replace(/\/ws$/,""),r=e?e.trim().replace(/\/+$/,""):`${s?"https":"http"}://${o}`;return{wsUrl:`${s?"wss":"ws"}://${o}/ws`,httpBase:r}}function Cn(n){return Oe(n).httpBase}function In(n,e,t,i){const s=`beforeSeq=${t}&limit=${i}`;return[`${n}/conversations/${e}/messages?${s}`,`${n}/conversations/${e}/history?${s}`]}async function Ne(n,e,t,i,s=Sn){for(const o of In(n,e,i,s))try{const r=await fetch(o,{headers:{authorization:`Bearer ${t}`}});if(!r.ok)continue;const d=await r.json();return{messages:d.messages??[],hasMore:d.hasMore??!1}}catch{}return null}async function En(n,e,t,i,s,o){const r=o?o.replace(/\/+$/,""):Cn(n),d=await Ne(r,t,e,Number.MAX_SAFE_INTEGER);if(!d||(d.messages.length?(i.apply({type:"sync",conversationId:t,messages:d.messages}),i.apply({type:"history",conversationId:t,messages:[],hasMore:d.hasMore}),s.render(i)):i.apply({type:"history",conversationId:t,messages:[],hasMore:!1}),!d.hasMore))return;let h=!1;const u=async()=>{if(h||!i.hasMoreHistory)return;h=!0;const f=i.messages()[0];if(!f){h=!1;return}const k=await Ne(r,t,e,f.seq);k&&(i.apply({type:"history",conversationId:t,messages:k.messages,hasMore:k.hasMore}),s.render(i)),h=!1},x=s.getScrollEl();if(!x)return;let p=!1;setTimeout(()=>{p=!0},300);const w=()=>{p&&x.scrollTop<80&&i.hasMoreHistory&&!h&&u()};x.addEventListener("scroll",w,{passive:!0}),s.setScrollCleanup(()=>x.removeEventListener("scroll",w))}const ne=new WeakMap,ce=new Map;function We(n){return`relay-launcher::${n.profileId}::${n.subjectId??""}`}let ie=null;function Tn(){if(ie&&ie.state!=="closed")return ie;try{return ie=new AudioContext,ie}catch{return null}}function Pn(n){var Qe,et,tt,nt,it;ne.has(n.el)&&(ne.get(n.el).close(),ne.delete(n.el)),n.launcher&&((Qe=ce.get(We(n)))==null||Qe.close());const e=lt();let t,i=!1;const s=n.token??n.userId??e,o=s!==e?e:void 0,{wsUrl:r,httpBase:d}=Oe(n.url,n.apiUrl);let h=new Xt(s);const u=n.subjectId?`${s}::${n.subjectId}`:s,x=new nn(u);let p,w=!1,f=null,k=null,v=null,y=null;!n.launcher&&!n.el.style.height&&n.el.clientHeight===0&&(n.el.style.width=n.el.style.width||"100%",n.el.style.height="600px");for(const l of x.load())h.addOptimistic(l.clientMsgId,l.content);let S=null,E=null,K=0,C=!n.launcher;if(n.launcher){const g=(n.position??"bottom-right").includes("right");S=document.createElement("div"),S.style.cssText=`position:fixed;${g?"right:20px":"left:20px"};bottom:20px;z-index:9999;display:flex;flex-direction:column;align-items:${g?"flex-end":"flex-start"};gap:12px`;const b=document.createElement("div"),B=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(max-width: 479px)"):null,pe=A=>{n.el.classList.toggle("ocw-fs",A),b.style.cssText=A?["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:16px","overflow:hidden","box-shadow:0 8px 40px rgba(0,0,0,.18)","display:none","flex-direction:column","background:#fff","transform-origin:bottom "+(g?"right":"left"),"transition:opacity .18s,transform .18s","opacity:0","transform:scale(.95)"].join(";")};pe((B==null?void 0:B.matches)??!1);const ue=A=>pe(A.matches);B==null||B.addEventListener("change",ue),f=B,k=ue,n.el.style.cssText="width:100%;height:100%;overflow:hidden",b.append(n.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>',$=document.createElement("button");$.type="button",$.style.cssText=["width:56px;height:56px;border-radius:50%",`background:${n.accent??"#4F63F5"}`,"color:#fff;border:none;cursor:pointer","box-shadow:0 4px 16px rgba(0,0,0,.25)","position:relative;flex:none","display:flex;align-items:center;justify-content:center","transition:transform .15s"].join(";"),$.onmouseenter=()=>{$.style.transform="scale(1.08)"},$.onmouseleave=()=>{$.style.transform="scale(1)"},E=document.createElement("span"),E.style.cssText="position:absolute;top:-4px;right:-4px;background:#ef4444;color:#fff;border-radius:50%;width:20px;height:20px;font-size:11px;font-weight:700;display:none;align-items:center;justify-content:center";const fe=()=>{$.innerHTML=C?Te:Ee,$.setAttribute("aria-label",C?"Close chat":"Open chat"),$.setAttribute("aria-expanded",String(C)),$.append(E)};fe(),S.append(b,$),document.body.append(S);const Pe=`ocw-teaser-dismissed::${n.profileId}`,we=typeof n.launcherMessage=="string"?{title:n.launcherMessage}:n.launcherMessage;let U=null;const Fn=()=>{try{return sessionStorage.getItem(Pe)==="1"}catch{return!1}},qn='<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>',st=()=>{const A=we!=null&&we.title?we:h.launcherMessage??void 0;if(!(!!(A!=null&&A.title)&&!C&&!Fn())){U&&(U.remove(),U=null);return}if(U)return;U=document.createElement("div"),U.setAttribute("role","button"),U.setAttribute("tabindex","0"),U.setAttribute("aria-label",A.title),U.style.cssText=["max-width:280px","background:#fff","border-radius:14px","box-shadow:0 6px 28px rgba(0,0,0,.16)","padding:14px 40px 14px 16px","position:relative","cursor:pointer","font-family:inherit",`align-self:${g?"flex-end":"flex-start"}`,"animation:ocw-teaser-in .22s ease-out"].join(";");const Ae=document.createElement("div");if(Ae.textContent=A.title,Ae.style.cssText="font-size:15px;font-weight:600;color:#111;line-height:1.35",U.append(Ae),A.subtitle){const O=document.createElement("div");O.style.cssText="display:flex;align-items:center;gap:6px;margin-top:6px;font-size:13px;color:#6b7280";const Be=document.createElement("span");Be.innerHTML=qn,Be.style.cssText=`color:${n.accent??"#4F63F5"};display:inline-flex`;const rt=document.createElement("span");rt.textContent=A.subtitle,O.append(Be,rt),U.append(O)}const J=document.createElement("button");J.type="button",J.setAttribute("aria-label","Dismiss"),J.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>',J.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",J.addEventListener("click",O=>{O.stopPropagation();try{sessionStorage.setItem(Pe,"1")}catch{}U&&(U.remove(),U=null)}),U.append(J);const ot=()=>{C||(C=!0,Ue(!0),fe(),K=0,E&&(E.style.display="none"),U&&(U.remove(),U=null))};U.addEventListener("click",ot),U.addEventListener("keydown",O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),ot())}),S.insertBefore(U,$)};if(!document.getElementById("ocw-teaser-style")){const A=document.createElement("style");A.id="ocw-teaser-style",A.textContent="@keyframes ocw-teaser-in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",document.head.append(A)}y=st,st();const Ue=A=>{A?(b.style.display="flex",requestAnimationFrame(()=>{b.style.opacity="1",b.style.transform="scale(1)"})):(b.style.opacity="0",b.style.transform="scale(.95)",setTimeout(()=>{C||(b.style.display="none")},180))};$.addEventListener("click",()=>{if(C=!C,Ue(C),fe(),C){K=0,E&&(E.style.display="none");try{sessionStorage.setItem(Pe,"1")}catch{}}y==null||y()}),v=A=>{A.key==="Escape"&&C&&(C=!1,Ue(!1),fe())},document.addEventListener("keydown",v)}const _=()=>{C||(K++,E&&(E.textContent=String(K),E.style.display="flex"))},L=()=>{try{const l=Tn();if(!l)return;l.state==="suspended"&&l.resume().catch(()=>{});const g=l.createOscillator(),b=l.createGain();g.connect(b),b.connect(l.destination),g.frequency.setValueAtTime(880,l.currentTime),g.frequency.exponentialRampToValueAtTime(440,l.currentTime+.15),b.gain.setValueAtTime(.3,l.currentTime),b.gain.exponentialRampToValueAtTime(.001,l.currentTime+.3),g.start(),g.stop(l.currentTime+.3)}catch{}},F=[],de=l=>{for(;F.length;){const g=F.shift();x.add({clientMsgId:g.clientMsgId,content:g.content,ts:Date.now()}),I.send({type:"send",conversationId:l,clientMsgId:g.clientMsgId,content:g.content})}};let I;const z=new un(`ocw-e2e-${n.profileId}`);let m=!1;const P=[],H=[];let Ye=!1;const Ie=(l,g)=>{z.sealText(g).then(b=>{p&&I.send({type:"send",conversationId:p,clientMsgId:l,content:b})})},zn=(l,g,b)=>{z.sealText(g,b).then(B=>{p&&I.send({type:"send",conversationId:p,clientMsgId:l,content:B})})},Dn=()=>{for(;P.length;){const l=P.shift();Ie(l.clientMsgId,l.text)}for(;H.length;){const l=H.shift();Ie(l.clientMsgId,l.text)}},$n=l=>{I.send({type:"fetchPrekey",targetUserId:l})},Rn=n.i18n??{},_n=["ar","he","fa","ur"],Hn=typeof navigator<"u"?(navigator.language??"").slice(0,2).toLowerCase():"";_n.includes(Hn)&&!n.el.dir&&(n.el.dir="rtl",n.el.style.fontFamily=n.el.style.fontFamily||"Tahoma,Arial,system-ui,sans-serif");const Ge=new Gt,Je=`oc_prechat_${n.profileId}_${s.slice(-8)}`,M=new vn(n.el,s,{onSend(l){const g=`cm_${Math.random().toString(36).slice(2)}`,b={kind:"text",text:l};h.addOptimistic(g,b),M.render(h),h.e2e?z.ready?Ie(g,l):Ye?H.push({clientMsgId:g,text:l}):(P.push({clientMsgId:g,text:l}),h.assignedAgentId&&$n(h.assignedAgentId)):p?(x.add({clientMsgId:g,content:b,ts:Date.now()}),I.send({type:"send",conversationId:p,clientMsgId:g,content:b})):F.push({clientMsgId:g,content:b})},async onAttach(l){if(!p)return;const g=`${d}/upload?name=${encodeURIComponent(l.name)}`,b=`cm_${Math.random().toString(36).slice(2)}`;h.addOptimistic(b,{kind:"text",text:`📎 Uploading ${l.name}…`}),M.render(h);try{const B=await fetch(g,{method:"POST",headers:{"content-type":l.type,authorization:`Bearer ${s}`},body:l});if(!B.ok)throw new Error(`Upload failed: ${B.status}`);const{url:pe,name:ue,mime:Ee,size:Te}=await B.json();I.send({type:"send",conversationId:p,clientMsgId:b,content:{kind:"attachment",url:pe,name:ue,mime:Ee,size:Te}})}catch(B){h.addOptimistic(b,{kind:"text",text:`⚠️ Upload failed: ${B.message}`}),M.render(h)}},onInvoke(l,g){p&&I.send({type:"invoke",conversationId:p,actionId:l,clientInvokeId:`iv_${Math.random().toString(36).slice(2)}`,...g?{inputs:g}:{}})},onTyping(l,g){p&&I.send({type:"typing",conversationId:p,isTyping:l,...g?{preview:g}:{}})},onPreChat(l){try{localStorage.setItem(Je,"1")}catch{}I.send({type:"open",profileId:n.profileId,...n.subjectId?{subjectId:n.subjectId}:{},userInfo:{...l.name?{name:l.name}:{},...l.email?{email:l.email}:{},...l.phone||l.topic?{meta:{...l.phone?{phone:l.phone}:{},...l.topic?{topic:l.topic}:{}}}:{}}});const g=l.callback?`📞 Call-back requested${l.phone?`: ${l.phone}`:""}${l.topic?` — ${l.topic}`:""}`:l.topic?`Topic: ${l.topic}`:"";g&&p&&!h.e2e&&I.send({type:"send",conversationId:p,clientMsgId:`pc_${Math.random().toString(36).slice(2,12)}`,content:{kind:"text",text:g}})},onDeflectQuery(l){if(i)return;clearTimeout(t);const g=l.trim();if(g.length<3){M.hideDeflection();return}t=setTimeout(()=>{fetch(`${d}/kb/search?profileId=${encodeURIComponent(n.profileId)}&q=${encodeURIComponent(g.slice(0,200))}`).then(b=>b.ok?b.json():{articles:[]}).then(b=>M.showDeflection(b.articles??[])).catch(()=>M.hideDeflection())},350)},onReadUpTo(l){p&&I.send({type:"read",conversationId:p,seq:l})},onLoadMore(){if(!p||!h.e2e)return;const l=h.messages()[0];l&&I.send({type:"history",conversationId:p,beforeSeq:l.seq,limit:20})},onEdit(l,g){p&&I.send({type:"edit",conversationId:p,messageId:l,content:{kind:"text",text:g}})},onDelete(l){p&&I.send({type:"delete",conversationId:p,messageId:l})},onReact(l,g,b){p&&I.send({type:"react",conversationId:p,messageId:l,emoji:g,remove:b})},onCsat(l){p&&fetch(`${d}/conversations/${p}/csat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({score:l})}).catch(()=>{})},onAnnotate(l){p&&I.send({type:"annotate",conversationId:p,stroke:l})},onAnnotateClear(){p&&I.send({type:"annotate_clear",conversationId:p})},...n.translateLang?{async onTranslate(l){try{const g=await fetch(`${d}/translate`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${s}`},body:JSON.stringify({text:l,targetLang:n.translateLang})});if(!g.ok)return null;const{translated:b}=await g.json();return b}catch{return null}}}:{},...n.onBack?{onBack:n.onBack}:{}},{...n.subject?{subject:n.subject}:{},...n.quickReplies?{quickReplies:n.quickReplies}:{},...n.accent?{accent:n.accent}:{},...(et=n.user)!=null&&et.name||(tt=n.user)!=null&&tt.avatar?{userInfo:{...n.user.name?{name:n.user.name}:{},...n.user.avatar?{avatar:n.user.avatar}:{}}}:{},i18n:Rn});try{localStorage.getItem(Je)&&M.completePreChat()}catch{}const Ze=n.user&&(n.user.name||n.user.email||n.user.avatar||n.user.meta)?{...n.user.name?{name:n.user.name}:{},...n.user.email?{email:n.user.email}:{},...n.user.avatar?{avatar:n.user.avatar}:{},...n.user.meta?{meta:n.user.meta}:{}}:void 0,jn={type:"open",profileId:n.profileId,...n.kind==="direct"&&n.peerId?{kind:"direct",peerId:n.peerId}:n.subjectId?{subjectId:n.subjectId}:{},...o?{linkFrom:o}:{},...Ze?{userInfo:Ze}:{},...typeof location<"u"?{pageUrl:location.href}:{},...typeof document<"u"&&document.title?{pageTitle:document.title}:{},...(nt=n.subject)!=null&&nt.title?{subjectTitle:n.subject.title}:{},...(it=n.subject)!=null&&it.subtitle?{subjectMeta:n.subject.subtitle}:{}};I=new Jt({...n.refreshToken?{refreshToken:n.refreshToken}:{},url:r,token:s,open:jn,getCursor:()=>h.highestSeq(),onStatusChange:(l,g)=>M.setConnStatus(l,g),onFrame(l){if(Ge.apply(l),l.type==="opened"){if(p=l.conversation.id,!w){w=!0;for(const g of x.load())I.send({type:"send",conversationId:p,clientMsgId:g.clientMsgId,content:g.content})}En(r,s,p,h,M,d),F.length&&de(p)}if(l.type==="ack"&&x.remove(l.clientMsgId),l.type==="prekeyBundle"){l.bundle&&(Ye=!0,z.x3dhSendTo(l.bundle).then(g=>{const b=[...P.splice(0),...H.splice(0)];for(const B of b)zn(B.clientMsgId,B.text,g);M.render(h)}));return}if(l.type==="message"&&h.e2e){const g=fn(l.message.content);if(g&&!z.ready){z.x3dhReceiveFrom(g.x3dhIK,g.x3dhEK,g.x3dhSPK).then(async()=>{await z.openFrame(l),h.apply(l),M.render(h)});return}}if(l.type==="peerkey"){z.onPeerKey(l.key).then(()=>{Dn(),M.render(h)});return}(async()=>{if(h.e2e&&await z.openFrame(l),h.apply(l),l.type==="manifest"&&(y==null||y()),l.type==="message"&&l.message.senderId!==s&&!l.message.internal&&(_(),L()),h.e2e&&p&&!m){m=!0;const g=await z.initX3DH();I.send({type:"uploadPrekeys",...g});const b=await z.begin();I.send({type:"pubkey",conversationId:p,key:b})}M.render(h)})()}}),I.connect(),M.render(h);const se=n.launcher?We(n):null,he={close:()=>{i=!0,clearTimeout(t),I.close(),S==null||S.remove(),M.destroy(),Ge.destroy(),f&&k&&f.removeEventListener("change",k),v&&(document.removeEventListener("keydown",v),v=null),ne.delete(n.el),se&&ce.get(se)===he&&ce.delete(se)}};return ne.set(n.el,he),se&&ce.set(se,he),he}const Un="wss://api.paramms.com/ws";let V=null,j=null,G={};function An(n,e){const t=n.profileId??n.appId;if(!t)throw new Error("Relay: `appId` is required (your chatroom id, e.g. 'p_...').");const i=n.subjectId??(n.listingId?`listing_${n.listingId}`:void 0),s=n.subjectTitle?{title:n.subjectTitle,...n.subjectMeta?{subtitle:n.subjectMeta}:{},...n.subjectPrice!=null?{tags:[`$${n.subjectPrice.toLocaleString()}`]}:{},...n.subjectStatus?{status:n.subjectStatus}:{}}:void 0,o=n.name||n.email||n.avatar?{...n.name?{name:n.name}:{},...n.email?{email:n.email}:{},...n.avatar?{avatar:n.avatar}:{}}:void 0;return{el:e,url:n.url??Un,profileId:t,...n.apiUrl?{apiUrl:n.apiUrl}:{},...i?{subjectId:i}:{},...n.token?{token:n.token}:{},...n.userId?{userId:n.userId}:{},...s?{subject:s}:{},...o?{user:o}:{},...n.accent?{accent:n.accent}:{},...n.translateLang?{translateLang:n.translateLang}:{},...n.launcherMessage?{launcherMessage:n.launcherSubtitle?{title:n.launcherMessage,subtitle:n.launcherSubtitle}:n.launcherMessage}:{},launcher:n.launcher??!0,position:n.position??"bottom-right"}}function Bn(){return(!j||!j.isConnected)&&(j=document.createElement("div"),j.id="relay-widget-root",document.body.appendChild(j)),j}function Ve(n){try{V==null||V.close(),V=Pn(An(n,Bn()))}catch(e){console.error("[Relay]",e instanceof Error?e.message:e)}}function Xe(n){G={...n},Ve(G)}function Kn(n){G={...G,...n},Ve(G)}function Ln(){V==null||V.close(),V=null,j==null||j.remove(),j=null,G={}}function Ce(n,e){switch(n){case"boot":Xe(e??{});break;case"update":case"identify":Kn(e??{});break;case"shutdown":Ln();break;default:console.warn("[Relay] unknown command:",n)}}function Mn(){if(typeof document>"u")return null;const n=document.querySelector("script[data-relay-app]"),e=n==null?void 0:n.dataset.relayApp;if(!e)return null;const t=n.dataset,i={appId:e};t.relayUser&&(i.userId=t.relayUser),t.relayToken&&(i.token=t.relayToken),t.relayListing&&(i.listingId=t.relayListing),t.relayAccent&&(i.accent=t.relayAccent),t.relayUrl&&(i.url=t.relayUrl);const s=t.relayPosition;return(s==="bottom-left"||s==="bottom-right")&&(i.position=s),t.relayLauncherMessage&&(i.launcherMessage=t.relayLauncherMessage),t.relayLauncherSubtitle&&(i.launcherSubtitle=t.relayLauncherSubtitle),t.relayLauncher==="false"&&(i.launcher=!1),i}if(typeof window<"u"){const n=window,e=n.Relay&&n.Relay.q?n.Relay.q:[];n.Relay=Ce;let t=!1;for(const i of e){const[s,o]=i;s==="boot"&&(t=!0),Ce(s,o)}if(!t){const i=n.relaySettings??Mn();i&&Xe(i)}}return q.Relay=Ce,Object.defineProperty(q,Symbol.toStringTag,{value:"Module"}),q}({});
177
195
  //# sourceMappingURL=embed.js.map