@paramms/chat-widget 1.0.32 → 1.0.34

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,4 +1,4 @@
1
- var RelayEmbed=function($){"use strict";var mn=Object.defineProperty;var vn=($,L,q)=>L in $?mn($,L,{enumerable:!0,configurable:!0,writable:!0,value:q}):$[L]=q;var a=($,L,q)=>vn($,typeof L!="symbol"?L+"":L,q);const L="oc_uid";function q(i){try{const e=document.cookie.match(new RegExp(`(?:^|; )${i}=([^;]*)`));return e?decodeURIComponent(e[1]):null}catch{return null}}function je(i,e){try{const n=location.protocol==="https:"?"; Secure":"";document.cookie=`${i}=${encodeURIComponent(e)}; Max-Age=31536000; Path=/; SameSite=Lax${n}`}catch{}}function qe(){return`g_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`}function Oe(){let i=null;try{i=localStorage.getItem(L)}catch{}i||(i=q(L));const e=i??qe();try{localStorage.setItem(L,e)}catch{}return je(L,e),e}function Ne(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 We(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 d=i.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 Ve=new TextEncoder,Xe=50;function Ye(i,e,t){Ve.encodeInto(i,e.subarray(t))}function Je(i,e,t){i.length>Xe?Ye(i,e,t):We(i,e,t)}const Ge=4096;function xe(i,e,t){let n=e;const s=n+t,o=[];let r="";for(;n<s;){const d=i[n++];if(!(d&128))o.push(d);else if((d&224)===192){const p=i[n++]&63;o.push((d&31)<<6|p)}else if((d&240)===224){const p=i[n++]&63,l=i[n++]&63;o.push((d&31)<<12|p<<6|l)}else if((d&248)===240){const p=i[n++]&63,l=i[n++]&63,b=i[n++]&63;let y=(d&7)<<18|p<<12|l<<6|b;y>65535&&(y-=65536,o.push(y>>>10&1023|55296),y=56320|y&1023),o.push(y)}else o.push(d);o.length>=Ge&&(r+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(r+=String.fromCharCode(...o)),r}const Ze=new TextDecoder,Qe=200;function et(i,e,t){const n=i.subarray(e,e+t);return Ze.decode(n)}function tt(i,e,t){return t>Qe?et(i,e,t):xe(i,e,t)}class Z{constructor(e,t){a(this,"type");a(this,"data");this.type=e,this.data=t}}class B extends Error{constructor(e){super(e);const t=Object.create(B.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:B.name})}}const W=4294967295;function nt(i,e,t){const n=t/4294967296,s=t;i.setUint32(e,n),i.setUint32(e+4,s)}function be(i,e,t){const n=Math.floor(t/4294967296),s=t;i.setUint32(e,n),i.setUint32(e+4,s)}function me(i,e){const t=i.getInt32(e),n=i.getUint32(e+4);return t*4294967296+n}function it(i,e){const t=i.getUint32(e),n=i.getUint32(e+4);return t*4294967296+n}const st=-1,ot=4294967296-1,rt=17179869184-1;function at({sec:i,nsec:e}){if(i>=0&&e>=0&&i<=rt)if(e===0&&i<=ot){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),be(n,4,i),t}}function ct(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 dt(i){if(i instanceof Date){const e=ct(i);return at(e)}else return null}function lt(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=me(e,4),n=e.getUint32(0);return{sec:t,nsec:n}}default:throw new B(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${i.length}`)}}function ht(i){const e=lt(i);return new Date(e.sec*1e3+e.nsec/1e6)}const ut={type:st,encode:dt,decode:ht},ne=class ne{constructor(){a(this,"__brand");a(this,"builtInEncoders",[]);a(this,"builtInDecoders",[]);a(this,"encoders",[]);a(this,"decoders",[]);this.register(ut)}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 Z(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 Z(r,o)}}}return e instanceof Z?e:null}decode(e,t,n){const s=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return s?s(e,t,n):new Z(t,e)}};a(ne,"defaultCodec",new ne);let Q=ne;function pt(i){return i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer}function ce(i){return i instanceof Uint8Array?i:ArrayBuffer.isView(i)?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):pt(i)?new Uint8Array(i):Uint8Array.from(i)}const ft=100,wt=2048;class de{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)??Q.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)??ft,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??wt,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 de({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=Ne(e);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),Je(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=ce(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),nt(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),be(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 yt(i,e){return new de(e).encodeSharedRef(i)}function le(i){return`${i<0?"-":""}0x${Math.abs(i).toString(16).padStart(2,"0")}`}const gt=16,xt=16;class bt{constructor(e=gt,t=xt){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 d=0;d<n;d++)if(r[d]!==e[t+d])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=xe(e,t,n),r=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(r,o),o}}const he="array",V="map_key",ve="map_value",mt=i=>{if(typeof i=="string"||typeof i=="number")return i;throw new B("The type of key must be string or number but "+typeof i)};class vt{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=he,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=V,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===he){const n=e;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(e.type===V||e.type===ve){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 X=-1,ue=new DataView(new ArrayBuffer(0)),kt=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 ke=new RangeError("Insufficient data"),St=new bt;class pe{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",kt);a(this,"headByte",X);a(this,"stack",new vt);a(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Q.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)??W,this.maxBinLength=(e==null?void 0:e.maxBinLength)??W,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??W,this.maxMapLength=(e==null?void 0:e.maxMapLength)??W,this.maxExtLength=(e==null?void 0:e.maxExtLength)??W,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:St,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??mt}clone(){return new pe({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=X,this.stack.reset()}setBuffer(e){const t=ce(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===X&&!this.hasRemaining(1))this.setBuffer(e);else{const t=this.bytes.subarray(this.pos),n=ce(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 d of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(d);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 ${le(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 B(`Unrecognized type byte: ${le(e)}`);this.complete();const n=this.stack;for(;n.length>0;){const s=n.top();if(s.type===he)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===V){if(t==="__proto__")throw new B("The key __proto__ is not allowed");s.key=this.mapKeyConverter(t),s.type=ve;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=V;continue e}}return t}}readHeadByte(){return this.headByte===X&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=X}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 B(`Unrecognized array type byte: ${le(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new B(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new B(`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 B(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw ke;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=tt(this.bytes,n,e),this.pos+=t+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===V:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new B(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw ke;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 B(`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=it(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 It(i,e){return new pe(e).decode(i)}const Et=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 Ct(i){return Et.has(i.type)}function Tt(i){return yt(i)}function Ut(i){let e;try{e=It(i)}catch{return null}return typeof e!="object"||e===null||typeof e.type!="string"?null:e}class At{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,"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);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=Se(t);let s=!1;for(const[o,r]of this.byId)r.senderId!==this.me||r.seq<=0||r.seq>e||Se(r.status)>=n||(this.byId.set(o,{...r,status:t}),s=!0);s&&(this._sorted=null)}}function Se(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",Pt=8e3;class Bt{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 d;if(typeof document>"u"||!((d=e.points)!=null&&d.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)},Pt);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 Kt{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??Mt)(this.opts.url);t.binaryType="arraybuffer",this.socket=t,t.onopen=()=>{this.raw({type:"auth",token:this.opts.token})},t.onmessage=o=>{const r=Ut(new Uint8Array(o.data));!r||Ct(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"&&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,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",Lt(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(Tt(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 zt=new Set(["UNAUTHORIZED"]);function Lt(i){switch(i){case"UNAUTHORIZED":return"Chat unavailable — sign-in/token was rejected";default:return"Chat unavailable"}}function Mt(i){return new WebSocket(i)}const Ee=200,Dt=7*864e5;class $t{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()-Dt,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 E=()=>globalThis.crypto.subtle;function ee(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 fe(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 Y(){const i=await E().generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]);return{publicKey:i.publicKey,privateKey:i.privateKey}}async function _(i){return ee(await E().exportKey("raw",i))}async function O(i){return E().importKey("raw",fe(i),{name:"ECDH",namedCurve:"P-256"},!1,[])}async function _t(i,e){const t=await O(e);return E().deriveKey({name:"ECDH",public:t},i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Rt(i,e){const t=globalThis.crypto.getRandomValues(new Uint8Array(12)),n=new TextEncoder().encode(e),s=await E().encrypt({name:"AES-GCM",iv:t},i,n);return{ct:ee(s),iv:ee(t)}}async function Ht(i,e,t){const n=await E().decrypt({name:"AES-GCM",iv:fe(t)},i,fe(e));return new TextDecoder().decode(n)}async function Ft(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),d=await E().importKey("jwk",o,{name:"ECDH",namedCurve:"P-256"},!0,[]),p=await E().importKey("jwk",r,{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]);return{publicKey:d,privateKey:p}}}catch{}const e=await Y();try{const s=await E().exportKey("jwk",e.publicKey),o=await E().exportKey("jwk",e.privateKey);(n=globalThis.localStorage)==null||n.setItem(i,JSON.stringify({pub:s,priv:o}))}catch{}return e}async function jt(i,e){const t=await E().exportKey("raw",e),n=await E().sign({name:"ECDSA",hash:"SHA-256"},i,t);return ee(n)}async function qt(){const i=await Y(),e=await E().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 Ce(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 E().importKey("jwk",o.ecdhPub,{name:"ECDH",namedCurve:"P-256"},!0,[]),d=await E().importKey("jwk",o.ecdhPriv,{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]),p=await E().importKey("jwk",o.ecdsaPub,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),l=await E().importKey("jwk",o.ecdsaPriv,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"]);return{ecdhKP:{publicKey:r,privateKey:d},ecdsaKP:{publicKey:p,privateKey:l},publicKeyB64:await _(r),sigPublicKeyB64:await _(p)}}}catch{}const e=await qt();try{const s=await E().exportKey("jwk",e.ecdhKP.publicKey),o=await E().exportKey("jwk",e.ecdhKP.privateKey),r=await E().exportKey("jwk",e.ecdsaKP.publicKey),d=await E().exportKey("jwk",e.ecdsaKP.privateKey);(n=globalThis.localStorage)==null||n.setItem(`${i}-identity`,JSON.stringify({ecdhPub:s,ecdhPriv:o,ecdsaPub:r,ecdsaPriv:d}))}catch{}return e}async function Ot(i,e){const t=await Y(),n=await _(t.publicKey),s=await O(e.identityKey),o=await O(e.signedPrekey),r=e.oneTimePrekey?await O(e.oneTimePrekey):null,d=await R(i.privateKey,o),p=await R(t.privateKey,s),l=await R(t.privateKey,o),b=r?await R(t.privateKey,r):null,y=Te(d,p,l,...b?[b]:[]);return{sharedKey:await Ue(y),ephemeralPublicKey:n}}async function Nt(i,e,t,n,s){const o=await O(t),r=await O(n),d=await R(e.privateKey,o),p=await R(i.privateKey,r),l=await R(e.privateKey,r),b=s?await R(s.privateKey,r):null,y=Te(d,p,l,...b?[b]:[]);return Ue(y)}async function R(i,e){return E().deriveBits({name:"ECDH",public:e},i,256)}function Te(...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 E().importKey("raw",i,"HKDF",!1,["deriveKey"]);return E().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 Wt=20;class Vt{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 Ft(this.storageKey),_(this.kp.publicKey)}async onPeerKey(e){this.kp&&(this.shared=await _t(this.kp.privateKey,e))}async initX3DH(){this.identityKP=await Ce(this.storageKey),this.signedPreKP=await Y(),this.signedPrekeyId=`spk-${Date.now()}-${Math.random().toString(36).slice(2)}`;for(let s=0;s<Wt;s++)this.otpKeys.push(await Y());const e=await _(this.signedPreKP.publicKey),t=await jt(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 Ce(this.storageKey));const{sharedKey:t,ephemeralPublicKey:n}=await Ot(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 Nt(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 Rt(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 Ht(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 Xt(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",Yt=["👍","❤️","😂","😮","😢","🙏"],Jt=`
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=`
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);
@@ -95,6 +95,17 @@ var RelayEmbed=function($){"use strict";var mn=Object.defineProperty;var vn=($,L
95
95
  .ocw-offline-input:focus { outline:none; border-color:var(--ocw-accent); }
96
96
  .ocw-offline-submit { background:var(--ocw-accent); color:#fff; border:none; border-radius:10px; padding:11px; font-size:14px; font-weight:600; cursor:pointer; }
97
97
  .ocw-offline-thanks { font-size:14px; color:#15803d; font-weight:600; }
98
+ .ocw-prechat { margin:20px 14px; padding:20px; background:#fff; border:1px solid #e3ded7; border-radius:16px; }
99
+ .ocw-prechat-title { font-weight:700; font-size:15px; margin-bottom:12px; }
100
+ .ocw-prechat select { border:1px solid #e3ded7; border-radius:10px; padding:10px 12px; font:inherit; font-size:13px; background:#fff; }
101
+ .ocw-prechat-cb { display:flex; align-items:center; gap:8px; font-size:13px; color:var(--ocw-ink); }
102
+ .ocw-deflect { margin:0 14px 8px; display:flex; flex-direction:column; gap:6px; }
103
+ .ocw-deflect-card { text-align:left; background:#fff; border:1px solid #e3ded7; border-radius:12px; padding:10px 12px; font:inherit; font-size:13px; cursor:pointer; }
104
+ .ocw-deflect-card:hover { border-color:var(--ocw-accent); }
105
+ .ocw-deflect-q { font-weight:600; margin-bottom:2px; }
106
+ .ocw-deflect-a { color:var(--ocw-mut); font-size:12.5px; display:none; white-space:pre-wrap; }
107
+ .ocw-deflect-card.open .ocw-deflect-a { display:block; }
108
+ .ocw-deflect-hint { font-size:11.5px; color:var(--ocw-mut); text-align:center; }
98
109
  .ocw-csat-title { font-size:13px; font-weight:600; margin-bottom:8px; }
99
110
  .ocw-csat-stars { display:flex; gap:6px; }
100
111
  .ocw-csat-star { background:none; border:none; font-size:22px; cursor:pointer; padding:2px; opacity:.4; transition:opacity .15s; }
@@ -157,8 +168,8 @@ var RelayEmbed=function($){"use strict";var mn=Object.defineProperty;var vn=($,L
157
168
  .ocw-row.theirs .ocw-translate-btn { right:auto; left:-26px; }
158
169
  .ocw-bubble-wrap:hover .ocw-translate-btn { opacity:1; }
159
170
  .ocw-translated-tag { font-size:10px; color:var(--ocw-mut); margin-top:2px; }
160
- `;function Gt(){if(typeof document>"u"||document.getElementById(Ae))return;const i=document.createElement("style");i.id=Ae,i.textContent=Jt,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 Zt(i){try{return new Date(i).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function we(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 Qt{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,"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 k,g,U,K,A,z,m,I,F;this.root=e,this.me=t,this.h=n,this.cfg=s,Gt(),e.replaceChildren(),e.classList.add("ocw"),s.accent&&e.style.setProperty("--ocw-accent",s.accent);const o=c("div","ocw-head"),r=c("div","ocw-avatar");if((k=s.userInfo)!=null&&k.avatar){const S=document.createElement("img");S.src=s.userInfo.avatar,S.alt=s.userInfo.name??"You",S.style.cssText="width:100%;height:100%;border-radius:50%;object-fit:cover",r.append(S)}else r.textContent=(g=s.userInfo)!=null&&g.name?s.userInfo.name[0].toUpperCase():"🧑";o.append(r);const d=c("div","ocw-head-main");this.headerName=c("div","ocw-head-name",((U=s.subject)==null?void 0:U.ownerLabel)??((K=s.subject)==null?void 0:K.title)??""),d.append(this.headerName),(A=s.subject)!=null&&A.subtitle&&d.append(c("div","ocw-head-meta",s.subject.subtitle)),o.append(d),this.statusBadge=c("span","ocw-badge",((z=s.subject)==null?void 0:z.status)??""),(m=s.subject)!=null&&m.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 S of s.quickReplies??[]){const T=c("button",void 0,S);T.addEventListener("click",()=>{this.h.onSend(S),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.input=c("textarea",void 0),this.input.rows=1,this.input.placeholder="Message…";const l=c("button","ocw-sendbtn",((I=s.i18n)==null?void 0:I.send)??"➤");l.addEventListener("click",()=>this.flushSend()),this.input.addEventListener("keydown",S=>{S.isComposing||S.keyCode===229||(S.key==="Enter"&&!S.shiftKey?(S.preventDefault(),this.flushSend()):this.signalTyping())});const b=c("button","ocw-attach","📎");b.title="Attach image or file";const y=document.createElement("input");y.type="file",y.accept="image/*,.pdf,.txt,.doc,.docx",y.style.display="none",b.addEventListener("click",()=>y.click()),y.addEventListener("change",()=>{var S;(S=y.files)!=null&&S[0]&&this.h.onAttach&&this.h.onAttach(y.files[0]),y.value=""});const f=c("div","ocw-input");f.append(b,y,this.input,l);const u=c("div","ocw-footer");((F=s.i18n)==null?void 0:F.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,f,this.footer),this.cobrowseCanvas=c("canvas","ocw-cobrowse-canvas"),this.cobrowseToolbar=c("div","ocw-cobrowse-toolbar");for(const S of["#f5713c","#1c1b1a","#2563eb","#16a34a","#dc2626"]){const T=c("button","ocw-cobrowse-swatch");T.style.background=S,T.type="button",S===this.cobrowseColor&&T.classList.add("sel"),T.addEventListener("click",()=>{this.cobrowseColor=S;for(const ie of this.cobrowseToolbar.querySelectorAll(".ocw-cobrowse-swatch"))ie.classList.remove("sel");T.classList.add("sel")}),this.cobrowseToolbar.append(T)}const v=c("button","ocw-cobrowse-clear","Clear");v.addEventListener("click",()=>{var S,T;return(T=(S=this.h).onAnnotateClear)==null?void 0:T.call(S)}),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()}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(){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,b,y;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 f=(l=this.cfg.subject)==null?void 0:l.ownerLabel;f&&(this.headerName.textContent=f)}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 f of t)this.chips.append(this.chipEl(f));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 f=c("div","ocw-load-more");f.textContent="↑ Loading earlier messages…",f.style.pointerEvents="none",this.scroll.append(f)}let o=0;for(const f of e.messages())this.scroll.append(this.messageEl(f,e)),f.senderId!==this.me&&f.seq>o&&(o=f.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 d=this.typing.querySelector(".ocw-typing-bubble");d&&d.setAttribute("aria-label",r.length?"typing":""),this.footer.style.display=e.whiteLabel?"none":"block",e.offline?(this.offlinePanel.style.display==="none"&&this.buildOfflinePanel(e.offlineMessage),this.offlinePanel.style.display="block",(b=this.root.querySelector(".ocw-input"))==null||b.style.setProperty("display","none")):(this.offlinePanel.style.display="none",(y=this.root.querySelector(".ocw-input"))==null||y.style.removeProperty("display"));const p=["resolved","closed","sold","issued","checked_out"];this.h.onCsat&&!this.csatSubmitted&&p.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 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"),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]
171
+ `;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 m,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"),r=c("div","ocw-avatar");if((m=s.userInfo)!=null&&m.avatar){const v=document.createElement("img");v.src=s.userInfo.avatar,v.alt=s.userInfo.name??"You",v.style.cssText="width:100%;height:100%;border-radius:50%;object-fit:cover",r.append(v)}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 v of s.quickReplies??[]){const T=c("button",void 0,v);T.addEventListener("click",()=>{this.h.onSend(v),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 v,T;this.storeRef&&!this.storeRef.messages().some(q=>q.senderRole==="guest")?(T=(v=this.h).onDeflectQuery)==null||T.call(v,this.input.value):this.hideDeflection()}),this.input.addEventListener("keydown",v=>{v.isComposing||v.keyCode===229||(v.key==="Enter"&&!v.shiftKey?(v.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 v;(v=l.files)!=null&&v[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 v of["#f5713c","#1c1b1a","#2563eb","#16a34a","#dc2626"]){const T=c("button","ocw-cobrowse-swatch");T.style.background=v,T.type="button",v===this.cobrowseColor&&T.classList.add("sel"),T.addEventListener("click",()=>{this.cobrowseColor=v;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 v,T;return(T=(v=this.h).onAnnotateClear)==null?void 0:T.call(v)}),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,m;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",(m=this.root.querySelector(".ocw-input"))==null||m.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]
161
172
  Name: ${n.value||"Anonymous"}
162
173
  Email: ${s.value}
163
- 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)}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 d=this.cobrowseCanvas.getBoundingClientRect(),p=d.width>0?(r.clientX-d.left)/d.width:0,l=d.height>0?(r.clientY-d.top)/d.height:0;return{x:Math.min(1,Math.max(0,p)),y:Math.min(1,Math.max(0,l))}},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 d,p;if(e){e=!1,t.length>1&&((p=(d=this.h).onAnnotate)==null||p.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,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[d,p]of Object.entries(t.fields))o.append(c("span","ocw-tag",`${d}: ${p}`));else for(const d of(n==null?void 0:n.tags)??[])o.append(c("span","ocw-tag",d));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"),d=c("button","ocw-modal-ok","Confirm"),p=l=>{n.remove(),t(l)};r.addEventListener("click",()=>p(!1)),d.addEventListener("click",()=>p(!0)),n.addEventListener("click",l=>{l.target===n&&p(!1)}),o.append(r,d),s.append(o),n.append(s),this.root.append(n),d.focus()})}openForm(e){var d,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 l of e.input??[]){const b=c("label","ocw-form-row");if(b.append(c("span","ocw-form-lbl",l.label)),l.type==="select"&&((d=l.options)!=null&&d.length)){const y=c("select","ocw-form-input");l.required||y.append(c("option",void 0,"— select —"));for(const f of l.options){const u=c("option");u.value=f,u.textContent=f,y.append(u)}l.required&&(y.required=!0),b.append(y),n.set(l.name,y)}else{const y=c("input","ocw-form-input");y.type=l.type==="number"?"number":l.type==="date"?"datetime-local":"text",l.required&&(y.required=!0),b.append(y),n.set(l.name,y)}t.append(b)}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 l={};for(const[b,y]of n){if(y.required&&!y.value){y.style.borderColor="#e5484d";return}l[b]=y.type==="number"?Number(y.value):y.value}this.formHost.replaceChildren(),this.h.onInvoke(e.id,l)}),s.append(o,r),t.append(s),this.formHost.append(t),(p=n.values().next().value)==null||p.focus()}messageEl(e,t){var y;if(e.senderRole==="system"){const f=c("div","ocw-sys");return f.textContent=e.deletedAt?"message deleted":we(e.content),f}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"),d=c("div","ocw-bubble-wrap");if(e.replyToId){const f=c("div","ocw-reply-to","↩ replying to a message");f.style.cssText="font-size:11px;color:var(--ocw-mut);margin-bottom:2px;font-style:italic",r.append(f)}const p=c("div","ocw-bubble");let l=null;if(e.deletedAt)p.append(c("span","ocw-deleted","message deleted"));else if(e.content.kind==="attachment"){const f=e.content;if((y=f.mime)!=null&&y.startsWith("image/")){const u=document.createElement("img");u.src=f.url,u.alt=f.name??"image",u.style.cssText="max-width:220px;max-height:160px;border-radius:10px;display:block;cursor:pointer",u.addEventListener("click",()=>window.open(f.url,"_blank")),p.append(u)}else{const u=document.createElement("a");u.href=f.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,f.name??"file")),p.append(u)}}else if(e.content.kind==="appointment"){const f=e.content,u=c("div","ocw-appt");u.append(c("div","ocw-appt-title",`📅 ${f.title}`)),u.append(c("div","ocw-appt-time",new Date(f.startIso).toLocaleString()+" – "+new Date(f.endIso).toLocaleTimeString())),f.location&&u.append(c("div","ocw-appt-loc",`📍 ${f.location}`)),f.description&&u.append(c("div","ocw-appt-desc",f.description));const v=c("div","ocw-appt-links"),k=document.createElement("a");k.href=f.googleUrl,k.target="_blank",k.rel="noopener",k.className="ocw-appt-btn",k.textContent="📅 Add to Google Calendar";const g=document.createElement("a");g.href=f.icalUrl,g.download=`${f.title}.ics`,g.className="ocw-appt-btn ocw-appt-btn-sec",g.textContent="🍎 Apple / iCal",v.append(k,g),u.append(v),p.append(u)}else l=document.createTextNode(we(e.content)),p.append(l),e.editedAt&&p.append(c("span","ocw-edited","(edited)"));if(d.append(p),!n&&!s&&this.h.onTranslate&&e.content.kind==="text"&&!e.deletedAt&&e.seq>0&&l){const f=e.content.text;if(f.trim()){const u=c("button","ocw-translate-btn","🌐");u.type="button",u.title="Translate",u.addEventListener("click",v=>{if(v.stopPropagation(),this.showingTranslation.has(e.id)){this.showingTranslation.delete(e.id),l.textContent=f,u.textContent="🌐",u.title="Translate";return}const k=this.translationCache.get(e.id);if(k!==void 0){this.showingTranslation.add(e.id),l.textContent=k,u.textContent="↩",u.title="Show original";return}u.textContent="⏳",this.h.onTranslate(f).then(g=>{if(g===null){u.textContent="⚠️",u.title="Translation unavailable",setTimeout(()=>{u.textContent="🌐",u.title="Translate"},1500);return}this.translationCache.set(e.id,g),this.showingTranslation.add(e.id),l.textContent=g,u.textContent="↩",u.title="Show original"})}),d.append(u)}}if(n&&!e.deletedAt&&e.seq>0&&(this.h.onEdit??this.h.onDelete)){const f=c("div","ocw-msg-menu");if(this.h.onEdit){const u=c("button",void 0,"✏️");u.title="Edit",u.addEventListener("click",v=>{v.stopPropagation();const k=we(e.content),g=document.createElement("textarea");g.value=k,g.rows=Math.min(4,Math.ceil(k.length/40)+1),g.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 U=c("button","ocw-form-submit","Save");U.style.cssText="margin-top:6px;padding:5px 14px;font-size:13px";const K=c("button","ocw-form-cancel","Cancel");K.style.cssText="margin-top:6px;padding:5px 10px;font-size:13px";const A=c("div");A.style.cssText="display:flex;gap:6px;justify-content:flex-end",A.append(K,U);const z=c("div");z.append(g,A),p.replaceChildren(z),g.focus(),g.select();const m=()=>p.replaceChildren(l??document.createTextNode(k));K.addEventListener("click",m),U.addEventListener("click",()=>{const I=g.value.trim();I&&I!==k&&this.h.onEdit(e.id,I),m()}),g.addEventListener("keydown",I=>{I.key==="Enter"&&!I.shiftKey&&(I.preventDefault(),U.click()),I.key==="Escape"&&m()})}),f.append(u)}if(this.h.onDelete){const u=c("button","del","🗑");u.title="Delete",u.addEventListener("click",v=>{v.stopPropagation(),this.h.onDelete(e.id)}),f.append(u)}d.append(f)}if(r.append(d),this.h.onReact&&!e.deletedAt&&e.seq>0){const f=c("div","ocw-react-wrap"),u=c("div","ocw-react");if(e.reactions&&Object.keys(e.reactions).length)for(const[g,U]of Object.entries(e.reactions)){const K=c("button",`ocw-react-pill${U.includes(this.me)?" mine":""}`,`${g} ${U.length}`);K.addEventListener("click",()=>{var A,z;return(z=(A=this.h).onReact)==null?void 0:z.call(A,e.id,g,U.includes(this.me))}),u.append(K)}const v=c("button","ocw-react-btn","+"),k=c("div","ocw-react-picker");for(const g of Yt){const U=c("button",void 0,g);U.addEventListener("click",K=>{var z,m,I,F;K.stopPropagation();const A=(m=(z=e.reactions)==null?void 0:z[g])==null?void 0:m.includes(this.me);(F=(I=this.h).onReact)==null||F.call(I,e.id,g,!!A),k.style.display="none"}),k.append(U)}k.style.display="none",v.addEventListener("click",g=>{g.stopPropagation(),k.style.display=k.style.display==="none"?"flex":"none"}),document.addEventListener("click",()=>{k.style.display="none"},{once:!0}),u.append(v),f.append(u,k),r.append(f)}else e.reactions&&Object.keys(e.reactions).length&&r.append(c("div","ocw-react",Object.entries(e.reactions).map(([f,u])=>`${f}${u.length}`).join(" ")));const b=c("div","ocw-time ocw-meta",Zt(e.ts));if(n&&e.status){const f=c("span",`ocw-tick${e.status==="read"?" read":e.status==="delivered"?" delivered":""}`,en(e.status));b.append(f)}return n&&e.seq>0&&t.lastReadByOthers>=e.seq&&b.append(c("span","ocw-seen"," · Seen")),r.append(b),o.append(r),o}}function en(i){switch(i){case"read":return"✓✓";case"delivered":return"✓✓";case"sent":return"✓";default:return"🕓"}}const tn=20;function Pe(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 nn(i){return Pe(i).httpBase}function sn(i,e,t,n){const s=`beforeSeq=${t}&limit=${n}`;return[`${i}/conversations/${e}/messages?${s}`,`${i}/conversations/${e}/history?${s}`]}async function Be(i,e,t,n,s=tn){for(const o of sn(i,e,n,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 on(i,e,t,n,s,o){const r=o?o.replace(/\/+$/,""):nn(i),d=await Be(r,t,e,Number.MAX_SAFE_INTEGER);if(!d||(d.messages.length?(n.apply({type:"sync",conversationId:t,messages:d.messages}),n.apply({type:"history",conversationId:t,messages:[],hasMore:d.hasMore}),s.render(n)):n.apply({type:"history",conversationId:t,messages:[],hasMore:!1}),!d.hasMore))return;let p=!1;const l=async()=>{if(p||!n.hasMoreHistory)return;p=!0;const u=n.messages()[0];if(!u){p=!1;return}const v=await Be(r,t,e,u.seq);v&&(n.apply({type:"history",conversationId:t,messages:v.messages,hasMore:v.hasMore}),s.render(n)),p=!1},b=s.getScrollEl();if(!b)return;let y=!1;setTimeout(()=>{y=!0},300);const f=()=>{y&&b.scrollTop<80&&n.hasMoreHistory&&!p&&l()};b.addEventListener("scroll",f,{passive:!0}),s.setScrollCleanup(()=>b.removeEventListener("scroll",f))}const J=new WeakMap,te=new Map;function Ke(i){return`relay-launcher::${i.profileId}::${i.subjectId??""}`}function rn(i){var $e,_e,Re,He,Fe;J.has(i.el)&&(J.get(i.el).close(),J.delete(i.el)),i.launcher&&(($e=te.get(Ke(i)))==null||$e.close());const e=Oe(),t=i.token??i.userId??e,n=t!==e?e:void 0,{wsUrl:s,httpBase:o}=Pe(i.url,i.apiUrl);let r=new At(t);const d=i.subjectId?`${t}::${i.subjectId}`:t,p=new $t(d);let l,b=!1,y=null,f=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 h of p.load())r.addOptimistic(h.clientMsgId,h.content);let u=null,v=null,k=0,g=!i.launcher;if(i.launcher){const w=(i.position??"bottom-right").includes("right");u=document.createElement("div"),u.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 x=document.createElement("div"),C=typeof window<"u"?window.matchMedia("(max-width: 479px)"):null,oe=j=>{x.style.cssText=j?["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(";")};oe((C==null?void 0:C.matches)??!1);const re=j=>oe(j.matches);C==null||C.addEventListener("change",re),y=C,f=re,i.el.style.cssText="width:100%;height:100%;overflow:hidden",x.append(i.el);const P=document.createElement("button");P.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(";"),P.textContent="💬",P.onmouseenter=()=>{P.style.transform="scale(1.08)"},P.onmouseleave=()=>{P.style.transform="scale(1)"},v=document.createElement("span"),v.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",P.append(v),u.append(x,P),document.body.append(u);const ae=j=>{j?(x.style.display="flex",requestAnimationFrame(()=>{x.style.opacity="1",x.style.transform="scale(1)"})):(x.style.opacity="0",x.style.transform="scale(.95)",setTimeout(()=>{g||(x.style.display="none")},180))};P.addEventListener("click",()=>{g=!g,ae(g),P.textContent=g?"✕":"💬",P.append(v),g&&(k=0,v&&(v.style.display="none"))}),document.addEventListener("keydown",j=>{j.key==="Escape"&&g&&(g=!1,ae(!1),P.textContent="💬",P.append(v))})}const U=()=>{g||(k++,v&&(v.textContent=String(k),v.style.display="flex"))},K=()=>{try{const h=new AudioContext,w=h.createOscillator(),x=h.createGain();w.connect(x),x.connect(h.destination),w.frequency.setValueAtTime(880,h.currentTime),w.frequency.exponentialRampToValueAtTime(440,h.currentTime+.15),x.gain.setValueAtTime(.3,h.currentTime),x.gain.exponentialRampToValueAtTime(.001,h.currentTime+.3),w.start(),w.stop(h.currentTime+.3)}catch{}},A=[],z=h=>{for(;A.length;){const w=A.shift();p.add({clientMsgId:w.clientMsgId,content:w.content,ts:Date.now()}),m.send({type:"send",conversationId:h,clientMsgId:w.clientMsgId,content:w.content})}};let m;const I=new Vt(`ocw-e2e-${i.profileId}`);let F=!1;const S=[],T=[];let ie=!1;const ge=(h,w)=>{I.sealText(w).then(x=>{l&&m.send({type:"send",conversationId:l,clientMsgId:h,content:x})})},pn=(h,w,x)=>{I.sealText(w,x).then(C=>{l&&m.send({type:"send",conversationId:l,clientMsgId:h,content:C})})},fn=()=>{for(;S.length;){const h=S.shift();ge(h.clientMsgId,h.text)}for(;T.length;){const h=T.shift();ge(h.clientMsgId,h.text)}},wn=h=>{m.send({type:"fetchPrekey",targetUserId:h})},yn=i.i18n??{},gn=["ar","he","fa","ur"],xn=typeof navigator<"u"?(navigator.language??"").slice(0,2).toLowerCase():"";gn.includes(xn)&&!i.el.dir&&(i.el.dir="rtl",i.el.style.fontFamily=i.el.style.fontFamily||"Tahoma,Arial,system-ui,sans-serif");const Me=new Bt,M=new Qt(i.el,t,{onSend(h){const w=`cm_${Math.random().toString(36).slice(2)}`,x={kind:"text",text:h};r.addOptimistic(w,x),M.render(r),r.e2e?I.ready?ge(w,h):ie?T.push({clientMsgId:w,text:h}):(S.push({clientMsgId:w,text:h}),r.assignedAgentId&&wn(r.assignedAgentId)):l?(p.add({clientMsgId:w,content:x,ts:Date.now()}),m.send({type:"send",conversationId:l,clientMsgId:w,content:x})):A.push({clientMsgId:w,content:x})},async onAttach(h){if(!l)return;const w=`${o}/upload?name=${encodeURIComponent(h.name)}`,x=`cm_${Math.random().toString(36).slice(2)}`;r.addOptimistic(x,{kind:"text",text:`📎 Uploading ${h.name}…`}),M.render(r);try{const C=await fetch(w,{method:"POST",headers:{"content-type":h.type,...i.token?{authorization:`Bearer ${i.token}`}:{}},body:h});if(!C.ok)throw new Error(`Upload failed: ${C.status}`);const{url:oe,name:re,mime:P,size:ae}=await C.json();m.send({type:"send",conversationId:l,clientMsgId:x,content:{kind:"attachment",url:oe,name:re,mime:P,size:ae}})}catch(C){r.addOptimistic(x,{kind:"text",text:`⚠️ Upload failed: ${C.message}`}),M.render(r)}},onInvoke(h,w){l&&m.send({type:"invoke",conversationId:l,actionId:h,clientInvokeId:`iv_${Math.random().toString(36).slice(2)}`,...w?{inputs:w}:{}})},onTyping(h,w){l&&m.send({type:"typing",conversationId:l,isTyping:h,...w?{preview:w}:{}})},onReadUpTo(h){l&&m.send({type:"read",conversationId:l,seq:h})},onLoadMore(){if(!l||!r.e2e)return;const h=r.messages()[0];h&&m.send({type:"history",conversationId:l,beforeSeq:h.seq,limit:20})},onEdit(h,w){l&&m.send({type:"edit",conversationId:l,messageId:h,content:{kind:"text",text:w}})},onDelete(h){l&&m.send({type:"delete",conversationId:l,messageId:h})},onReact(h,w,x){l&&m.send({type:"react",conversationId:l,messageId:h,emoji:w,remove:x})},onCsat(h){l&&fetch(`${o}/conversations/${l}/csat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({score:h})}).catch(()=>{})},onAnnotate(h){l&&m.send({type:"annotate",conversationId:l,stroke:h})},onAnnotateClear(){l&&m.send({type:"annotate_clear",conversationId:l})},...i.translateLang?{async onTranslate(h){try{const w=await fetch(`${o}/translate`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:JSON.stringify({text:h,targetLang:i.translateLang})});if(!w.ok)return null;const{translated:x}=await w.json();return x}catch{return null}}}:{}},{...i.subject?{subject:i.subject}:{},...i.quickReplies?{quickReplies:i.quickReplies}:{},...i.accent?{accent:i.accent}:{},...(_e=i.user)!=null&&_e.name||(Re=i.user)!=null&&Re.avatar?{userInfo:{...i.user.name?{name:i.user.name}:{},...i.user.avatar?{avatar:i.user.avatar}:{}}}:{},i18n:yn}),De=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,bn={type:"open",profileId:i.profileId,...i.subjectId?{subjectId:i.subjectId}:{},...n?{linkFrom:n}:{},...De?{userInfo:De}:{},...typeof location<"u"?{pageUrl:location.href}:{},...typeof document<"u"&&document.title?{pageTitle:document.title}:{},...(He=i.subject)!=null&&He.title?{subjectTitle:i.subject.title}:{},...(Fe=i.subject)!=null&&Fe.subtitle?{subjectMeta:i.subject.subtitle}:{}};m=new Kt({...i.refreshToken?{refreshToken:i.refreshToken}:{},url:s,token:t,open:bn,getCursor:()=>r.highestSeq(),onStatusChange:(h,w)=>M.setConnStatus(h,w),onFrame(h){if(Me.apply(h),h.type==="opened"){if(l=h.conversation.id,!b){b=!0;for(const w of p.load())m.send({type:"send",conversationId:l,clientMsgId:w.clientMsgId,content:w.content})}on(s,t,l,r,M,o),A.length&&z(l)}if(h.type==="ack"&&p.remove(h.clientMsgId),h.type==="prekeyBundle"){h.bundle&&(ie=!0,I.x3dhSendTo(h.bundle).then(w=>{const x=[...S.splice(0),...T.splice(0)];for(const C of x)pn(C.clientMsgId,C.text,w);M.render(r)}));return}if(h.type==="message"&&r.e2e){const w=Xt(h.message.content);if(w&&!I.ready){I.x3dhReceiveFrom(w.x3dhIK,w.x3dhEK,w.x3dhSPK).then(async()=>{await I.openFrame(h),r.apply(h),M.render(r)});return}}if(h.type==="peerkey"){I.onPeerKey(h.key).then(()=>{fn(),M.render(r)});return}(async()=>{if(r.e2e&&await I.openFrame(h),r.apply(h),h.type==="message"&&h.message.senderId!==t&&!h.message.internal&&(U(),K()),r.e2e&&l&&!F){F=!0;const w=await I.initX3DH();m.send({type:"uploadPrekeys",...w});const x=await I.begin();m.send({type:"pubkey",conversationId:l,key:x})}M.render(r)})()}}),m.connect(),M.render(r);const G=i.launcher?Ke(i):null,se={close:()=>{m.close(),u==null||u.remove(),M.destroy(),Me.destroy(),y&&f&&y.removeEventListener("change",f),J.delete(i.el),G&&te.get(G)===se&&te.delete(G)}};return J.set(i.el,se),G&&te.set(G,se),se}const an="wss://api.paramms.com/ws";let H=null,D=null,N={};function cn(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??an,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 dn(){return(!D||!D.isConnected)&&(D=document.createElement("div"),D.id="relay-widget-root",document.body.appendChild(D)),D}function ze(i){try{H==null||H.close(),H=rn(cn(i,dn()))}catch(e){console.error("[Relay]",e instanceof Error?e.message:e)}}function Le(i){N={...i},ze(N)}function ln(i){N={...N,...i},ze(N)}function hn(){H==null||H.close(),H=null,D==null||D.remove(),D=null,N={}}function ye(i,e){switch(i){case"boot":Le(e??{});break;case"update":case"identify":ln(e??{});break;case"shutdown":hn();break;default:console.warn("[Relay] unknown command:",i)}}function un(){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=ye;let t=!1;for(const n of e){const[s,o]=n;s==="boot"&&(t=!0),ye(s,o)}if(!t){const n=i.relaySettings??un();n&&Le(n)}}return $.Relay=ye,Object.defineProperty($,Symbol.toStringTag,{value:"Module"}),$}({});
174
+ 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,m,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&&((m=e.topics)!=null&&m.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"),m=document.createElement("a");m.href=x.googleUrl,m.target="_blank",m.rel="noopener",m.className="ocw-appt-btn",m.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(m,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 m=this.translationCache.get(e.id);if(m!==void 0){this.showingTranslation.add(e.id),f.textContent=m,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 m=ye(e.content),y=document.createElement("textarea");y.value=m,y.rows=Math.min(4,Math.ceil(m.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(m));I.addEventListener("click",A),E.addEventListener("click",()=>{const U=y.value.trim();U&&U!==m&&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","+"),m=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),m.style.display="none"}),m.append(E)}m.style.display="none",S.addEventListener("click",y=>{y.stopPropagation(),m.style.display=m.style.display==="none"?"flex":"none"}),document.addEventListener("click",()=>{m.style.display="none"},{once:!0}),u.append(S),x.append(u,m),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 m=null,y=null,E=0,I=!i.launcher;if(i.launcher){const w=(i.position??"bottom-right").includes("right");m=document.createElement("div"),m.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 b=document.createElement("div"),P=typeof window<"u"?window.matchMedia("(max-width: 479px)"):null,re=F=>{b.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",b.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),m.append(b,K),document.body.append(m);const ce=F=>{F?(b.style.display="flex",requestAnimationFrame(()=>{b.style.opacity="1",b.style.transform="scale(1)"})):(b.style.opacity="0",b.style.transform="scale(.95)",setTimeout(()=>{I||(b.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(),b=d.createGain();w.connect(b),b.connect(d.destination),w.frequency.setValueAtTime(880,d.currentTime),w.frequency.exponentialRampToValueAtTime(440,d.currentTime+.15),b.gain.setValueAtTime(.3,d.currentTime),b.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 v=new Jt(`ocw-e2e-${i.profileId}`);let T=!1;const q=[],se=[];let De=!1;const ge=(d,w)=>{v.sealText(w).then(b=>{l&&k.send({type:"send",conversationId:l,clientMsgId:d,content:b})})},yn=(d,w,b)=>{v.sealText(w,b).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)}`,b={kind:"text",text:d};p.addOptimistic(w,b),B.render(p),p.e2e?v.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:b,ts:Date.now()}),k.send({type:"send",conversationId:l,clientMsgId:w,content:b})):A.push({clientMsgId:w,content:b})},async onAttach(d){if(!l)return;const w=`${h}/upload?name=${encodeURIComponent(d.name)}`,b=`cm_${Math.random().toString(36).slice(2)}`;p.addOptimistic(b,{kind:"text",text:`📎 Uploading ${d.name}…`}),B.render(p);try{const P=await fetch(w,{method:"POST",headers:{"content-type":d.type,...i.token?{authorization:`Bearer ${i.token}`}:{}},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:b,content:{kind:"attachment",url:re,name:ae,mime:K,size:ce}})}catch(P){p.addOptimistic(b,{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(b=>b.ok?b.json():{articles:[]}).then(b=>B.showDeflection(b.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,b){l&&k.send({type:"react",conversationId:l,messageId:d,emoji:w,remove:b})},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:b}=await w.json();return b}catch{return null}}}:{}},{...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,v.x3dhSendTo(d.bundle).then(w=>{const b=[...q.splice(0),...se.splice(0)];for(const P of b)yn(P.clientMsgId,P.text,w);B.render(p)}));return}if(d.type==="message"&&p.e2e){const w=Gt(d.message.content);if(w&&!v.ready){v.x3dhReceiveFrom(w.x3dhIK,w.x3dhEK,w.x3dhSPK).then(async()=>{await v.openFrame(d),p.apply(d),B.render(p)});return}}if(d.type==="peerkey"){v.onPeerKey(d.key).then(()=>{xn(),B.render(p)});return}(async()=>{if(p.e2e&&await v.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 v.initX3DH();k.send({type:"uploadPrekeys",...w});const b=await v.begin();k.send({type:"pubkey",conversationId:l,key:b})}B.render(p)})()}}),k.connect(),B.render(p);const Z=i.launcher?ze(i):null,oe={close:()=>{n=!0,clearTimeout(t),k.close(),m==null||m.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}({});
164
175
  //# sourceMappingURL=embed.js.map