@paramms/chat-widget 1.0.42 → 1.0.43
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/chatlist.d.ts +4 -0
- package/dist/chatlist.js +48 -44
- package/dist/chatlist.js.map +1 -1
- package/dist/codec.js +130 -125
- package/dist/codec.js.map +1 -1
- package/dist/embed.js +7 -3
- package/dist/embed.js.map +1 -1
- package/dist/react.js +94 -91
- package/dist/react.js.map +1 -1
- package/package.json +1 -1
package/dist/embed.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var RelayEmbed=function(J){"use strict";var ni=Object.defineProperty;var ii=(J,X,ce)=>X in J?ni(J,X,{enumerable:!0,configurable:!0,writable:!0,value:ce}):J[X]=ce;var a=(J,X,ce)=>ii(J,typeof X!="symbol"?X+"":X,ce);const X="oc_uid";function ce(n){try{const e=document.cookie.match(new RegExp(`(?:^|; )${n}=([^;]*)`));return e?decodeURIComponent(e[1]):null}catch{return null}}function Ct(n,e){try{const o=location.protocol==="https:"?"; Secure":"";document.cookie=`${n}=${encodeURIComponent(e)}; Max-Age=31536000; Path=/; SameSite=Lax${o}`}catch{}}function Et(){return`g_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`}function et(){let n=null;try{n=localStorage.getItem(X)}catch{}n||(n=ce(X));const e=n??Et();try{localStorage.setItem(X,e)}catch{}return Ct(X,e),e}function Tt(n){const e=n.length;let t=0,o=0;for(;o<e;){let i=n.charCodeAt(o++);if(i&4294967168)if(!(i&4294965248))t+=2;else{if(i>=55296&&i<=56319&&o<e){const s=n.charCodeAt(o);(s&64512)===56320&&(++o,i=((i&1023)<<10)+(s&1023)+65536)}i&4294901760?t+=4:t+=3}else{t++;continue}}return t}function Ut(n,e,t){const o=n.length;let i=t,s=0;for(;s<o;){let r=n.charCodeAt(s++);if(r&4294967168)if(!(r&4294965248))e[i++]=r>>6&31|192;else{if(r>=55296&&r<=56319&&s<o){const p=n.charCodeAt(s);(p&64512)===56320&&(++s,r=((r&1023)<<10)+(p&1023)+65536)}r&4294901760?(e[i++]=r>>18&7|240,e[i++]=r>>12&63|128,e[i++]=r>>6&63|128):(e[i++]=r>>12&15|224,e[i++]=r>>6&63|128)}else{e[i++]=r;continue}e[i++]=r&63|128}}const At=new TextEncoder,Pt=50;function Bt(n,e,t){At.encodeInto(n,e.subarray(t))}function Lt(n,e,t){n.length>Pt?Bt(n,e,t):Ut(n,e,t)}const Mt=4096;function tt(n,e,t){let o=e;const i=o+t,s=[];let r="";for(;o<i;){const p=n[o++];if(!(p&128))s.push(p);else if((p&224)===192){const l=n[o++]&63;s.push((p&31)<<6|l)}else if((p&240)===224){const l=n[o++]&63,u=n[o++]&63;s.push((p&31)<<12|l<<6|u)}else if((p&248)===240){const l=n[o++]&63,u=n[o++]&63,y=n[o++]&63;let d=(p&7)<<18|l<<12|u<<6|y;d>65535&&(d-=65536,s.push(d>>>10&1023|55296),d=56320|d&1023),s.push(d)}else s.push(p);s.length>=Mt&&(r+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(r+=String.fromCharCode(...s)),r}const zt=new TextDecoder,Kt=200;function $t(n,e,t){const o=n.subarray(e,e+t);return zt.decode(o)}function Dt(n,e,t){return t>Kt?$t(n,e,t):tt(n,e,t)}class Ce{constructor(e,t){a(this,"type");a(this,"data");this.type=e,this.data=t}}class O extends Error{constructor(e){super(e);const t=Object.create(O.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:O.name})}}const ue=4294967295;function Rt(n,e,t){const o=t/4294967296,i=t;n.setUint32(e,o),n.setUint32(e+4,i)}function nt(n,e,t){const o=Math.floor(t/4294967296),i=t;n.setUint32(e,o),n.setUint32(e+4,i)}function it(n,e){const t=n.getInt32(e),o=n.getUint32(e+4);return t*4294967296+o}function _t(n,e){const t=n.getUint32(e),o=n.getUint32(e+4);return t*4294967296+o}const jt=-1,Ht=4294967296-1,qt=17179869184-1;function Nt({sec:n,nsec:e}){if(n>=0&&e>=0&&n<=qt)if(e===0&&n<=Ht){const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n),t}else{const t=n/4294967296,o=n&4294967295,i=new Uint8Array(8),s=new DataView(i.buffer);return s.setUint32(0,e<<2|t&3),s.setUint32(4,o),i}else{const t=new Uint8Array(12),o=new DataView(t.buffer);return o.setUint32(0,e),nt(o,4,n),t}}function Ft(n){const e=n.getTime(),t=Math.floor(e/1e3),o=(e-t*1e3)*1e6,i=Math.floor(o/1e9);return{sec:t+i,nsec:o-i*1e9}}function Ot(n){if(n instanceof Date){const e=Ft(n);return Nt(e)}else return null}function Wt(n){const e=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const t=e.getUint32(0),o=e.getUint32(4),i=(t&3)*4294967296+o,s=t>>>2;return{sec:i,nsec:s}}case 12:{const t=it(e,4),o=e.getUint32(0);return{sec:t,nsec:o}}default:throw new O(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${n.length}`)}}function Vt(n){const e=Wt(n);return new Date(e.sec*1e3+e.nsec/1e6)}const Xt={type:jt,encode:Ot,decode:Vt},Pe=class Pe{constructor(){a(this,"__brand");a(this,"builtInEncoders",[]);a(this,"builtInDecoders",[]);a(this,"encoders",[]);a(this,"decoders",[]);this.register(Xt)}register({type:e,encode:t,decode:o}){if(e>=0)this.encoders[e]=t,this.decoders[e]=o;else{const i=-1-e;this.builtInEncoders[i]=t,this.builtInDecoders[i]=o}}tryToEncode(e,t){for(let o=0;o<this.builtInEncoders.length;o++){const i=this.builtInEncoders[o];if(i!=null){const s=i(e,t);if(s!=null){const r=-1-o;return new Ce(r,s)}}}for(let o=0;o<this.encoders.length;o++){const i=this.encoders[o];if(i!=null){const s=i(e,t);if(s!=null){const r=o;return new Ce(r,s)}}}return e instanceof Ce?e:null}decode(e,t,o){const i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(e,t,o):new Ce(t,e)}};a(Pe,"defaultCodec",new Pe);let Ee=Pe;function Gt(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function $e(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):Gt(n)?new Uint8Array(n):Uint8Array.from(n)}const Yt=100,Jt=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)??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)??Yt,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??Jt,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),o=new Uint8Array(t),i=new DataView(t);o.set(this.bytes),this.view=i,this.bytes=o}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const o=Tt(e);this.ensureBufferSizeToWrite(5+o),this.writeStringHeader(o),Lt(e,this.bytes,this.pos),this.pos+=o}encodeObject(e,t){const o=this.extensionCodec.tryToEncode(e,this.context);if(o!=null)this.encodeExtension(o);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 o=$e(e);this.writeU8a(o)}encodeArray(e,t){const o=e.length;if(o<16)this.writeU8(144+o);else if(o<65536)this.writeU8(220),this.writeU16(o);else if(o<4294967296)this.writeU8(221),this.writeU32(o);else throw new Error(`Too large array: ${o}`);for(const i of e)this.doEncode(i,t+1)}countWithoutUndefined(e,t){let o=0;for(const i of t)e[i]!==void 0&&o++;return o}encodeMap(e,t){const o=Object.keys(e);this.sortKeys&&o.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(e,o):o.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(`Too large map object: ${i}`);for(const s of o){const r=e[s];this.ignoreUndefined&&r===void 0||(this.encodeString(s),this.doEncode(r,t+1))}}encodeExtension(e){if(typeof e.data=="function"){const o=e.data(this.pos+6),i=o.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);this.writeU8(201),this.writeU32(i),this.writeI8(e.type),this.writeU8a(o);return}const 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),Rt(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),nt(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function Zt(n,e){return new De(e).encodeSharedRef(n)}function Re(n){return`${n<0?"-":""}0x${Math.abs(n).toString(16).padStart(2,"0")}`}const Qt=16,en=16;class tn{constructor(e=Qt,t=en){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 o=0;o<this.maxKeyLength;o++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,o){const i=this.caches[o-1];e:for(const s of i){const r=s.bytes;for(let p=0;p<o;p++)if(r[p]!==e[t+p])continue e;return s.str}return null}store(e,t){const o=this.caches[e.length-1],i={bytes:e,str:t};o.length>=this.maxLengthPerKey?o[Math.random()*o.length|0]=i:o.push(i)}decode(e,t,o){const i=this.find(e,t,o);if(i!=null)return this.hit++,i;this.miss++;const s=tt(e,t,o),r=Uint8Array.prototype.slice.call(e,t,t+o);return this.store(r,s),s}}const _e="array",fe="map_key",ot="map_value",nn=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new O("The type of key must be string or number but "+typeof n)};class on{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=_e,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=fe,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===_e){const o=e;o.size=0,o.array=void 0,o.position=0,o.type=void 0}if(e.type===fe||e.type===ot){const o=e;o.size=0,o.map=void 0,o.readCount=0,o.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const we=-1,je=new DataView(new ArrayBuffer(0)),sn=new Uint8Array(je.buffer);try{je.getInt8(0)}catch(n){if(!(n instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const st=new RangeError("Insufficient data"),rn=new tn;class He{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",je);a(this,"bytes",sn);a(this,"headByte",we);a(this,"stack",new on);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)??ue,this.maxBinLength=(e==null?void 0:e.maxBinLength)??ue,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??ue,this.maxMapLength=(e==null?void 0:e.maxMapLength)??ue,this.maxExtLength=(e==null?void 0:e.maxExtLength)??ue,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:rn,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??nn}clone(){return new He({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=we,this.stack.reset()}setBuffer(e){const t=$e(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===we&&!this.hasRemaining(1))this.setBuffer(e);else{const t=this.bytes.subarray(this.pos),o=$e(e),i=new Uint8Array(t.length+o.length);i.set(t),i.set(o,t.length),this.setBuffer(i)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:t,pos:o}=this;return new RangeError(`Extra ${t.byteLength-o} 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,o;for await(const p of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(p);try{o=this.doDecodeSync(),t=!0}catch(l){if(!(l instanceof RangeError))throw l}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return o}const{headByte:i,pos:s,totalPos:r}=this;throw new RangeError(`Insufficient data in parsing ${Re(i)} at ${r} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let o=t,i=-1;for await(const s of e){if(t&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),o&&(i=this.readArraySize(),o=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(r){if(!(r instanceof RangeError))throw r}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){const i=e-128;if(i!==0){this.pushMapState(i),this.complete();continue e}else t={}}else if(e<160){const i=e-144;if(i!==0){this.pushArrayState(i),this.complete();continue e}else t=[]}else{const i=e-160;t=this.decodeString(i,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 i=this.lookU8();t=this.decodeString(i,1)}else if(e===218){const i=this.lookU16();t=this.decodeString(i,2)}else if(e===219){const i=this.lookU32();t=this.decodeString(i,4)}else if(e===220){const i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue e}else t=[]}else if(e===221){const i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue e}else t=[]}else if(e===222){const i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue e}else t={}}else if(e===223){const i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue e}else t={}}else if(e===196){const i=this.lookU8();t=this.decodeBinary(i,1)}else if(e===197){const i=this.lookU16();t=this.decodeBinary(i,2)}else if(e===198){const i=this.lookU32();t=this.decodeBinary(i,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 i=this.lookU8();t=this.decodeExtension(i,1)}else if(e===200){const i=this.lookU16();t=this.decodeExtension(i,2)}else if(e===201){const i=this.lookU32();t=this.decodeExtension(i,4)}else throw new O(`Unrecognized type byte: ${Re(e)}`);this.complete();const o=this.stack;for(;o.length>0;){const i=o.top();if(i.type===_e)if(i.array[i.position]=t,i.position++,i.position===i.size)t=i.array,o.release(i);else continue e;else if(i.type===fe){if(t==="__proto__")throw new O("The key __proto__ is not allowed");i.key=this.mapKeyConverter(t),i.type=ot;continue e}else if(i.map[i.key]=t,i.readCount++,i.readCount===i.size)t=i.map,o.release(i);else{i.key=null,i.type=fe;continue e}}return t}}readHeadByte(){return this.headByte===we&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=we}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 O(`Unrecognized array type byte: ${Re(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new O(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new O(`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 s;if(e>this.maxStrLength)throw new O(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw st;const o=this.pos+t;let i;return this.stateIsMapKey()&&((s=this.keyDecoder)!=null&&s.canBeCached(e))?i=this.keyDecoder.decode(this.bytes,o,e):i=Dt(this.bytes,o,e),this.pos+=t+e,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===fe:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new O(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw st;const o=this.pos+t,i=this.bytes.subarray(o,o+e);return this.pos+=t+e,i}decodeExtension(e,t){if(e>this.maxExtLength)throw new O(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const o=this.view.getInt8(this.pos+t),i=this.decodeBinary(e,t+1);return this.extensionCodec.decode(i,o,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=_t(this.view,this.pos);return this.pos+=8,e}readI64(){const e=it(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 an(n,e){return new He(e).decode(n)}const cn=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 ln(n){return cn.has(n.type)}function qe(n){return Zt(n)}function rt(n){let e;try{e=an(n)}catch{return null}return typeof e!="object"||e===null||typeof e.type!="string"?null:e}class dn{constructor(e){a(this,"conversationId");a(this,"state","");a(this,"version",0);a(this,"hasMoreHistory",!1);a(this,"lastReadByOthers",0);a(this,"assignedAgentId");a(this,"accent");a(this,"subject");a(this,"name");a(this,"e2e",!1);a(this,"offline",!1);a(this,"offlineMessage","");a(this,"launcherMessage",null);a(this,"preChat",null);a(this,"whiteLabel",!1);a(this,"typing",new Set);a(this,"online",new Set);a(this,"annotations",[]);a(this,"annotationVersion",0);a(this,"sentiment");a(this,"sentimentScore");a(this,"actions",[]);a(this,"byId",new Map);a(this,"keyByClient",new Map);a(this,"_maxSeq",0);a(this,"_sorted",null);this.me=e}messages(){return this._sorted||(this._sorted=[...this.byId.values()].sort((e,t)=>{const o=e.status==="pending",i=t.status==="pending";return o!==i?o?1:-1:o&&i?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 o={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,o),this.keyByClient.set(e,e),this._sorted=null,o}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),this.offline=e.offline===!0,this.offlineMessage=e.offlineMessage??"",e.launcherMessage&&(this.launcherMessage=e.launcherMessage),e.whiteLabel&&(this.whiteLabel=!0),e.preChat&&(this.preChat=e.preChat);return;case"message":this.upsert({...e.message});return;case"ack":{const o=this.keyByClient.get(e.clientMsgId),i=o?this.byId.get(o):void 0;if(i&&o){this.byId.delete(o);const s={...i,id:e.messageId,seq:e.seq,ts:e.ts,status:"sent"};this.byId.set(e.messageId,s),this.keyByClient.set(e.clientMsgId,e.messageId),e.seq>this._maxSeq&&(this._maxSeq=e.seq)}this._sorted=null;return}case"delivered":this.markOwnStatus(e.seq,"delivered");return;case"read":e.by!==this.me&&(this.lastReadByOthers=Math.max(this.lastReadByOthers,e.seq),this.markOwnStatus(e.seq,"read"));return;case"sync":for(const o of e.messages)this.upsert({...o});return;case"history":for(const o of e.messages)this.upsert({...o});this.hasMoreHistory=e.hasMore;return;case"typing":e.userId!==this.me&&(e.isTyping?this.typing.add(e.userId):this.typing.delete(e.userId));return;case"reaction":{const o=this.byId.get(e.messageId);if(!o)return;const i={...o.reactions??{}},s=(i[e.emoji]??[]).filter(r=>r!==e.by);e.removed||s.push(e.by),s.length?i[e.emoji]=s:delete i[e.emoji],this.byId.set(e.messageId,{...o,reactions:i}),this._sorted=null;return}case"edited":{const o=this.byId.get(e.messageId);o&&(this.byId.set(e.messageId,{...o,content:e.content,editedAt:e.editedAt}),this._sorted=null);return}case"deleted":{const o=this.byId.get(e.messageId);o&&(this.byId.set(e.messageId,{...o,deletedAt:e.ts}),this._sorted=null);return}case"state":this.state=e.state;return;case"assigned":this.assignedAgentId=e.agentId??void 0;return;case"presence":e.status==="online"?this.online.add(e.userId):this.online.delete(e.userId);return;case"subjectState":case"invoked":case"authed":case"error":case"pong":return;case"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 o=at(t);let i=!1;for(const[s,r]of this.byId)r.senderId!==this.me||r.seq<=0||r.seq>e||at(r.status)>=o||(this.byId.set(s,{...r,status:t}),i=!0);i&&(this._sorted=null)}}function at(n){switch(n){case"read":return 3;case"delivered":return 2;case"sent":return 1;default:return 0}}const ct="http://www.w3.org/2000/svg",hn=8e3;class pn{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 o of e.annotations)this.draw(o)}ensureSvg(){var t;if((t=this.svg)!=null&&t.isConnected)return this.svg;const e=document.createElementNS(ct,"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 p;if(typeof document>"u"||!((p=e.points)!=null&&p.length))return;const t=this.ensureSvg(),o=window.innerWidth,i=window.innerHeight,s=document.createElementNS(ct,"polyline");s.setAttribute("points",e.points.map(l=>`${(l.x*o).toFixed(1)},${(l.y*i).toFixed(1)}`).join(" ")),s.setAttribute("fill","none"),s.setAttribute("stroke",e.color||"#ff3b30"),s.setAttribute("stroke-width",String(e.width||3)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("data-stroke-id",e.id),t.append(s);const r=setTimeout(()=>{s.style.transition="opacity 600ms",s.style.opacity="0";const l=setTimeout(()=>{s.remove(),this.timers.delete(l)},650);this.timers.add(l),this.timers.delete(r)},hn);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 un{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 o,i;if(this.state==="connecting"||this.state==="open")return;this.stopped=!1,this.state="connecting",this.authed=!1,(i=(o=this.opts).onStatusChange)==null||i.call(o,this.attempt>0?"reconnecting":"connecting");const t=(this.opts.socketFactory??gn)(this.opts.url);t.binaryType="arraybuffer",this.socket=t,t.onopen=()=>{this.raw({type:"auth",token:this.opts.token})},t.onmessage=s=>{const r=rt(new Uint8Array(s.data));!r||ln(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}this.queue(e)}pendingCount(){return this.outbox.length}close(){var e;this.stopped=!0,this.timer&&clearTimeout(this.timer),this.state="closed";try{(e=this.socket)==null||e.close()}catch{}}handle(e){var t,o,i,s;if(e.type==="authed"&&(this.attempt=0,this.state="open",this.authed=!0,this.everAuthed=!0,(o=(t=this.opts).onStatusChange)==null||o.call(t,"open"),this.raw(this.opts.open),this.opts.open.type!=="open"&&this.flush()),e.type==="opened"&&(this.raw({type:"sync",conversationId:e.conversation.id,sinceSeq:this.opts.getCursor()}),this.flush(e.conversation.id)),e.type==="error"&&fn.has(e.code)){if(e.code==="UNAUTHORIZED"&&this.opts.refreshToken&&!this.refreshing){this.refreshing=!0,(s=(i=this.opts).onStatusChange)==null||s.call(i,"reconnecting","Renewing session…"),this.opts.refreshToken().then(r=>{var p;if(this.refreshing=!1,!r){this.fatal(e);return}this.opts.token=r;try{(p=this.socket)==null||p.close()}catch{}}).catch(()=>{this.refreshing=!1,this.fatal(e)});return}this.fatal(e);return}this.opts.onFrame(e)}fatal(e){var t,o,i;this.stopped=!0;try{(t=this.socket)==null||t.close()}catch{}this.state="closed",(i=(o=this.opts).onStatusChange)==null||i.call(o,"error",wn(e.code)),this.opts.onFrame(e)}flush(e){const t=this.outbox;this.outbox=[];for(const o of t)this.raw(e&&o.type==="send"&&o.conversationId!==e?{...o,conversationId:e}:o)}queue(e){const t=this.opts.maxOutbox??1e3;this.outbox.length>=t&&(this.outbox=this.outbox.slice(this.outbox.length-(t>>1))),this.outbox.push(e)}raw(e){if(!this.socket){this.queue(e);return}try{this.socket.send(qe(e))}catch{this.queue(e)}}onClosed(){var i,s;if(this.authed=!1,this.socket=null,this.stopped){this.state="closed";return}this.state="idle";const e=this.opts.backoffBaseMs??500,t=this.opts.backoffMaxMs??15e3,o=Math.min(t,e*2**this.attempt)*(.5+Math.random()*.5);this.attempt++,this.attempt>=3&&!this.everAuthed&&((s=(i=this.opts).onStatusChange)==null||s.call(i,"reconnecting","Can't reach chat — retrying…")),this.timer=setTimeout(()=>this.connect(),o)}}const fn=new Set(["UNAUTHORIZED"]);function wn(n){switch(n){case"UNAUTHORIZED":return"Chat unavailable — sign-in/token was rejected";default:return"Chat unavailable"}}function gn(n){return new WebSocket(n)}const lt=200,xn=7*864e5;class yn{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),o=Date.now()-xn,i=t.filter(s=>s.ts>=o);return i.length!==t.length&&this.save(i),i}catch{return[]}}add(e){try{const t=this.load();t.push(e),this.save(t.length>lt?t.slice(t.length-lt):t)}catch{}}remove(e){try{const t=this.load().filter(o=>o.clientMsgId!==e);this.save(t)}catch{}}save(e){try{localStorage.setItem(this.key,JSON.stringify(e))}catch{}}}const B=()=>globalThis.crypto.subtle;function Te(n){const e=n instanceof Uint8Array?n:new Uint8Array(n);let t="";for(const o of e)t+=String.fromCharCode(o);return btoa(t)}function Ne(n){const e=atob(n),t=new ArrayBuffer(e.length),o=new Uint8Array(t);for(let i=0;i<e.length;i++)o[i]=e.charCodeAt(i);return o}async function ge(){const n=await B().generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]);return{publicKey:n.publicKey,privateKey:n.privateKey}}async function ie(n){return Te(await B().exportKey("raw",n))}async function le(n){return B().importKey("raw",Ne(n),{name:"ECDH",namedCurve:"P-256"},!1,[])}async function bn(n,e){const t=await le(e);return B().deriveKey({name:"ECDH",public:t},n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function mn(n,e){const t=globalThis.crypto.getRandomValues(new Uint8Array(12)),o=new TextEncoder().encode(e),i=await B().encrypt({name:"AES-GCM",iv:t},n,o);return{ct:Te(i),iv:Te(t)}}async function vn(n,e,t){const o=await B().decrypt({name:"AES-GCM",iv:Ne(t)},n,Ne(e));return new TextDecoder().decode(o)}async function kn(n){var t,o;try{const i=(t=globalThis.localStorage)==null?void 0:t.getItem(n);if(i){const{pub:s,priv:r}=JSON.parse(i),p=await B().importKey("jwk",s,{name:"ECDH",namedCurve:"P-256"},!0,[]),l=await B().importKey("jwk",r,{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]);return{publicKey:p,privateKey:l}}}catch{}const e=await ge();try{const i=await B().exportKey("jwk",e.publicKey),s=await B().exportKey("jwk",e.privateKey);(o=globalThis.localStorage)==null||o.setItem(n,JSON.stringify({pub:i,priv:s}))}catch{}return e}async function Sn(n,e){const t=await B().exportKey("raw",e),o=await B().sign({name:"ECDSA",hash:"SHA-256"},n,t);return Te(o)}async function In(){const n=await ge(),e=await B().generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]);return{ecdhKP:n,ecdsaKP:{publicKey:e.publicKey,privateKey:e.privateKey},publicKeyB64:await ie(n.publicKey),sigPublicKeyB64:await ie(e.publicKey)}}async function dt(n){var t,o;try{const i=(t=globalThis.localStorage)==null?void 0:t.getItem(`${n}-identity`);if(i){const s=JSON.parse(i),r=await B().importKey("jwk",s.ecdhPub,{name:"ECDH",namedCurve:"P-256"},!0,[]),p=await B().importKey("jwk",s.ecdhPriv,{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]),l=await B().importKey("jwk",s.ecdsaPub,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),u=await B().importKey("jwk",s.ecdsaPriv,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"]);return{ecdhKP:{publicKey:r,privateKey:p},ecdsaKP:{publicKey:l,privateKey:u},publicKeyB64:await ie(r),sigPublicKeyB64:await ie(l)}}}catch{}const e=await In();try{const i=await B().exportKey("jwk",e.ecdhKP.publicKey),s=await B().exportKey("jwk",e.ecdhKP.privateKey),r=await B().exportKey("jwk",e.ecdsaKP.publicKey),p=await B().exportKey("jwk",e.ecdsaKP.privateKey);(o=globalThis.localStorage)==null||o.setItem(`${n}-identity`,JSON.stringify({ecdhPub:i,ecdhPriv:s,ecdsaPub:r,ecdsaPriv:p}))}catch{}return e}async function Cn(n,e){const t=await ge(),o=await ie(t.publicKey),i=await le(e.identityKey),s=await le(e.signedPrekey),r=e.oneTimePrekey?await le(e.oneTimePrekey):null,p=await oe(n.privateKey,s),l=await oe(t.privateKey,i),u=await oe(t.privateKey,s),y=r?await oe(t.privateKey,r):null,d=ht(p,l,u,...y?[y]:[]);return{sharedKey:await pt(d),ephemeralPublicKey:o}}async function En(n,e,t,o,i){const s=await le(t),r=await le(o),p=await oe(e.privateKey,s),l=await oe(n.privateKey,r),u=await oe(e.privateKey,r),y=i?await oe(i.privateKey,r):null,d=ht(p,l,u,...y?[y]:[]);return pt(d)}async function oe(n,e){return B().deriveBits({name:"ECDH",public:e},n,256)}function ht(...n){const e=n.reduce((i,s)=>i+s.byteLength,0),t=new Uint8Array(e);let o=0;for(const i of n)t.set(new Uint8Array(i),o),o+=i.byteLength;return t.buffer}async function pt(n){const e=await B().importKey("raw",n,"HKDF",!1,["deriveKey"]);return B().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 Tn=20;class Un{constructor(e){a(this,"kp");a(this,"shared");a(this,"identityKP");a(this,"signedPreKP");a(this,"signedPrekeyId");a(this,"otpKeys",[]);a(this,"x3dhShared");a(this,"pendingX3DH");this.storageKey=e}get ready(){return!!(this.shared??this.x3dhShared)}async begin(){return this.kp=await kn(this.storageKey),ie(this.kp.publicKey)}async onPeerKey(e){this.kp&&(this.shared=await bn(this.kp.privateKey,e))}async initX3DH(){this.identityKP=await dt(this.storageKey),this.signedPreKP=await ge(),this.signedPrekeyId=`spk-${Date.now()}-${Math.random().toString(36).slice(2)}`;for(let i=0;i<Tn;i++)this.otpKeys.push(await ge());const e=await ie(this.signedPreKP.publicKey),t=await Sn(this.identityKP.ecdsaKP.privateKey,this.signedPreKP.publicKey),o=await Promise.all(this.otpKeys.map(i=>ie(i.publicKey)));return{identityKey:this.identityKP.publicKeyB64,signedPrekey:e,signedPrekeyId:this.signedPrekeyId,signature:t,oneTimePrekeys:o}}async x3dhSendTo(e){this.identityKP||(this.identityKP=await dt(this.storageKey));const{sharedKey:t,ephemeralPublicKey:o}=await Cn(this.identityKP.ecdhKP,e);return this.x3dhShared=t,{ephemeralKey:o,spkId:e.signedPrekeyId,usedOTP:!!e.oneTimePrekey,senderIK:this.identityKP.publicKeyB64}}async x3dhReceiveFrom(e,t,o){if(!this.identityKP||!this.signedPreKP){this.pendingX3DH={senderIK:e,ephemeralKey:t,spkId:o};return}const i=this.otpKeys.shift();this.x3dhShared=await En(this.identityKP.ecdhKP,this.signedPreKP,e,t,i)}async flushPendingX3DH(){if(!this.pendingX3DH)return;const{senderIK:e,ephemeralKey:t,spkId:o}=this.pendingX3DH;this.pendingX3DH=void 0,await this.x3dhReceiveFrom(e,t,o)}async sealText(e,t){const o=this.x3dhShared??this.shared;if(!o)throw new Error("secure channel not ready");const{ct:i,iv:s}=await mn(o,e);return{kind:"text",text:i,enc:!0,iv:s,...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 vn(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 An(n){if(n.kind!=="text"||!n.enc)return null;const e=n;return!e.x3dhEK||!e.x3dhSPK||!e.x3dhIK?null:{x3dhEK:e.x3dhEK,x3dhSPK:e.x3dhSPK,x3dhIK:e.x3dhIK}}const ut="objectchat-widget-styles",Pn=["👍","❤️","😂","😮","😢","🙏"],Bn=400,Ln='<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M22 2 11 13M22 2l-7 20-4-9-9-4 20-7z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',Mn=`
|
|
1
|
+
var RelayEmbed=function(J){"use strict";var ni=Object.defineProperty;var ii=(J,X,ce)=>X in J?ni(J,X,{enumerable:!0,configurable:!0,writable:!0,value:ce}):J[X]=ce;var a=(J,X,ce)=>ii(J,typeof X!="symbol"?X+"":X,ce);const X="oc_uid";function ce(n){try{const e=document.cookie.match(new RegExp(`(?:^|; )${n}=([^;]*)`));return e?decodeURIComponent(e[1]):null}catch{return null}}function It(n,e){try{const o=location.protocol==="https:"?"; Secure":"";document.cookie=`${n}=${encodeURIComponent(e)}; Max-Age=31536000; Path=/; SameSite=Lax${o}`}catch{}}function Et(){return`g_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`}function et(){let n=null;try{n=localStorage.getItem(X)}catch{}n||(n=ce(X));const e=n??Et();try{localStorage.setItem(X,e)}catch{}return It(X,e),e}function Tt(n){const e=n.length;let t=0,o=0;for(;o<e;){let i=n.charCodeAt(o++);if(i&4294967168)if(!(i&4294965248))t+=2;else{if(i>=55296&&i<=56319&&o<e){const s=n.charCodeAt(o);(s&64512)===56320&&(++o,i=((i&1023)<<10)+(s&1023)+65536)}i&4294901760?t+=4:t+=3}else{t++;continue}}return t}function Ut(n,e,t){const o=n.length;let i=t,s=0;for(;s<o;){let r=n.charCodeAt(s++);if(r&4294967168)if(!(r&4294965248))e[i++]=r>>6&31|192;else{if(r>=55296&&r<=56319&&s<o){const p=n.charCodeAt(s);(p&64512)===56320&&(++s,r=((r&1023)<<10)+(p&1023)+65536)}r&4294901760?(e[i++]=r>>18&7|240,e[i++]=r>>12&63|128,e[i++]=r>>6&63|128):(e[i++]=r>>12&15|224,e[i++]=r>>6&63|128)}else{e[i++]=r;continue}e[i++]=r&63|128}}const At=new TextEncoder,Pt=50;function Bt(n,e,t){At.encodeInto(n,e.subarray(t))}function Lt(n,e,t){n.length>Pt?Bt(n,e,t):Ut(n,e,t)}const Mt=4096;function tt(n,e,t){let o=e;const i=o+t,s=[];let r="";for(;o<i;){const p=n[o++];if(!(p&128))s.push(p);else if((p&224)===192){const c=n[o++]&63;s.push((p&31)<<6|c)}else if((p&240)===224){const c=n[o++]&63,u=n[o++]&63;s.push((p&31)<<12|c<<6|u)}else if((p&248)===240){const c=n[o++]&63,u=n[o++]&63,y=n[o++]&63;let d=(p&7)<<18|c<<12|u<<6|y;d>65535&&(d-=65536,s.push(d>>>10&1023|55296),d=56320|d&1023),s.push(d)}else s.push(p);s.length>=Mt&&(r+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(r+=String.fromCharCode(...s)),r}const zt=new TextDecoder,Kt=200;function $t(n,e,t){const o=n.subarray(e,e+t);return zt.decode(o)}function Rt(n,e,t){return t>Kt?$t(n,e,t):tt(n,e,t)}class Ie{constructor(e,t){a(this,"type");a(this,"data");this.type=e,this.data=t}}class O extends Error{constructor(e){super(e);const t=Object.create(O.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:O.name})}}const ue=4294967295;function Dt(n,e,t){const o=t/4294967296,i=t;n.setUint32(e,o),n.setUint32(e+4,i)}function nt(n,e,t){const o=Math.floor(t/4294967296),i=t;n.setUint32(e,o),n.setUint32(e+4,i)}function it(n,e){const t=n.getInt32(e),o=n.getUint32(e+4);return t*4294967296+o}function _t(n,e){const t=n.getUint32(e),o=n.getUint32(e+4);return t*4294967296+o}const jt=-1,Ht=4294967296-1,qt=17179869184-1;function Nt({sec:n,nsec:e}){if(n>=0&&e>=0&&n<=qt)if(e===0&&n<=Ht){const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n),t}else{const t=n/4294967296,o=n&4294967295,i=new Uint8Array(8),s=new DataView(i.buffer);return s.setUint32(0,e<<2|t&3),s.setUint32(4,o),i}else{const t=new Uint8Array(12),o=new DataView(t.buffer);return o.setUint32(0,e),nt(o,4,n),t}}function Ft(n){const e=n.getTime(),t=Math.floor(e/1e3),o=(e-t*1e3)*1e6,i=Math.floor(o/1e9);return{sec:t+i,nsec:o-i*1e9}}function Ot(n){if(n instanceof Date){const e=Ft(n);return Nt(e)}else return null}function Wt(n){const e=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const t=e.getUint32(0),o=e.getUint32(4),i=(t&3)*4294967296+o,s=t>>>2;return{sec:i,nsec:s}}case 12:{const t=it(e,4),o=e.getUint32(0);return{sec:t,nsec:o}}default:throw new O(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${n.length}`)}}function Vt(n){const e=Wt(n);return new Date(e.sec*1e3+e.nsec/1e6)}const Xt={type:jt,encode:Ot,decode:Vt},Pe=class Pe{constructor(){a(this,"__brand");a(this,"builtInEncoders",[]);a(this,"builtInDecoders",[]);a(this,"encoders",[]);a(this,"decoders",[]);this.register(Xt)}register({type:e,encode:t,decode:o}){if(e>=0)this.encoders[e]=t,this.decoders[e]=o;else{const i=-1-e;this.builtInEncoders[i]=t,this.builtInDecoders[i]=o}}tryToEncode(e,t){for(let o=0;o<this.builtInEncoders.length;o++){const i=this.builtInEncoders[o];if(i!=null){const s=i(e,t);if(s!=null){const r=-1-o;return new Ie(r,s)}}}for(let o=0;o<this.encoders.length;o++){const i=this.encoders[o];if(i!=null){const s=i(e,t);if(s!=null){const r=o;return new Ie(r,s)}}}return e instanceof Ie?e:null}decode(e,t,o){const i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(e,t,o):new Ie(t,e)}};a(Pe,"defaultCodec",new Pe);let Ee=Pe;function Gt(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function $e(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):Gt(n)?new Uint8Array(n):Uint8Array.from(n)}const Yt=100,Jt=2048;class Re{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)??Yt,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??Jt,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 Re({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),o=new Uint8Array(t),i=new DataView(t);o.set(this.bytes),this.view=i,this.bytes=o}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const o=Tt(e);this.ensureBufferSizeToWrite(5+o),this.writeStringHeader(o),Lt(e,this.bytes,this.pos),this.pos+=o}encodeObject(e,t){const o=this.extensionCodec.tryToEncode(e,this.context);if(o!=null)this.encodeExtension(o);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 o=$e(e);this.writeU8a(o)}encodeArray(e,t){const o=e.length;if(o<16)this.writeU8(144+o);else if(o<65536)this.writeU8(220),this.writeU16(o);else if(o<4294967296)this.writeU8(221),this.writeU32(o);else throw new Error(`Too large array: ${o}`);for(const i of e)this.doEncode(i,t+1)}countWithoutUndefined(e,t){let o=0;for(const i of t)e[i]!==void 0&&o++;return o}encodeMap(e,t){const o=Object.keys(e);this.sortKeys&&o.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(e,o):o.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(`Too large map object: ${i}`);for(const s of o){const r=e[s];this.ignoreUndefined&&r===void 0||(this.encodeString(s),this.doEncode(r,t+1))}}encodeExtension(e){if(typeof e.data=="function"){const o=e.data(this.pos+6),i=o.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);this.writeU8(201),this.writeU32(i),this.writeI8(e.type),this.writeU8a(o);return}const 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),Dt(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),nt(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function Zt(n,e){return new Re(e).encodeSharedRef(n)}function De(n){return`${n<0?"-":""}0x${Math.abs(n).toString(16).padStart(2,"0")}`}const Qt=16,en=16;class tn{constructor(e=Qt,t=en){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 o=0;o<this.maxKeyLength;o++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,o){const i=this.caches[o-1];e:for(const s of i){const r=s.bytes;for(let p=0;p<o;p++)if(r[p]!==e[t+p])continue e;return s.str}return null}store(e,t){const o=this.caches[e.length-1],i={bytes:e,str:t};o.length>=this.maxLengthPerKey?o[Math.random()*o.length|0]=i:o.push(i)}decode(e,t,o){const i=this.find(e,t,o);if(i!=null)return this.hit++,i;this.miss++;const s=tt(e,t,o),r=Uint8Array.prototype.slice.call(e,t,t+o);return this.store(r,s),s}}const _e="array",fe="map_key",ot="map_value",nn=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new O("The type of key must be string or number but "+typeof n)};class on{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=_e,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=fe,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===_e){const o=e;o.size=0,o.array=void 0,o.position=0,o.type=void 0}if(e.type===fe||e.type===ot){const o=e;o.size=0,o.map=void 0,o.readCount=0,o.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const we=-1,je=new DataView(new ArrayBuffer(0)),sn=new Uint8Array(je.buffer);try{je.getInt8(0)}catch(n){if(!(n instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const st=new RangeError("Insufficient data"),rn=new tn;class He{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",je);a(this,"bytes",sn);a(this,"headByte",we);a(this,"stack",new on);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)??ue,this.maxBinLength=(e==null?void 0:e.maxBinLength)??ue,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??ue,this.maxMapLength=(e==null?void 0:e.maxMapLength)??ue,this.maxExtLength=(e==null?void 0:e.maxExtLength)??ue,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:rn,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??nn}clone(){return new He({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=we,this.stack.reset()}setBuffer(e){const t=$e(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===we&&!this.hasRemaining(1))this.setBuffer(e);else{const t=this.bytes.subarray(this.pos),o=$e(e),i=new Uint8Array(t.length+o.length);i.set(t),i.set(o,t.length),this.setBuffer(i)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:t,pos:o}=this;return new RangeError(`Extra ${t.byteLength-o} 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,o;for await(const p of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(p);try{o=this.doDecodeSync(),t=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return o}const{headByte:i,pos:s,totalPos:r}=this;throw new RangeError(`Insufficient data in parsing ${De(i)} at ${r} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let o=t,i=-1;for await(const s of e){if(t&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),o&&(i=this.readArraySize(),o=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(r){if(!(r instanceof RangeError))throw r}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){const i=e-128;if(i!==0){this.pushMapState(i),this.complete();continue e}else t={}}else if(e<160){const i=e-144;if(i!==0){this.pushArrayState(i),this.complete();continue e}else t=[]}else{const i=e-160;t=this.decodeString(i,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 i=this.lookU8();t=this.decodeString(i,1)}else if(e===218){const i=this.lookU16();t=this.decodeString(i,2)}else if(e===219){const i=this.lookU32();t=this.decodeString(i,4)}else if(e===220){const i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue e}else t=[]}else if(e===221){const i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue e}else t=[]}else if(e===222){const i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue e}else t={}}else if(e===223){const i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue e}else t={}}else if(e===196){const i=this.lookU8();t=this.decodeBinary(i,1)}else if(e===197){const i=this.lookU16();t=this.decodeBinary(i,2)}else if(e===198){const i=this.lookU32();t=this.decodeBinary(i,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 i=this.lookU8();t=this.decodeExtension(i,1)}else if(e===200){const i=this.lookU16();t=this.decodeExtension(i,2)}else if(e===201){const i=this.lookU32();t=this.decodeExtension(i,4)}else throw new O(`Unrecognized type byte: ${De(e)}`);this.complete();const o=this.stack;for(;o.length>0;){const i=o.top();if(i.type===_e)if(i.array[i.position]=t,i.position++,i.position===i.size)t=i.array,o.release(i);else continue e;else if(i.type===fe){if(t==="__proto__")throw new O("The key __proto__ is not allowed");i.key=this.mapKeyConverter(t),i.type=ot;continue e}else if(i.map[i.key]=t,i.readCount++,i.readCount===i.size)t=i.map,o.release(i);else{i.key=null,i.type=fe;continue e}}return t}}readHeadByte(){return this.headByte===we&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=we}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 O(`Unrecognized array type byte: ${De(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new O(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new O(`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 s;if(e>this.maxStrLength)throw new O(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw st;const o=this.pos+t;let i;return this.stateIsMapKey()&&((s=this.keyDecoder)!=null&&s.canBeCached(e))?i=this.keyDecoder.decode(this.bytes,o,e):i=Rt(this.bytes,o,e),this.pos+=t+e,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===fe:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new O(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw st;const o=this.pos+t,i=this.bytes.subarray(o,o+e);return this.pos+=t+e,i}decodeExtension(e,t){if(e>this.maxExtLength)throw new O(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const o=this.view.getInt8(this.pos+t),i=this.decodeBinary(e,t+1);return this.extensionCodec.decode(i,o,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=_t(this.view,this.pos);return this.pos+=8,e}readI64(){const e=it(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 an(n,e){return new He(e).decode(n)}const cn=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 ln(n){return cn.has(n.type)}function qe(n){return Zt(n)}function rt(n){let e;try{e=an(n)}catch{return null}return typeof e!="object"||e===null||typeof e.type!="string"?null:e}class dn{constructor(e){a(this,"conversationId");a(this,"state","");a(this,"version",0);a(this,"hasMoreHistory",!1);a(this,"lastReadByOthers",0);a(this,"assignedAgentId");a(this,"accent");a(this,"subject");a(this,"name");a(this,"e2e",!1);a(this,"offline",!1);a(this,"offlineMessage","");a(this,"launcherMessage",null);a(this,"preChat",null);a(this,"whiteLabel",!1);a(this,"typing",new Set);a(this,"online",new Set);a(this,"annotations",[]);a(this,"annotationVersion",0);a(this,"sentiment");a(this,"sentimentScore");a(this,"actions",[]);a(this,"byId",new Map);a(this,"keyByClient",new Map);a(this,"_maxSeq",0);a(this,"_sorted",null);this.me=e}messages(){return this._sorted||(this._sorted=[...this.byId.values()].sort((e,t)=>{const o=e.status==="pending",i=t.status==="pending";return o!==i?o?1:-1:o&&i?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 o={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,o),this.keyByClient.set(e,e),this._sorted=null,o}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),this.offline=e.offline===!0,this.offlineMessage=e.offlineMessage??"",e.launcherMessage&&(this.launcherMessage=e.launcherMessage),e.whiteLabel&&(this.whiteLabel=!0),e.preChat&&(this.preChat=e.preChat);return;case"message":this.upsert({...e.message});return;case"ack":{const o=this.keyByClient.get(e.clientMsgId),i=o?this.byId.get(o):void 0;if(i&&o){this.byId.delete(o);const s={...i,id:e.messageId,seq:e.seq,ts:e.ts,status:"sent"};this.byId.set(e.messageId,s),this.keyByClient.set(e.clientMsgId,e.messageId),e.seq>this._maxSeq&&(this._maxSeq=e.seq)}this._sorted=null;return}case"delivered":this.markOwnStatus(e.seq,"delivered");return;case"read":e.by!==this.me&&(this.lastReadByOthers=Math.max(this.lastReadByOthers,e.seq),this.markOwnStatus(e.seq,"read"));return;case"sync":for(const o of e.messages)this.upsert({...o});return;case"history":for(const o of e.messages)this.upsert({...o});this.hasMoreHistory=e.hasMore;return;case"typing":e.userId!==this.me&&(e.isTyping?this.typing.add(e.userId):this.typing.delete(e.userId));return;case"reaction":{const o=this.byId.get(e.messageId);if(!o)return;const i={...o.reactions??{}},s=(i[e.emoji]??[]).filter(r=>r!==e.by);e.removed||s.push(e.by),s.length?i[e.emoji]=s:delete i[e.emoji],this.byId.set(e.messageId,{...o,reactions:i}),this._sorted=null;return}case"edited":{const o=this.byId.get(e.messageId);o&&(this.byId.set(e.messageId,{...o,content:e.content,editedAt:e.editedAt}),this._sorted=null);return}case"deleted":{const o=this.byId.get(e.messageId);o&&(this.byId.set(e.messageId,{...o,deletedAt:e.ts}),this._sorted=null);return}case"state":this.state=e.state;return;case"assigned":this.assignedAgentId=e.agentId??void 0;return;case"presence":e.status==="online"?this.online.add(e.userId):this.online.delete(e.userId);return;case"subjectState":case"invoked":case"authed":case"error":case"pong":return;case"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 o=at(t);let i=!1;for(const[s,r]of this.byId)r.senderId!==this.me||r.seq<=0||r.seq>e||at(r.status)>=o||(this.byId.set(s,{...r,status:t}),i=!0);i&&(this._sorted=null)}}function at(n){switch(n){case"read":return 3;case"delivered":return 2;case"sent":return 1;default:return 0}}const ct="http://www.w3.org/2000/svg",hn=8e3;class pn{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 o of e.annotations)this.draw(o)}ensureSvg(){var t;if((t=this.svg)!=null&&t.isConnected)return this.svg;const e=document.createElementNS(ct,"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 p;if(typeof document>"u"||!((p=e.points)!=null&&p.length))return;const t=this.ensureSvg(),o=window.innerWidth,i=window.innerHeight,s=document.createElementNS(ct,"polyline");s.setAttribute("points",e.points.map(c=>`${(c.x*o).toFixed(1)},${(c.y*i).toFixed(1)}`).join(" ")),s.setAttribute("fill","none"),s.setAttribute("stroke",e.color||"#ff3b30"),s.setAttribute("stroke-width",String(e.width||3)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("data-stroke-id",e.id),t.append(s);const r=setTimeout(()=>{s.style.transition="opacity 600ms",s.style.opacity="0";const c=setTimeout(()=>{s.remove(),this.timers.delete(c)},650);this.timers.add(c),this.timers.delete(r)},hn);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 un{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 o,i;if(this.state==="connecting"||this.state==="open")return;this.stopped=!1,this.state="connecting",this.authed=!1,(i=(o=this.opts).onStatusChange)==null||i.call(o,this.attempt>0?"reconnecting":"connecting");const t=(this.opts.socketFactory??gn)(this.opts.url);t.binaryType="arraybuffer",this.socket=t,t.onopen=()=>{this.raw({type:"auth",token:this.opts.token})},t.onmessage=s=>{const r=rt(new Uint8Array(s.data));!r||ln(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}this.queue(e)}pendingCount(){return this.outbox.length}close(){var e;this.stopped=!0,this.timer&&clearTimeout(this.timer),this.state="closed";try{(e=this.socket)==null||e.close()}catch{}}handle(e){var t,o,i,s;if(e.type==="authed"&&(this.attempt=0,this.state="open",this.authed=!0,this.everAuthed=!0,(o=(t=this.opts).onStatusChange)==null||o.call(t,"open"),this.raw(this.opts.open),this.opts.open.type!=="open"&&this.flush()),e.type==="opened"&&(this.raw({type:"sync",conversationId:e.conversation.id,sinceSeq:this.opts.getCursor()}),this.flush(e.conversation.id)),e.type==="error"&&fn.has(e.code)){if(e.code==="UNAUTHORIZED"&&this.opts.refreshToken&&!this.refreshing){this.refreshing=!0,(s=(i=this.opts).onStatusChange)==null||s.call(i,"reconnecting","Renewing session…"),this.opts.refreshToken().then(r=>{var p;if(this.refreshing=!1,!r){this.fatal(e);return}this.opts.token=r;try{(p=this.socket)==null||p.close()}catch{}}).catch(()=>{this.refreshing=!1,this.fatal(e)});return}this.fatal(e);return}this.opts.onFrame(e)}fatal(e){var t,o,i;this.stopped=!0;try{(t=this.socket)==null||t.close()}catch{}this.state="closed",(i=(o=this.opts).onStatusChange)==null||i.call(o,"error",wn(e.code)),this.opts.onFrame(e)}flush(e){const t=this.outbox;this.outbox=[];for(const o of t)this.raw(e&&o.type==="send"&&o.conversationId!==e?{...o,conversationId:e}:o)}queue(e){const t=this.opts.maxOutbox??1e3;this.outbox.length>=t&&(this.outbox=this.outbox.slice(this.outbox.length-(t>>1))),this.outbox.push(e)}raw(e){if(!this.socket){this.queue(e);return}try{this.socket.send(qe(e))}catch{this.queue(e)}}onClosed(){var i,s;if(this.authed=!1,this.socket=null,this.stopped){this.state="closed";return}this.state="idle";const e=this.opts.backoffBaseMs??500,t=this.opts.backoffMaxMs??15e3,o=Math.min(t,e*2**this.attempt)*(.5+Math.random()*.5);this.attempt++,this.attempt>=3&&!this.everAuthed&&((s=(i=this.opts).onStatusChange)==null||s.call(i,"reconnecting","Can't reach chat — retrying…")),this.timer=setTimeout(()=>this.connect(),o)}}const fn=new Set(["UNAUTHORIZED"]);function wn(n){switch(n){case"UNAUTHORIZED":return"Chat unavailable — sign-in/token was rejected";default:return"Chat unavailable"}}function gn(n){return new WebSocket(n)}const lt=200,xn=7*864e5;class yn{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),o=Date.now()-xn,i=t.filter(s=>s.ts>=o);return i.length!==t.length&&this.save(i),i}catch{return[]}}add(e){try{const t=this.load();t.push(e),this.save(t.length>lt?t.slice(t.length-lt):t)}catch{}}remove(e){try{const t=this.load().filter(o=>o.clientMsgId!==e);this.save(t)}catch{}}save(e){try{localStorage.setItem(this.key,JSON.stringify(e))}catch{}}}const B=()=>globalThis.crypto.subtle;function Te(n){const e=n instanceof Uint8Array?n:new Uint8Array(n);let t="";for(const o of e)t+=String.fromCharCode(o);return btoa(t)}function Ne(n){const e=atob(n),t=new ArrayBuffer(e.length),o=new Uint8Array(t);for(let i=0;i<e.length;i++)o[i]=e.charCodeAt(i);return o}async function ge(){const n=await B().generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]);return{publicKey:n.publicKey,privateKey:n.privateKey}}async function ie(n){return Te(await B().exportKey("raw",n))}async function le(n){return B().importKey("raw",Ne(n),{name:"ECDH",namedCurve:"P-256"},!1,[])}async function bn(n,e){const t=await le(e);return B().deriveKey({name:"ECDH",public:t},n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function mn(n,e){const t=globalThis.crypto.getRandomValues(new Uint8Array(12)),o=new TextEncoder().encode(e),i=await B().encrypt({name:"AES-GCM",iv:t},n,o);return{ct:Te(i),iv:Te(t)}}async function vn(n,e,t){const o=await B().decrypt({name:"AES-GCM",iv:Ne(t)},n,Ne(e));return new TextDecoder().decode(o)}async function kn(n){var t,o;try{const i=(t=globalThis.localStorage)==null?void 0:t.getItem(n);if(i){const{pub:s,priv:r}=JSON.parse(i),p=await B().importKey("jwk",s,{name:"ECDH",namedCurve:"P-256"},!0,[]),c=await B().importKey("jwk",r,{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]);return{publicKey:p,privateKey:c}}}catch{}const e=await ge();try{const i=await B().exportKey("jwk",e.publicKey),s=await B().exportKey("jwk",e.privateKey);(o=globalThis.localStorage)==null||o.setItem(n,JSON.stringify({pub:i,priv:s}))}catch{}return e}async function Sn(n,e){const t=await B().exportKey("raw",e),o=await B().sign({name:"ECDSA",hash:"SHA-256"},n,t);return Te(o)}async function Cn(){const n=await ge(),e=await B().generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]);return{ecdhKP:n,ecdsaKP:{publicKey:e.publicKey,privateKey:e.privateKey},publicKeyB64:await ie(n.publicKey),sigPublicKeyB64:await ie(e.publicKey)}}async function dt(n){var t,o;try{const i=(t=globalThis.localStorage)==null?void 0:t.getItem(`${n}-identity`);if(i){const s=JSON.parse(i),r=await B().importKey("jwk",s.ecdhPub,{name:"ECDH",namedCurve:"P-256"},!0,[]),p=await B().importKey("jwk",s.ecdhPriv,{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]),c=await B().importKey("jwk",s.ecdsaPub,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),u=await B().importKey("jwk",s.ecdsaPriv,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"]);return{ecdhKP:{publicKey:r,privateKey:p},ecdsaKP:{publicKey:c,privateKey:u},publicKeyB64:await ie(r),sigPublicKeyB64:await ie(c)}}}catch{}const e=await Cn();try{const i=await B().exportKey("jwk",e.ecdhKP.publicKey),s=await B().exportKey("jwk",e.ecdhKP.privateKey),r=await B().exportKey("jwk",e.ecdsaKP.publicKey),p=await B().exportKey("jwk",e.ecdsaKP.privateKey);(o=globalThis.localStorage)==null||o.setItem(`${n}-identity`,JSON.stringify({ecdhPub:i,ecdhPriv:s,ecdsaPub:r,ecdsaPriv:p}))}catch{}return e}async function In(n,e){const t=await ge(),o=await ie(t.publicKey),i=await le(e.identityKey),s=await le(e.signedPrekey),r=e.oneTimePrekey?await le(e.oneTimePrekey):null,p=await oe(n.privateKey,s),c=await oe(t.privateKey,i),u=await oe(t.privateKey,s),y=r?await oe(t.privateKey,r):null,d=ht(p,c,u,...y?[y]:[]);return{sharedKey:await pt(d),ephemeralPublicKey:o}}async function En(n,e,t,o,i){const s=await le(t),r=await le(o),p=await oe(e.privateKey,s),c=await oe(n.privateKey,r),u=await oe(e.privateKey,r),y=i?await oe(i.privateKey,r):null,d=ht(p,c,u,...y?[y]:[]);return pt(d)}async function oe(n,e){return B().deriveBits({name:"ECDH",public:e},n,256)}function ht(...n){const e=n.reduce((i,s)=>i+s.byteLength,0),t=new Uint8Array(e);let o=0;for(const i of n)t.set(new Uint8Array(i),o),o+=i.byteLength;return t.buffer}async function pt(n){const e=await B().importKey("raw",n,"HKDF",!1,["deriveKey"]);return B().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 Tn=20;class Un{constructor(e){a(this,"kp");a(this,"shared");a(this,"identityKP");a(this,"signedPreKP");a(this,"signedPrekeyId");a(this,"otpKeys",[]);a(this,"x3dhShared");a(this,"pendingX3DH");this.storageKey=e}get ready(){return!!(this.shared??this.x3dhShared)}async begin(){return this.kp=await kn(this.storageKey),ie(this.kp.publicKey)}async onPeerKey(e){this.kp&&(this.shared=await bn(this.kp.privateKey,e))}async initX3DH(){this.identityKP=await dt(this.storageKey),this.signedPreKP=await ge(),this.signedPrekeyId=`spk-${Date.now()}-${Math.random().toString(36).slice(2)}`;for(let i=0;i<Tn;i++)this.otpKeys.push(await ge());const e=await ie(this.signedPreKP.publicKey),t=await Sn(this.identityKP.ecdsaKP.privateKey,this.signedPreKP.publicKey),o=await Promise.all(this.otpKeys.map(i=>ie(i.publicKey)));return{identityKey:this.identityKP.publicKeyB64,signedPrekey:e,signedPrekeyId:this.signedPrekeyId,signature:t,oneTimePrekeys:o}}async x3dhSendTo(e){this.identityKP||(this.identityKP=await dt(this.storageKey));const{sharedKey:t,ephemeralPublicKey:o}=await In(this.identityKP.ecdhKP,e);return this.x3dhShared=t,{ephemeralKey:o,spkId:e.signedPrekeyId,usedOTP:!!e.oneTimePrekey,senderIK:this.identityKP.publicKeyB64}}async x3dhReceiveFrom(e,t,o){if(!this.identityKP||!this.signedPreKP){this.pendingX3DH={senderIK:e,ephemeralKey:t,spkId:o};return}const i=this.otpKeys.shift();this.x3dhShared=await En(this.identityKP.ecdhKP,this.signedPreKP,e,t,i)}async flushPendingX3DH(){if(!this.pendingX3DH)return;const{senderIK:e,ephemeralKey:t,spkId:o}=this.pendingX3DH;this.pendingX3DH=void 0,await this.x3dhReceiveFrom(e,t,o)}async sealText(e,t){const o=this.x3dhShared??this.shared;if(!o)throw new Error("secure channel not ready");const{ct:i,iv:s}=await mn(o,e);return{kind:"text",text:i,enc:!0,iv:s,...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 vn(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 An(n){if(n.kind!=="text"||!n.enc)return null;const e=n;return!e.x3dhEK||!e.x3dhSPK||!e.x3dhIK?null:{x3dhEK:e.x3dhEK,x3dhSPK:e.x3dhSPK,x3dhIK:e.x3dhIK}}const ut="objectchat-widget-styles",Pn=["👍","❤️","😂","😮","😢","🙏"],Bn=400,Ln='<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M22 2 11 13M22 2l-7 20-4-9-9-4 20-7z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',Mn=`
|
|
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);
|
|
@@ -186,7 +186,7 @@ var RelayEmbed=function(J){"use strict";var ni=Object.defineProperty;var ii=(J,X
|
|
|
186
186
|
.ocw-row.theirs .ocw-translate-btn { right:auto; left:-26px; }
|
|
187
187
|
.ocw-bubble-wrap:hover .ocw-translate-btn { opacity:1; }
|
|
188
188
|
.ocw-translated-tag { font-size:10px; color:var(--ocw-mut); margin-top:2px; }
|
|
189
|
-
`;function zn(){if(typeof document>"u"||document.getElementById(ut))return;const n=document.createElement("style");n.id=ut,n.textContent=Mn,document.head.appendChild(n)}function c(n,e,t){const o=document.createElement(n);return e&&(o.className=e),t!==void 0&&(o.textContent=t),o}function Kn(n){try{return new Date(n).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function Fe(n){var e;switch(n.kind){case"text":return n.text;case"system":return typeof((e=n.data)==null?void 0:e.message)=="string"?String(n.data.message):n.event;case"card":return[n.title,n.body].filter(Boolean).join(" — ");case"attachment":return n.name??n.url;case"form":return n.prompt;case"appointment":return`📅 ${n.title} — ${new Date(n.startIso).toLocaleString()}`}}class $n{constructor(e,t,o,i={}){a(this,"scroll");a(this,"chips");a(this,"typing");a(this,"quick");a(this,"formHost");a(this,"csatPanel");a(this,"awayNotice");a(this,"preChatPanel");a(this,"deflectPanel");a(this,"preChatBuilt",!1);a(this,"preChatDone",!1);a(this,"footer");a(this,"input");a(this,"subjectCard");a(this,"e2eBadge");a(this,"statusBadge");a(this,"headerName");a(this,"connStatus");a(this,"typingTimer",null);a(this,"csatSubmitted",!1);a(this,"sendBtn");a(this,"compactObserver",null);a(this,"cobrowseBtn");a(this,"cobrowseCanvas");a(this,"cobrowseToolbar");a(this,"cobrowseHint");a(this,"cobrowseActive",!1);a(this,"cobrowseColor","#f5713c");a(this,"lastAnnotationVersion",-1);a(this,"storeRef",null);a(this,"scrollCleanup",null);a(this,"translationCache",new Map);a(this,"showingTranslation",new Set);a(this,"subjectBuilt",!1);var C,E,L,T,H,R,W,ee,k,$;this.root=e,this.me=t,this.h=o,this.cfg=i,zn(),e.replaceChildren(),e.classList.add("ocw"),i.accent&&e.style.setProperty("--ocw-accent",i.accent);const s=c("div","ocw-head");if(this.h.onBack){const b=c("button","ocw-back","‹");b.type="button",b.setAttribute("aria-label","Back"),b.addEventListener("click",()=>this.h.onBack()),s.append(b)}const r=c("div","ocw-avatar");if((C=i.userInfo)!=null&&C.avatar){const b=document.createElement("img");b.src=i.userInfo.avatar,b.alt=i.userInfo.name??"You",b.style.cssText="width:100%;height:100%;border-radius:50%;object-fit:cover",r.append(b)}else r.textContent=(E=i.userInfo)!=null&&E.name?i.userInfo.name[0].toUpperCase():"🧑";s.append(r);const p=c("div","ocw-head-main");this.headerName=c("div","ocw-head-name",((L=i.subject)==null?void 0:L.ownerLabel)??((T=i.subject)==null?void 0:T.title)??""),p.append(this.headerName),(H=i.subject)!=null&&H.subtitle&&p.append(c("div","ocw-head-meta",i.subject.subtitle)),s.append(p),this.statusBadge=c("span","ocw-badge",((R=i.subject)==null?void 0:R.status)??""),(W=i.subject)!=null&&W.status||(this.statusBadge.style.display="none"),s.append(this.statusBadge),this.e2eBadge=c("span","ocw-e2e","🔒 E2E"),this.e2eBadge.style.display="none",s.append(this.e2eBadge),this.connStatus=c("span","ocw-conn-status"),this.connStatus.style.display="none",s.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()}),s.append(this.cobrowseBtn),s.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 l=c("div","ocw-typing-bubble");l.append(c("div","ocw-typing-dot"),c("div","ocw-typing-dot"),c("div","ocw-typing-dot")),this.typing.append(c("div","ocw-dot","🧑"),l),this.quick=c("div","ocw-quick");for(const b of i.quickReplies??[]){const P=c("button",void 0,b);P.addEventListener("click",()=>{this.h.onSend(b),this.quick.style.display="none"}),this.quick.append(P)}this.formHost=c("div","ocw-form-host"),this.csatPanel=c("div","ocw-csat"),this.csatPanel.style.display="none",this.awayNotice=c("div","ocw-away"),this.awayNotice.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=((ee=i.i18n)==null?void 0:ee.placeholder)??"Message…";const u=c("button","ocw-sendbtn");u.type="button";const y=(k=i.i18n)==null?void 0:k.send;y?(u.textContent=y,u.classList.add("ocw-sendbtn-label"),u.setAttribute("aria-label",y)):(u.innerHTML=Ln,u.setAttribute("aria-label","Send message")),u.disabled=!0,this.sendBtn=u,u.addEventListener("click",()=>this.flushSend()),this.input.addEventListener("input",()=>{var b,P;this.sendBtn.disabled=this.input.value.trim().length===0,this.autoGrowInput(),this.storeRef&&!this.storeRef.messages().some(N=>N.senderRole==="guest")?(P=(b=this.h).onDeflectQuery)==null||P.call(b,this.input.value):this.hideDeflection()}),this.input.addEventListener("keydown",b=>{b.isComposing||b.keyCode===229||(b.key==="Enter"&&!b.shiftKey?(b.preventDefault(),this.flushSend()):this.signalTyping())});const d=c("button","ocw-attach","📎");d.title="Attach image or file";const f=document.createElement("input");f.type="file",f.accept="image/*,.pdf,.txt,.doc,.docx",f.style.display="none",d.addEventListener("click",()=>f.click()),f.addEventListener("change",()=>{var b;(b=f.files)!=null&&b[0]&&this.h.onAttach&&this.h.onAttach(f.files[0]),f.value=""});const w=c("div","ocw-input");w.append(d,f,this.input,u);const I=c("div","ocw-footer");(($=i.i18n)==null?void 0:$.poweredBy)!==void 0?I.textContent=i.i18n.poweredBy:I.innerHTML='Powered by <a href="https://relay.paramms.com" target="_blank" rel="noopener">Relay</a>',this.footer=I,e.append(s,this.chips,this.scroll,this.typing,this.quick,this.formHost,this.csatPanel,this.preChatPanel,this.deflectPanel,this.awayNotice,w,this.footer),this.cobrowseCanvas=c("canvas","ocw-cobrowse-canvas"),this.cobrowseToolbar=c("div","ocw-cobrowse-toolbar");for(const b of["#f5713c","#1c1b1a","#2563eb","#16a34a","#dc2626"]){const P=c("button","ocw-cobrowse-swatch");P.style.background=b,P.type="button",b===this.cobrowseColor&&P.classList.add("sel"),P.addEventListener("click",()=>{this.cobrowseColor=b;for(const N of this.cobrowseToolbar.querySelectorAll(".ocw-cobrowse-swatch"))N.classList.remove("sel");P.classList.add("sel")}),this.cobrowseToolbar.append(P)}const v=c("button","ocw-cobrowse-clear","Clear");v.addEventListener("click",()=>{var b,P;return(P=(b=this.h).onAnnotateClear)==null?void 0:P.call(b)}),this.cobrowseToolbar.append(v),this.cobrowseHint=c("div","ocw-cobrowse-hint","🖍 Draw to point things out — visible to both sides"),e.append(this.cobrowseCanvas,this.cobrowseToolbar,this.cobrowseHint),this.bindCobrowsePointerEvents();const g=b=>{e.classList.toggle("ocw-compact",b>0&&b<Bn)};g(e.clientWidth),typeof ResizeObserver<"u"&&(this.compactObserver=new ResizeObserver(b=>{var N;const P=((N=b[0])==null?void 0:N.contentRect.width)??e.clientWidth;g(P)}),this.compactObserver.observe(e))}getScrollEl(){return this.scroll}setScrollCleanup(e){var t;(t=this.scrollCleanup)==null||t.call(this),this.scrollCleanup=e}destroy(){var e,t;(e=this.scrollCleanup)==null||e.call(this),this.scrollCleanup=null,this.typingTimer&&(clearTimeout(this.typingTimer),this.typingTimer=null),(t=this.compactObserver)==null||t.disconnect(),this.compactObserver=null}flushSend(){this.hideDeflection();const e=this.input.value.trim();e&&(this.input.value="",this.sendBtn.disabled=!0,this.autoGrowInput(),this.h.onTyping(!1),this.h.onSend(e))}autoGrowInput(){this.input.style.height="auto";const e=this.input.scrollHeight;e>0?this.input.style.height=`${Math.min(e,120)}px`:this.input.style.removeProperty("height")}signalTyping(){const e=this.input.value.trim().slice(0,100)||void 0;this.h.onTyping(!0,e),this.typingTimer&&clearTimeout(this.typingTimer),this.typingTimer=setTimeout(()=>this.h.onTyping(!1),2e3)}render(e){var d,f,w,I,v;if(this.storeRef=e,this.cobrowseBtn.classList.toggle("show",!!e.subject),!e.subject&&this.cobrowseActive&&(this.cobrowseActive=!1,this.updateCobrowseUI()),this.cobrowseActive&&e.annotationVersion!==this.lastAnnotationVersion&&(this.lastAnnotationVersion=e.annotationVersion,this.resizeCobrowseCanvas(),this.redrawCobrowse()),e.accent&&this.root.style.setProperty("--ocw-accent",e.accent),this.e2eBadge.style.display=e.e2e?"inline-flex":"none",this.buildSubjectCard(e),e.subject){const g=(d=this.cfg.subject)==null?void 0:d.ownerLabel;g&&(this.headerName.textContent=g)}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 g of t)this.chips.append(this.chipEl(g));const o=this.scroll.scrollHeight,i=this.scroll.scrollTop;if(this.scroll.replaceChildren(),this.subjectCard.childNodes.length&&this.scroll.append(this.subjectCard),e.hasMoreHistory){const g=c("div","ocw-load-more");g.textContent="↑ Loading earlier messages…",g.style.pointerEvents="none",this.scroll.append(g)}let s=0;for(const g of e.messages())this.scroll.append(this.messageEl(g,e)),g.senderId!==this.me&&g.seq>s&&(s=g.seq);i>20?this.scroll.scrollTop=this.scroll.scrollHeight-o+i:this.scroll.scrollTop=this.scroll.scrollHeight,s>0&&this.h.onReadUpTo(s);const r=[...e.typing];this.typing.classList.toggle("active",r.length>0);const p=this.typing.querySelector(".ocw-typing-bubble");p&&p.setAttribute("aria-label",r.length?"typing":""),this.footer.style.display=e.whiteLabel?"none":"block";const l=e.messages().some(g=>g.senderRole==="guest");if(!!((f=e.preChat)!=null&&f.enabled)&&!this.preChatDone&&!l&&(e.preChat.showWhen!=="offline"||e.offline))this.preChatBuilt||this.buildPreChatPanel(e.preChat),this.preChatPanel.style.display="block",this.awayNotice.style.display="none",(w=this.root.querySelector(".ocw-input"))==null||w.style.setProperty("display","none");else{if(this.preChatPanel.style.display="none",e.offline){this.awayNotice.firstChild||this.awayNotice.append(c("span","ocw-away-icon","🌙"),c("span","",""));const g=this.awayNotice.lastChild;g.textContent=e.offlineMessage||((I=this.cfg.i18n)==null?void 0:I.offline)||"We're away right now — send your message and we'll reply as soon as we're back.",this.awayNotice.style.display="flex"}else this.awayNotice.style.display="none";(v=this.root.querySelector(".ocw-input"))==null||v.style.removeProperty("display")}const y=["resolved","closed","sold","issued","checked_out"];this.h.onCsat&&!this.csatSubmitted&&y.includes(e.state)&&e.messages().length>0&&(this.csatPanel.style.display==="none"&&this.buildCsatPanel(),this.csatPanel.style.display="block")}setConnStatus(e,t){if(e==="open"){this.connStatus.style.display="none";return}this.connStatus.style.display="";const o=e==="error";this.connStatus.className=`ocw-conn-status${o?" err":e==="reconnecting"?" warn":""}`,this.connStatus.textContent=o?`⚠ ${t??"Chat unavailable"}`:e==="reconnecting"?t??"↻ reconnecting…":"● connecting…"}buildPreChatPanel(e){var l;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"),o={};for(const u of e.fields??["name","email"]){const y=c("input","ocw-offline-input");y.type=u==="email"?"email":u==="phone"?"tel":"text",y.placeholder=u==="name"?"Your name":u==="email"?"Your email":"Your phone number",o[u]=y,t.append(y)}let i=null;if((l=e.topics)!=null&&l.length){i=c("select",void 0);const u=document.createElement("option");u.value="",u.textContent="What is this about?",i.append(u);for(const y of e.topics){const d=document.createElement("option");d.value=y,d.textContent=y,i.append(d)}t.append(i)}let s=null,r=null;if(e.callbackOption){const u=c("label","ocw-prechat-cb");s=document.createElement("input"),s.type="checkbox",u.append(s,document.createTextNode("📞 Request a call back")),t.append(u),o.phone||(r=c("input","ocw-offline-input"),r.type="tel",r.placeholder="Phone number for the call",r.style.display="none",s.addEventListener("change",()=>r.style.setProperty("display",s.checked?"block":"none")),t.append(r))}const p=c("button","ocw-offline-submit","Start chat");p.type="button",p.addEventListener("click",()=>{var f,w,I,v,g,C,E;const u=(f=o.email)==null?void 0:f.value.trim();if(o.email&&(!u||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(u))){o.email.focus();return}const y=!!(s!=null&&s.checked),d=(((w=o.phone)==null?void 0:w.value)??(r==null?void 0:r.value)??"").trim();if(y&&!d){(I=o.phone??r)==null||I.focus();return}if(i&&((v=e.topics)!=null&&v.length)&&!i.value){i.focus();return}p.disabled=!0,this.completePreChat(),(E=(C=this.h).onPreChat)==null||E.call(C,{...(g=o.name)!=null&&g.value.trim()?{name:o.name.value.trim()}:{},...u?{email:u}:{},...d?{phone:d}:{},...i!=null&&i.value?{topic:i.value}:{},...y?{callback:!0}:{}})}),t.append(p),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 o=c("button","ocw-deflect-card");o.append(c("div","ocw-deflect-q",t.title),c("div","ocw-deflect-a",t.answer)),o.addEventListener("click",()=>o.classList.toggle("open")),this.deflectPanel.append(o)}this.deflectPanel.style.display="flex"}hideDeflection(){this.deflectPanel.style.display="none",this.deflectPanel.replaceChildren()}buildCsatPanel(){this.csatPanel.replaceChildren(),this.csatPanel.append(c("div","ocw-csat-title","How did we do?"));const e=c("div","ocw-csat-stars"),t=[];for(let o=1;o<=5;o++){const i=c("button","ocw-csat-star","★");i.dataset.score=String(o),i.addEventListener("mouseenter",()=>t.forEach((s,r)=>s.classList.toggle("lit",r<o))),i.addEventListener("mouseleave",()=>t.forEach(s=>s.classList.remove("lit"))),i.addEventListener("click",()=>{var s,r;this.csatSubmitted=!0,this.csatPanel.replaceChildren(c("div","ocw-csat-done",`Thanks for your ${o}★ rating!`)),(r=(s=this.h).onCsat)==null||r.call(s,o)}),t.push(i),e.append(i)}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 o=this.cobrowseCanvas.width,i=this.cobrowseCanvas.height;t.strokeStyle=e.color,t.lineWidth=Math.max(1,e.width*Math.min(o,i)),t.lineJoin="round",t.lineCap="round",t.beginPath(),t.moveTo(e.points[0].x*o,e.points[0].y*i);for(const s of e.points.slice(1))t.lineTo(s.x*o,s.y*i);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 o of((t=this.storeRef)==null?void 0:t.annotations)??[])this.drawStroke(o)}}bindCobrowsePointerEvents(){let e=!1,t=[];const o=r=>{const p=this.cobrowseCanvas.getBoundingClientRect(),l=p.width>0?(r.clientX-p.left)/p.width:0,u=p.height>0?(r.clientY-p.top)/p.height:0;return{x:Math.min(1,Math.max(0,l)),y:Math.min(1,Math.max(0,u))}},i=.006;this.cobrowseCanvas.addEventListener("pointerdown",r=>{this.cobrowseActive&&(e=!0,t=[o(r)],this.cobrowseCanvas.setPointerCapture(r.pointerId))}),this.cobrowseCanvas.addEventListener("pointermove",r=>{e&&(t.push(o(r)),this.redrawCobrowse(),this.drawStroke({points:t,color:this.cobrowseColor,width:i}))});const s=r=>{var p,l;if(e){e=!1,t.length>1&&((l=(p=this.h).onAnnotate)==null||l.call(p,{id:`an_${Date.now()}_${Math.random().toString(36).slice(2)}`,points:t,color:this.cobrowseColor,width:i})),t=[];try{this.cobrowseCanvas.releasePointerCapture(r.pointerId)}catch{}}};this.cobrowseCanvas.addEventListener("pointerup",s),this.cobrowseCanvas.addEventListener("pointercancel",s)}buildSubjectCard(e){if(this.subjectBuilt)return;const t=e.subject,o=this.cfg.subject,i=(t==null?void 0:t.title)??(o==null?void 0:o.title);if(!i)return;this.subjectBuilt=!0,this.subjectCard.replaceChildren(),this.subjectCard.append(c("div","ocw-subject-title",i)),o!=null&&o.subtitle&&this.subjectCard.append(c("div","ocw-subject-sub",o.subtitle));const s=c("div","ocw-tags");if(t)for(const[p,l]of Object.entries(t.fields))s.append(c("span","ocw-tag",`${p}: ${l}`));else for(const p of(o==null?void 0:o.tags)??[])s.append(c("span","ocw-tag",p));s.childNodes.length&&this.subjectCard.append(s);const r=(t==null?void 0:t.state)??(o==null?void 0:o.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 o;e.confirm&&!await this.confirm(e.label)||((o=e.input)!=null&&o.length?this.openForm(e):this.h.onInvoke(e.id))}),t}confirm(e){return new Promise(t=>{const o=c("div","ocw-modal"),i=c("div","ocw-modal-card");i.append(c("div","ocw-modal-title",e)),i.append(c("div","ocw-modal-body",`Confirm “${e}”?`));const s=c("div","ocw-modal-actions"),r=c("button","ocw-modal-cancel","Cancel"),p=c("button","ocw-modal-ok","Confirm"),l=u=>{o.remove(),t(u)};r.addEventListener("click",()=>l(!1)),p.addEventListener("click",()=>l(!0)),o.addEventListener("click",u=>{u.target===o&&l(!1)}),s.append(r,p),i.append(s),o.append(i),this.root.append(o),p.focus()})}openForm(e){var p,l;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 o=new Map;for(const u of e.input??[]){const y=c("label","ocw-form-row");if(y.append(c("span","ocw-form-lbl",u.label)),u.type==="select"&&((p=u.options)!=null&&p.length)){const d=c("select","ocw-form-input");u.required||d.append(c("option",void 0,"— select —"));for(const f of u.options){const w=c("option");w.value=f,w.textContent=f,d.append(w)}u.required&&(d.required=!0),y.append(d),o.set(u.name,d)}else{const d=c("input","ocw-form-input");d.type=u.type==="number"?"number":u.type==="date"?"datetime-local":"text",u.required&&(d.required=!0),y.append(d),o.set(u.name,d)}t.append(y)}const i=c("div","ocw-form-actions"),s=c("button","ocw-form-cancel","Cancel"),r=c("button","ocw-form-submit","Send");s.addEventListener("click",()=>this.formHost.replaceChildren()),r.addEventListener("click",()=>{const u={};for(const[y,d]of o){if(d.required&&!d.value){d.style.borderColor="#e5484d";return}u[y]=d.type==="number"?Number(d.value):d.value}this.formHost.replaceChildren(),this.h.onInvoke(e.id,u)}),i.append(s,r),t.append(i),this.formHost.append(t),(l=o.values().next().value)==null||l.focus()}messageEl(e,t){var d;if(e.senderRole==="system"){const f=c("div","ocw-sys");return f.textContent=e.deletedAt?"message deleted":Fe(e.content),f}const o=e.senderId===this.me,i=!!e.internal,s=c("div",`ocw-row ${i?"ocw-note mine":o?"mine":"theirs"} ${e.senderRole==="bot"?"ocw-bot":""}`);!o&&!i&&s.append(c("div","ocw-dot",e.senderRole==="bot"?"🤖":"🧑"));const r=c("div"),p=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 l=c("div","ocw-bubble");let u=null;if(e.deletedAt)l.append(c("span","ocw-deleted","message deleted"));else if(e.content.kind==="attachment"){const f=e.content;if((d=f.mime)!=null&&d.startsWith("image/")){const w=document.createElement("img");w.src=f.url,w.alt=f.name??"image",w.style.cssText="max-width:220px;max-height:160px;border-radius:10px;display:block;cursor:pointer",w.addEventListener("click",()=>window.open(f.url,"_blank")),l.append(w)}else{const w=document.createElement("a");w.href=f.url,w.target="_blank",w.rel="noopener",w.style.cssText="display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none",w.append(c("span",void 0,"📄"),c("span",void 0,f.name??"file")),l.append(w)}}else if(e.content.kind==="appointment"){const f=e.content,w=c("div","ocw-appt");w.append(c("div","ocw-appt-title",`📅 ${f.title}`)),w.append(c("div","ocw-appt-time",new Date(f.startIso).toLocaleString()+" – "+new Date(f.endIso).toLocaleTimeString())),f.location&&w.append(c("div","ocw-appt-loc",`📍 ${f.location}`)),f.description&&w.append(c("div","ocw-appt-desc",f.description));const I=c("div","ocw-appt-links"),v=document.createElement("a");v.href=f.googleUrl,v.target="_blank",v.rel="noopener",v.className="ocw-appt-btn",v.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",I.append(v,g),w.append(I),l.append(w)}else u=document.createTextNode(Fe(e.content)),l.append(u),e.editedAt&&l.append(c("span","ocw-edited","(edited)"));if(p.append(l),!o&&!i&&this.h.onTranslate&&e.content.kind==="text"&&!e.deletedAt&&e.seq>0&&u){const f=e.content.text;if(f.trim()){const w=c("button","ocw-translate-btn","🌐");w.type="button",w.title="Translate",w.addEventListener("click",I=>{if(I.stopPropagation(),this.showingTranslation.has(e.id)){this.showingTranslation.delete(e.id),u.textContent=f,w.textContent="🌐",w.title="Translate";return}const v=this.translationCache.get(e.id);if(v!==void 0){this.showingTranslation.add(e.id),u.textContent=v,w.textContent="↩",w.title="Show original";return}w.textContent="⏳",this.h.onTranslate(f).then(g=>{if(g===null){w.textContent="⚠️",w.title="Translation unavailable",setTimeout(()=>{w.textContent="🌐",w.title="Translate"},1500);return}this.translationCache.set(e.id,g),this.showingTranslation.add(e.id),u.textContent=g,w.textContent="↩",w.title="Show original"})}),p.append(w)}}if(o&&!e.deletedAt&&e.seq>0&&(this.h.onEdit??this.h.onDelete)){const f=c("div","ocw-msg-menu");if(this.h.onEdit){const w=c("button",void 0,"✏️");w.title="Edit",w.addEventListener("click",I=>{I.stopPropagation();const v=Fe(e.content),g=document.createElement("textarea");g.value=v,g.rows=Math.min(4,Math.ceil(v.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 C=c("button","ocw-form-submit","Save");C.style.cssText="margin-top:6px;padding:5px 14px;font-size:13px";const E=c("button","ocw-form-cancel","Cancel");E.style.cssText="margin-top:6px;padding:5px 10px;font-size:13px";const L=c("div");L.style.cssText="display:flex;gap:6px;justify-content:flex-end",L.append(E,C);const T=c("div");T.append(g,L),l.replaceChildren(T),g.focus(),g.select();const H=()=>l.replaceChildren(u??document.createTextNode(v));E.addEventListener("click",H),C.addEventListener("click",()=>{const R=g.value.trim();R&&R!==v&&this.h.onEdit(e.id,R),H()}),g.addEventListener("keydown",R=>{R.key==="Enter"&&!R.shiftKey&&(R.preventDefault(),C.click()),R.key==="Escape"&&H()})}),f.append(w)}if(this.h.onDelete){const w=c("button","del","🗑");w.title="Delete",w.addEventListener("click",I=>{I.stopPropagation(),this.h.onDelete(e.id)}),f.append(w)}p.append(f)}if(r.append(p),this.h.onReact&&!e.deletedAt&&e.seq>0){const f=c("div","ocw-react-wrap"),w=c("div","ocw-react");if(e.reactions&&Object.keys(e.reactions).length)for(const[g,C]of Object.entries(e.reactions)){const E=c("button",`ocw-react-pill${C.includes(this.me)?" mine":""}`,`${g} ${C.length}`);E.addEventListener("click",()=>{var L,T;return(T=(L=this.h).onReact)==null?void 0:T.call(L,e.id,g,C.includes(this.me))}),w.append(E)}const I=c("button","ocw-react-btn","+"),v=c("div","ocw-react-picker");for(const g of Pn){const C=c("button",void 0,g);C.addEventListener("click",E=>{var T,H,R,W;E.stopPropagation();const L=(H=(T=e.reactions)==null?void 0:T[g])==null?void 0:H.includes(this.me);(W=(R=this.h).onReact)==null||W.call(R,e.id,g,!!L),v.style.display="none"}),v.append(C)}v.style.display="none",I.addEventListener("click",g=>{g.stopPropagation();const C=v.style.display==="none";v.style.display=C?"flex":"none",C&&document.addEventListener("click",()=>{v.style.display="none"},{once:!0})}),w.append(I),f.append(w,v),r.append(f)}else e.reactions&&Object.keys(e.reactions).length&&r.append(c("div","ocw-react",Object.entries(e.reactions).map(([f,w])=>`${f}${w.length}`).join(" ")));const y=c("div","ocw-time ocw-meta",Kn(e.ts));if(o&&e.status){const f=c("span",`ocw-tick${e.status==="read"?" read":e.status==="delivered"?" delivered":""}`,Dn(e.status));y.append(f)}return o&&e.seq>0&&t.lastReadByOthers>=e.seq&&y.append(c("span","ocw-seen"," · Seen")),r.append(y),s.append(r),s}}function Dn(n){switch(n){case"read":return"✓✓";case"delivered":return"✓✓";case"sent":return"✓";default:return"🕓"}}const Rn=20;function Oe(n,e){var l;const t=n.trim().replace(/\/+$/,""),o=(l=t.match(/^(https|http|wss|ws):\/\//))==null?void 0:l[1],i=o?o==="https"||o==="wss":!0,s=(o?t.slice(o.length+3):t).replace(/\/ws$/,""),r=e?e.trim().replace(/\/+$/,""):`${i?"https":"http"}://${s}`;return{wsUrl:`${i?"wss":"ws"}://${s}/ws`,httpBase:r}}function _n(n){return Oe(n).httpBase}function jn(n,e,t,o){const i=`beforeSeq=${t}&limit=${o}`;return[`${n}/conversations/${e}/messages?${i}`,`${n}/conversations/${e}/history?${i}`]}async function ft(n,e,t,o,i=Rn){for(const s of jn(n,e,o,i))try{const r=await fetch(s,{headers:{authorization:`Bearer ${t}`}});if(!r.ok)continue;const p=await r.json();return{messages:p.messages??[],hasMore:p.hasMore??!1}}catch{}return null}async function Hn(n,e,t,o,i,s){const r=s?s.replace(/\/+$/,""):_n(n),p=await ft(r,t,e,Number.MAX_SAFE_INTEGER);if(!p||(p.messages.length?(o.apply({type:"sync",conversationId:t,messages:p.messages}),o.apply({type:"history",conversationId:t,messages:[],hasMore:p.hasMore}),i.render(o)):o.apply({type:"history",conversationId:t,messages:[],hasMore:!1}),!p.hasMore))return;let l=!1;const u=async()=>{if(l||!o.hasMoreHistory)return;l=!0;const w=o.messages()[0];if(!w){l=!1;return}const I=await ft(r,t,e,w.seq);I&&(o.apply({type:"history",conversationId:t,messages:I.messages,hasMore:I.hasMore}),i.render(o)),l=!1},y=i.getScrollEl();if(!y)return;let d=!1;setTimeout(()=>{d=!0},300);const f=()=>{d&&y.scrollTop<80&&o.hasMoreHistory&&!l&&u()};y.addEventListener("scroll",f,{passive:!0}),i.setScrollCleanup(()=>y.removeEventListener("scroll",f))}const xe=new WeakMap,Ue=new Map;function wt(n){return`relay-launcher::${n.profileId}::${n.subjectId??""}`}let ye=null;function qn(){if(ye&&ye.state!=="closed")return ye;try{return ye=new AudioContext,ye}catch{return null}}function gt(n){var Se,Ie,bt,mt,vt;xe.has(n.el)&&(xe.get(n.el).close(),xe.delete(n.el)),n.launcher&&((Se=Ue.get(wt(n)))==null||Se.close());const e=et();let t,o=!1;const i=n.token??n.userId??e,s=i!==e?e:void 0,{wsUrl:r,httpBase:p}=Oe(n.url,n.apiUrl);let l=new dn(i);const u=n.subjectId?`${i}::${n.subjectId}`:i,y=new yn(u);let d,f=!1,w=null,I=null,v=null,g=null;!n.launcher&&!n.el.style.height&&n.el.clientHeight===0&&(n.el.style.width=n.el.style.width||"100%",n.el.style.height="600px");for(const h of y.load())l.addOptimistic(h.clientMsgId,h.content);let C=null,E=null,L=0,T=!n.launcher;if(n.launcher){const x=(n.position??"bottom-right").includes("right");C=document.createElement("div"),C.style.cssText=`position:fixed;${x?"right:20px":"left:20px"};bottom:20px;z-index:9999;display:flex;flex-direction:column;align-items:${x?"flex-end":"flex-start"};gap:12px`;const S=document.createElement("div"),j=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(max-width: 479px)"):null,Le=D=>{n.el.classList.toggle("ocw-fs",D),S.style.cssText=D?["position:fixed","inset:0","width:100%","height:100dvh","border-radius:0","overflow:hidden","box-shadow:none","display:none","flex-direction:column","background:#fff","transition:opacity .18s","opacity:0","z-index:9998"].join(";"):["width:min(380px, calc(100vw - 40px))","height:min(600px, calc(100dvh - 108px))","border-radius:16px","overflow:hidden","box-shadow:0 8px 40px rgba(0,0,0,.18)","display:none","flex-direction:column","background:#fff","transform-origin:bottom "+(x?"right":"left"),"transition:opacity .18s,transform .18s","opacity:0","transform:scale(.95)"].join(";")};Le((j==null?void 0:j.matches)??!1);const Me=D=>Le(D.matches);j==null||j.addEventListener("change",Me),w=j,I=Me,n.el.style.cssText="width:100%;height:100%;overflow:hidden",S.append(n.el);const Xe='<svg viewBox="0 0 24 24" width="26" height="26" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',Ge='<svg viewBox="0 0 24 24" width="22" height="22" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/></svg>',V=document.createElement("button");V.type="button",V.style.cssText=["width:56px;height:56px;border-radius:50%",`background:${n.accent??"#4F63F5"}`,"color:#fff;border:none;cursor:pointer","box-shadow:0 4px 16px rgba(0,0,0,.25)","position:relative;flex:none","display:flex;align-items:center;justify-content:center","transition:transform .15s"].join(";"),V.onmouseenter=()=>{V.style.transform="scale(1.08)"},V.onmouseleave=()=>{V.style.transform="scale(1)"},E=document.createElement("span"),E.style.cssText="position:absolute;top:-4px;right:-4px;background:#ef4444;color:#fff;border-radius:50%;width:20px;height:20px;font-size:11px;font-weight:700;display:none;align-items:center;justify-content:center";const ze=()=>{V.innerHTML=T?Ge:Xe,V.setAttribute("aria-label",T?"Close chat":"Open chat"),V.setAttribute("aria-expanded",String(T)),V.append(E)};ze(),C.append(S,V),document.body.append(C);const Ye=`ocw-teaser-dismissed::${n.profileId}`,Ke=typeof n.launcherMessage=="string"?{title:n.launcherMessage}:n.launcherMessage;let K=null;const ei=()=>{try{return sessionStorage.getItem(Ye)==="1"}catch{return!1}},ti='<svg viewBox="0 0 24 24" width="15" height="15" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',kt=()=>{const D=Ke!=null&&Ke.title?Ke:l.launcherMessage??void 0;if(!(!!(D!=null&&D.title)&&!T&&!ei())){K&&(K.remove(),K=null);return}if(K)return;K=document.createElement("div"),K.setAttribute("role","button"),K.setAttribute("tabindex","0"),K.setAttribute("aria-label",D.title),K.style.cssText=["max-width:280px","background:#fff","border-radius:14px","box-shadow:0 6px 28px rgba(0,0,0,.16)","padding:14px 40px 14px 16px","position:relative","cursor:pointer","font-family:inherit",`align-self:${x?"flex-end":"flex-start"}`,"animation:ocw-teaser-in .22s ease-out"].join(";");const Ze=document.createElement("div");if(Ze.textContent=D.title,Ze.style.cssText="font-size:15px;font-weight:600;color:#111;line-height:1.35",K.append(Ze),D.subtitle){const ne=document.createElement("div");ne.style.cssText="display:flex;align-items:center;gap:6px;margin-top:6px;font-size:13px;color:#6b7280";const Qe=document.createElement("span");Qe.innerHTML=ti,Qe.style.cssText=`color:${n.accent??"#4F63F5"};display:inline-flex`;const It=document.createElement("span");It.textContent=D.subtitle,ne.append(Qe,It),K.append(ne)}const pe=document.createElement("button");pe.type="button",pe.setAttribute("aria-label","Dismiss"),pe.innerHTML='<svg viewBox="0 0 24 24" width="14" height="14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M18 6 6 18M6 6l12 12" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/></svg>',pe.style.cssText="position:absolute;top:8px;right:8px;width:24px;height:24px;border:none;border-radius:50%;background:#f3f4f6;color:#6b7280;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0",pe.addEventListener("click",ne=>{ne.stopPropagation();try{sessionStorage.setItem(Ye,"1")}catch{}K&&(K.remove(),K=null)}),K.append(pe);const St=()=>{T||(T=!0,Je(!0),ze(),L=0,E&&(E.style.display="none"),K&&(K.remove(),K=null))};K.addEventListener("click",St),K.addEventListener("keydown",ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),St())}),C.insertBefore(K,V)};if(!document.getElementById("ocw-teaser-style")){const D=document.createElement("style");D.id="ocw-teaser-style",D.textContent="@keyframes ocw-teaser-in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",document.head.append(D)}g=kt,kt();const Je=D=>{D?(S.style.display="flex",requestAnimationFrame(()=>{S.style.opacity="1",S.style.transform="scale(1)"})):(S.style.opacity="0",S.style.transform="scale(.95)",setTimeout(()=>{T||(S.style.display="none")},180))};V.addEventListener("click",()=>{if(T=!T,Je(T),ze(),T){L=0,E&&(E.style.display="none");try{sessionStorage.setItem(Ye,"1")}catch{}}g==null||g()}),v=D=>{D.key==="Escape"&&T&&(T=!1,Je(!1),ze())},document.addEventListener("keydown",v)}const H=()=>{T||(L++,E&&(E.textContent=String(L),E.style.display="flex"))},R=()=>{try{const h=qn();if(!h)return;h.state==="suspended"&&h.resume().catch(()=>{});const x=h.createOscillator(),S=h.createGain();x.connect(S),S.connect(h.destination),x.frequency.setValueAtTime(880,h.currentTime),x.frequency.exponentialRampToValueAtTime(440,h.currentTime+.15),S.gain.setValueAtTime(.3,h.currentTime),S.gain.exponentialRampToValueAtTime(.001,h.currentTime+.3),x.start(),x.stop(h.currentTime+.3)}catch{}},W=[],ee=h=>{for(;W.length;){const x=W.shift();y.add({clientMsgId:x.clientMsgId,content:x.content,ts:Date.now()}),k.send({type:"send",conversationId:h,clientMsgId:x.clientMsgId,content:x.content})}};let k;const $=new Un(`ocw-e2e-${n.profileId}`);let b=!1;const P=[],N=[];let ve=!1;const de=(h,x)=>{$.sealText(x).then(S=>{d&&k.send({type:"send",conversationId:d,clientMsgId:h,content:S})})},Be=(h,x,S)=>{$.sealText(x,S).then(j=>{d&&k.send({type:"send",conversationId:d,clientMsgId:h,content:j})})},m=()=>{for(;P.length;){const h=P.shift();de(h.clientMsgId,h.text)}for(;N.length;){const h=N.shift();de(h.clientMsgId,h.text)}},M=h=>{k.send({type:"fetchPrekey",targetUserId:h})},q=n.i18n??{},G=["ar","he","fa","ur"],F=typeof navigator<"u"?(navigator.language??"").slice(0,2).toLowerCase():"";G.includes(F)&&!n.el.dir&&(n.el.dir="rtl",n.el.style.fontFamily=n.el.style.fontFamily||"Tahoma,Arial,system-ui,sans-serif");const Y=new pn,U=`oc_prechat_${n.profileId}_${i.slice(-8)}`,z=new $n(n.el,i,{onSend(h){const x=`cm_${Math.random().toString(36).slice(2)}`,S={kind:"text",text:h};l.addOptimistic(x,S),z.render(l),l.e2e?$.ready?de(x,h):ve?N.push({clientMsgId:x,text:h}):(P.push({clientMsgId:x,text:h}),l.assignedAgentId&&M(l.assignedAgentId)):d?(y.add({clientMsgId:x,content:S,ts:Date.now()}),k.send({type:"send",conversationId:d,clientMsgId:x,content:S})):W.push({clientMsgId:x,content:S})},async onAttach(h){if(!d)return;const x=`${p}/upload?name=${encodeURIComponent(h.name)}`,S=`cm_${Math.random().toString(36).slice(2)}`;l.addOptimistic(S,{kind:"text",text:`📎 Uploading ${h.name}…`}),z.render(l);try{const j=await fetch(x,{method:"POST",headers:{"content-type":h.type,authorization:`Bearer ${i}`},body:h});if(!j.ok)throw new Error(`Upload failed: ${j.status}`);const{url:Le,name:Me,mime:Xe,size:Ge}=await j.json();k.send({type:"send",conversationId:d,clientMsgId:S,content:{kind:"attachment",url:Le,name:Me,mime:Xe,size:Ge}})}catch(j){l.addOptimistic(S,{kind:"text",text:`⚠️ Upload failed: ${j.message}`}),z.render(l)}},onInvoke(h,x){d&&k.send({type:"invoke",conversationId:d,actionId:h,clientInvokeId:`iv_${Math.random().toString(36).slice(2)}`,...x?{inputs:x}:{}})},onTyping(h,x){d&&k.send({type:"typing",conversationId:d,isTyping:h,...x?{preview:x}:{}})},onPreChat(h){try{localStorage.setItem(U,"1")}catch{}k.send({type:"open",profileId:n.profileId,...n.subjectId?{subjectId:n.subjectId}:{},userInfo:{...h.name?{name:h.name}:{},...h.email?{email:h.email}:{},...h.phone||h.topic?{meta:{...h.phone?{phone:h.phone}:{},...h.topic?{topic:h.topic}:{}}}:{}}});const x=h.callback?`📞 Call-back requested${h.phone?`: ${h.phone}`:""}${h.topic?` — ${h.topic}`:""}`:h.topic?`Topic: ${h.topic}`:"";x&&d&&!l.e2e&&k.send({type:"send",conversationId:d,clientMsgId:`pc_${Math.random().toString(36).slice(2,12)}`,content:{kind:"text",text:x}})},onDeflectQuery(h){if(o)return;clearTimeout(t);const x=h.trim();if(x.length<3){z.hideDeflection();return}t=setTimeout(()=>{fetch(`${p}/kb/search?profileId=${encodeURIComponent(n.profileId)}&q=${encodeURIComponent(x.slice(0,200))}`).then(S=>S.ok?S.json():{articles:[]}).then(S=>z.showDeflection(S.articles??[])).catch(()=>z.hideDeflection())},350)},onReadUpTo(h){d&&k.send({type:"read",conversationId:d,seq:h})},onLoadMore(){if(!d||!l.e2e)return;const h=l.messages()[0];h&&k.send({type:"history",conversationId:d,beforeSeq:h.seq,limit:20})},onEdit(h,x){d&&k.send({type:"edit",conversationId:d,messageId:h,content:{kind:"text",text:x}})},onDelete(h){d&&k.send({type:"delete",conversationId:d,messageId:h})},onReact(h,x,S){d&&k.send({type:"react",conversationId:d,messageId:h,emoji:x,remove:S})},onCsat(h){d&&fetch(`${p}/conversations/${d}/csat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({score:h})}).catch(()=>{})},onAnnotate(h){d&&k.send({type:"annotate",conversationId:d,stroke:h})},onAnnotateClear(){d&&k.send({type:"annotate_clear",conversationId:d})},...n.translateLang?{async onTranslate(h){try{const x=await fetch(`${p}/translate`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${i}`},body:JSON.stringify({text:h,targetLang:n.translateLang})});if(!x.ok)return null;const{translated:S}=await x.json();return S}catch{return null}}}:{},...n.onBack?{onBack:n.onBack}:{}},{...n.subject?{subject:n.subject}:{},...n.quickReplies?{quickReplies:n.quickReplies}:{},...n.accent?{accent:n.accent}:{},...(Ie=n.user)!=null&&Ie.name||(bt=n.user)!=null&&bt.avatar?{userInfo:{...n.user.name?{name:n.user.name}:{},...n.user.avatar?{avatar:n.user.avatar}:{}}}:{},i18n:q});try{localStorage.getItem(U)&&z.completePreChat()}catch{}const he=n.user&&(n.user.name||n.user.email||n.user.avatar||n.user.meta)?{...n.user.name?{name:n.user.name}:{},...n.user.email?{email:n.user.email}:{},...n.user.avatar?{avatar:n.user.avatar}:{},...n.user.meta?{meta:n.user.meta}:{}}:void 0,ke={type:"open",profileId:n.profileId,...n.kind==="direct"&&n.peerId?{kind:"direct",peerId:n.peerId}:n.subjectId?{subjectId:n.subjectId}:{},...s?{linkFrom:s}:{},...he?{userInfo:he}:{},...typeof location<"u"?{pageUrl:location.href}:{},...typeof document<"u"&&document.title?{pageTitle:document.title}:{},...(mt=n.subject)!=null&&mt.title?{subjectTitle:n.subject.title}:{},...(vt=n.subject)!=null&&vt.subtitle?{subjectMeta:n.subject.subtitle}:{}};k=new un({...n.refreshToken?{refreshToken:n.refreshToken}:{},url:r,token:i,open:ke,getCursor:()=>l.highestSeq(),onStatusChange:(h,x)=>z.setConnStatus(h,x),onFrame(h){if(Y.apply(h),h.type==="opened"){if(d=h.conversation.id,!f){f=!0;for(const x of y.load())k.send({type:"send",conversationId:d,clientMsgId:x.clientMsgId,content:x.content})}Hn(r,i,d,l,z,p),W.length&&ee(d)}if(h.type==="ack"&&y.remove(h.clientMsgId),h.type==="prekeyBundle"){h.bundle&&(ve=!0,$.x3dhSendTo(h.bundle).then(x=>{const S=[...P.splice(0),...N.splice(0)];for(const j of S)Be(j.clientMsgId,j.text,x);z.render(l)}));return}if(h.type==="message"&&l.e2e){const x=An(h.message.content);if(x&&!$.ready){$.x3dhReceiveFrom(x.x3dhIK,x.x3dhEK,x.x3dhSPK).then(async()=>{await $.openFrame(h),l.apply(h),z.render(l)});return}}if(h.type==="peerkey"){$.onPeerKey(h.key).then(()=>{m(),z.render(l)});return}(async()=>{if(l.e2e&&await $.openFrame(h),l.apply(h),h.type==="manifest"&&(g==null||g()),h.type==="message"&&h.message.senderId!==i&&!h.message.internal&&(H(),R()),l.e2e&&d&&!b){b=!0;const x=await $.initX3DH();k.send({type:"uploadPrekeys",...x});const S=await $.begin();k.send({type:"pubkey",conversationId:d,key:S})}z.render(l)})()}}),k.connect(),z.render(l);const ae=n.launcher?wt(n):null,te={close:()=>{o=!0,clearTimeout(t),k.close(),C==null||C.remove(),z.destroy(),Y.destroy(),w&&I&&w.removeEventListener("change",I),v&&(document.removeEventListener("keydown",v),v=null),xe.delete(n.el),ae&&Ue.get(ae)===te&&Ue.delete(ae)}};return xe.set(n.el,te),ae&&Ue.set(ae,te),te}const We="wss://api.paramms.com/ws";function Nn(n,e){const t=n.profileId??n.appId;if(!t)throw new Error("Relay: `profileId` is required (your chatroom id, e.g. 'p_...').");const o=n.subjectId??(n.listingId?`listing_${n.listingId}`:void 0),i=n.launcher??!0,s=n.contextTitle??n.listingTitle??n.subjectTitle,r=n.contextSubtitle??n.listingMeta??n.subjectMeta,p=n.contextStatus??n.listingStatus??n.subjectStatus,l=n.listingPrice??n.subjectPrice,u=s?{title:s,...r?{subtitle:r}:{},...l!=null?{tags:[`$${l.toLocaleString()}`]}:{},...p?{status:p}:{}}:void 0,y=n.subject??u,d=n.userName??n.name,f=n.userEmail??n.email,w=n.userAvatar??n.avatar,I=d||f||w?{...d?{name:d}:{},...f?{email:f}:{},...w?{avatar:w}:{}}:void 0,v=n.user??I,g=n.launcherMessage&&typeof n.launcherMessage=="object"?n.launcherMessage:n.launcherMessage?n.launcherSubtitle?{title:n.launcherMessage,subtitle:n.launcherSubtitle}:n.launcherMessage:void 0;return{el:e,url:n.url??We,profileId:t,...n.apiUrl?{apiUrl:n.apiUrl}:{},...o?{subjectId:o}:{},...n.token?{token:n.token}:{},...n.refreshToken?{refreshToken:n.refreshToken}:{},...n.userId?{userId:n.userId}:{},...y?{subject:y}:{},...v?{user:v}:{},...n.quickReplies?{quickReplies:n.quickReplies}:{},...n.i18n?{i18n:n.i18n}:{},...n.accent?{accent:n.accent}:{},...n.translateLang?{translateLang:n.translateLang}:{},...g?{launcherMessage:g}:{},...xt(n)&&!i?{onBack:()=>{be=!0,me=!1,Ae(re)}}:{},launcher:i,position:n.position??"bottom-right"}}let Z=null,_=null,se=!1,re={},be=!1,me=!1;function xt(n){return!!(n.inbox||n.inboxStart)}let Q=null;function Fn(n,e){const t=!e&&!!n.el;if(se&&!t&&(_.innerHTML="",_=null,se=!1),t){const o=typeof n.el=="string"?document.querySelector(n.el):n.el;o instanceof HTMLElement?(_&&_!==o&&!se&&_.remove(),_=o,se=!0):console.error(`[Relay] \`el\` ("${String(n.el)}") did not match any element — falling back to an auto-created host.`)}return(!_||!se&&!_.isConnected)&&(_=document.createElement("div"),_.id="relay-widget-root",document.body.appendChild(_),se=!1),!e&&n.height&&(_.style.height=n.height,_.style.width||(_.style.width="100%")),_}function Ae(n){try{const e=n.launcher??!0;Q==null||Q(),Q=null,Z==null||Z.close(),Z=null;const t=Fn(n,e);if(xt(n)&&!e&&be){On(n,t);return}Z=gt(Nn(n,t))}catch(e){console.error("[Relay]",e instanceof Error?e.message:e)}}async function On(n,e){const t=n.profileId??n.appId;if(!t&&!n.tenantId){console.error("[Relay] `inbox` requires `profileId` or `tenantId`.");return}e.innerHTML="";const o=document.createElement("div");o.style.cssText="position:relative;width:100%;height:100%;overflow:hidden;background:#fff";const i=document.createElement("div");i.style.cssText="position:absolute;inset:0";const s=document.createElement("div");s.style.cssText="position:absolute;inset:0;display:none";const r=document.createElement("button");r.type="button",r.setAttribute("aria-label","Close"),r.textContent="✕",r.style.cssText="position:absolute;top:8px;right:8px;z-index:20;width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.05);border:none;color:#1c1b1a;font-size:16px;line-height:1;cursor:pointer",r.onclick=()=>{be=!1,Ae(re)},o.append(i,s),!me&&!!t&&o.append(r),e.appendChild(o);let l=null,u=null;Q=()=>{u==null||u.close(),l==null||l.close(),e.innerHTML=""};let y;try{({mountChatList:y}=await Promise.resolve().then(()=>Qn))}catch(f){console.error("[Relay] could not load the conversation list module.",f),i.isConnected&&(i.style.cssText+=";display:flex;align-items:center;justify-content:center;padding:16px;font:13px system-ui;color:#b91c1c;text-align:center",i.textContent="Could not load conversations.");return}if(!i.isConnected)return;const d=f=>{const w=f.profileId??t;if(!w){console.error("[Relay] conversation row has no chatroom; cannot open it.",f);return}r.style.display="none",u==null||u.close(),u=gt({el:s,url:n.url??We,...n.apiUrl?{apiUrl:n.apiUrl}:{},profileId:w,...f.kind==="direct"&&f.peerId?{kind:"direct",peerId:f.peerId}:f.subjectId?{subjectId:f.subjectId}:{},...n.token?{token:n.token}:{},...n.refreshToken?{refreshToken:n.refreshToken}:{},...n.userId?{userId:n.userId}:{},...n.userId||n.userName||n.userEmail||n.userAvatar?{user:{...n.userName?{name:n.userName}:{},...n.userEmail?{email:n.userEmail}:{},...n.userAvatar?{avatar:n.userAvatar}:{}}}:{},...f.subjectTitle?{subject:{title:f.subjectTitle,...f.subjectMeta?{subtitle:f.subjectMeta}:{}}}:{},...n.accent?{accent:n.accent}:{},launcher:!1,onBack:()=>{u==null||u.close(),u=null,s.style.display="none",i.style.display="",r.style.display="",l==null||l.refresh()}}),i.style.display="none",s.style.display=""};l=y({el:i,url:n.url??We,...n.apiUrl?{apiUrl:n.apiUrl}:{},...t?{profileId:t}:{},...n.tenantId?{tenantId:n.tenantId}:{},scope:n.inboxScope??"tenant",onSelect:d,onNewChat:()=>{const f=t??(l==null?void 0:l.defaultProfileId());f&&d({id:"__new__",profileId:f,state:"open",updatedAt:Date.now()})},...n.token?{token:n.token}:{},...n.userId?{userId:n.userId}:{},...n.accent?{accent:n.accent}:{}})}function yt(n){me=!!(n.inboxStart&&!(n.launcher??!0)),be=me,re={...n},Ae(re)}function Wn(n){re={...re,...n},Ae(re)}function Vn(){Q==null||Q(),Q=null,Z==null||Z.close(),Z=null,_&&!se&&_.remove(),_=null,se=!1,be=!1,me=!1,re={}}function Ve(n,e){switch(n){case"boot":yt(e??{});break;case"update":case"identify":Wn(e??{});break;case"shutdown":Vn();break;default:console.warn("[Relay] unknown command:",n)}}function Xn(){if(typeof document>"u")return null;const n=document.querySelector("script[data-relay-app]")??document.querySelector("script[data-relay-profile-id]")??document.querySelector("script[data-relay-tenant-id]"),e=n==null?void 0:n.dataset,t=(e==null?void 0:e.relayApp)??(e==null?void 0:e.relayProfileId),o=e==null?void 0:e.relayTenantId;if(!t&&!o)return null;const i=t?{profileId:t}:{};o&&(i.tenantId=o),e.relayUser&&(i.userId=e.relayUser),e.relayToken&&(i.token=e.relayToken),e.relayListing&&(i.listingId=e.relayListing),e.relayAccent&&(i.accent=e.relayAccent),e.relayUrl&&(i.url=e.relayUrl);const s=e.relayPosition;(s==="bottom-left"||s==="bottom-right")&&(i.position=s),e.relayLauncherMessage&&(i.launcherMessage=e.relayLauncherMessage),e.relayLauncherSubtitle&&(i.launcherSubtitle=e.relayLauncherSubtitle),e.relayLauncher==="false"&&(i.launcher=!1),e.relayUserName&&(i.userName=e.relayUserName),e.relayUserEmail&&(i.userEmail=e.relayUserEmail),e.relayUserAvatar&&(i.userAvatar=e.relayUserAvatar),e.relayContextTitle&&(i.contextTitle=e.relayContextTitle),e.relayContextSubtitle&&(i.contextSubtitle=e.relayContextSubtitle),e.relayContextStatus&&(i.contextStatus=e.relayContextStatus),e.relayListingTitle&&(i.listingTitle=e.relayListingTitle),e.relayListingMeta&&(i.listingMeta=e.relayListingMeta),e.relayListingPrice&&(i.listingPrice=Number(e.relayListingPrice)),e.relayListingStatus&&(i.listingStatus=e.relayListingStatus),e.relayTarget&&(i.el=e.relayTarget),e.relayHeight&&(i.height=e.relayHeight),e.relayInbox==="true"&&(i.inbox=!0),e.relayInbox==="false"&&(i.inbox=!1),e.relayInboxStart==="true"&&(i.inboxStart=!0),e.relayInboxStart==="false"&&(i.inboxStart=!1);const r=e.relayInboxScope;return(r==="tenant"||r==="profile")&&(i.inboxScope=r),i}if(typeof window<"u"){const n=window,e=n.Relay&&n.Relay.q?n.Relay.q:[];n.Relay=Ve;let t=!1;for(const o of e){const[i,s]=o;i==="boot"&&(t=!0),Ve(i,s)}if(!t){const o=n.relaySettings??Xn();o&&yt(o)}}function Gn(n){const e=Math.floor((Date.now()-n)/1e3);if(e<60)return"just now";if(e<3600)return`${Math.floor(e/60)}m`;if(e<86400)return`${Math.floor(e/3600)}h`;const t=Math.floor(e/86400);if(t<=7)return`${t}d`;try{return new Date(n).toLocaleDateString(void 0,{month:"short",day:"numeric"})}catch{return`${t}d`}}const Yn='<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="currentColor" fill-opacity="0.12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function A(n,e,t){const o=document.createElement(n);return e&&(o.className=e),t!==void 0&&(o.textContent=t),o}const Jn=`
|
|
189
|
+
`;function zn(){if(typeof document>"u"||document.getElementById(ut))return;const n=document.createElement("style");n.id=ut,n.textContent=Mn,document.head.appendChild(n)}function l(n,e,t){const o=document.createElement(n);return e&&(o.className=e),t!==void 0&&(o.textContent=t),o}function Kn(n){try{return new Date(n).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function Fe(n){var e;switch(n.kind){case"text":return n.text;case"system":return typeof((e=n.data)==null?void 0:e.message)=="string"?String(n.data.message):n.event;case"card":return[n.title,n.body].filter(Boolean).join(" — ");case"attachment":return n.name??n.url;case"form":return n.prompt;case"appointment":return`📅 ${n.title} — ${new Date(n.startIso).toLocaleString()}`}}class $n{constructor(e,t,o,i={}){a(this,"scroll");a(this,"chips");a(this,"typing");a(this,"quick");a(this,"formHost");a(this,"csatPanel");a(this,"awayNotice");a(this,"preChatPanel");a(this,"deflectPanel");a(this,"preChatBuilt",!1);a(this,"preChatDone",!1);a(this,"footer");a(this,"input");a(this,"subjectCard");a(this,"e2eBadge");a(this,"statusBadge");a(this,"headerName");a(this,"connStatus");a(this,"typingTimer",null);a(this,"csatSubmitted",!1);a(this,"sendBtn");a(this,"compactObserver",null);a(this,"cobrowseBtn");a(this,"cobrowseCanvas");a(this,"cobrowseToolbar");a(this,"cobrowseHint");a(this,"cobrowseActive",!1);a(this,"cobrowseColor","#f5713c");a(this,"lastAnnotationVersion",-1);a(this,"storeRef",null);a(this,"scrollCleanup",null);a(this,"translationCache",new Map);a(this,"showingTranslation",new Set);a(this,"subjectBuilt",!1);var I,E,L,T,H,D,W,ee,k,$;this.root=e,this.me=t,this.h=o,this.cfg=i,zn(),e.replaceChildren(),e.classList.add("ocw"),i.accent&&e.style.setProperty("--ocw-accent",i.accent);const s=l("div","ocw-head");if(this.h.onBack){const b=l("button","ocw-back","‹");b.type="button",b.setAttribute("aria-label","Back"),b.addEventListener("click",()=>this.h.onBack()),s.append(b)}const r=l("div","ocw-avatar");if((I=i.userInfo)!=null&&I.avatar){const b=document.createElement("img");b.src=i.userInfo.avatar,b.alt=i.userInfo.name??"You",b.style.cssText="width:100%;height:100%;border-radius:50%;object-fit:cover",r.append(b)}else r.textContent=(E=i.userInfo)!=null&&E.name?i.userInfo.name[0].toUpperCase():"🧑";s.append(r);const p=l("div","ocw-head-main");this.headerName=l("div","ocw-head-name",((L=i.subject)==null?void 0:L.ownerLabel)??((T=i.subject)==null?void 0:T.title)??""),p.append(this.headerName),(H=i.subject)!=null&&H.subtitle&&p.append(l("div","ocw-head-meta",i.subject.subtitle)),s.append(p),this.statusBadge=l("span","ocw-badge",((D=i.subject)==null?void 0:D.status)??""),(W=i.subject)!=null&&W.status||(this.statusBadge.style.display="none"),s.append(this.statusBadge),this.e2eBadge=l("span","ocw-e2e","🔒 E2E"),this.e2eBadge.style.display="none",s.append(this.e2eBadge),this.connStatus=l("span","ocw-conn-status"),this.connStatus.style.display="none",s.append(this.connStatus),this.cobrowseBtn=l("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()}),s.append(this.cobrowseBtn),s.append(l("button","ocw-menu","⋯")),this.chips=l("div","ocw-chiprow"),this.scroll=l("div","ocw-scroll"),this.subjectCard=l("div","ocw-subject"),this.typing=l("div","ocw-typing");const c=l("div","ocw-typing-bubble");c.append(l("div","ocw-typing-dot"),l("div","ocw-typing-dot"),l("div","ocw-typing-dot")),this.typing.append(l("div","ocw-dot","🧑"),c),this.quick=l("div","ocw-quick");for(const b of i.quickReplies??[]){const P=l("button",void 0,b);P.addEventListener("click",()=>{this.h.onSend(b),this.quick.style.display="none"}),this.quick.append(P)}this.formHost=l("div","ocw-form-host"),this.csatPanel=l("div","ocw-csat"),this.csatPanel.style.display="none",this.awayNotice=l("div","ocw-away"),this.awayNotice.style.display="none",this.preChatPanel=l("div","ocw-prechat"),this.preChatPanel.style.display="none",this.deflectPanel=l("div","ocw-deflect"),this.deflectPanel.style.display="none",this.input=l("textarea",void 0),this.input.rows=1,this.input.placeholder=((ee=i.i18n)==null?void 0:ee.placeholder)??"Message…";const u=l("button","ocw-sendbtn");u.type="button";const y=(k=i.i18n)==null?void 0:k.send;y?(u.textContent=y,u.classList.add("ocw-sendbtn-label"),u.setAttribute("aria-label",y)):(u.innerHTML=Ln,u.setAttribute("aria-label","Send message")),u.disabled=!0,this.sendBtn=u,u.addEventListener("click",()=>this.flushSend()),this.input.addEventListener("input",()=>{var b,P;this.sendBtn.disabled=this.input.value.trim().length===0,this.autoGrowInput(),this.storeRef&&!this.storeRef.messages().some(N=>N.senderRole==="guest")?(P=(b=this.h).onDeflectQuery)==null||P.call(b,this.input.value):this.hideDeflection()}),this.input.addEventListener("keydown",b=>{b.isComposing||b.keyCode===229||(b.key==="Enter"&&!b.shiftKey?(b.preventDefault(),this.flushSend()):this.signalTyping())});const d=l("button","ocw-attach","📎");d.title="Attach image or file";const f=document.createElement("input");f.type="file",f.accept="image/*,.pdf,.txt,.doc,.docx",f.style.display="none",d.addEventListener("click",()=>f.click()),f.addEventListener("change",()=>{var b;(b=f.files)!=null&&b[0]&&this.h.onAttach&&this.h.onAttach(f.files[0]),f.value=""});const w=l("div","ocw-input");w.append(d,f,this.input,u);const C=l("div","ocw-footer");(($=i.i18n)==null?void 0:$.poweredBy)!==void 0?C.textContent=i.i18n.poweredBy:C.innerHTML='Powered by <a href="https://relay.paramms.com" target="_blank" rel="noopener">Relay</a>',this.footer=C,e.append(s,this.chips,this.scroll,this.typing,this.quick,this.formHost,this.csatPanel,this.preChatPanel,this.deflectPanel,this.awayNotice,w,this.footer),this.cobrowseCanvas=l("canvas","ocw-cobrowse-canvas"),this.cobrowseToolbar=l("div","ocw-cobrowse-toolbar");for(const b of["#f5713c","#1c1b1a","#2563eb","#16a34a","#dc2626"]){const P=l("button","ocw-cobrowse-swatch");P.style.background=b,P.type="button",b===this.cobrowseColor&&P.classList.add("sel"),P.addEventListener("click",()=>{this.cobrowseColor=b;for(const N of this.cobrowseToolbar.querySelectorAll(".ocw-cobrowse-swatch"))N.classList.remove("sel");P.classList.add("sel")}),this.cobrowseToolbar.append(P)}const v=l("button","ocw-cobrowse-clear","Clear");v.addEventListener("click",()=>{var b,P;return(P=(b=this.h).onAnnotateClear)==null?void 0:P.call(b)}),this.cobrowseToolbar.append(v),this.cobrowseHint=l("div","ocw-cobrowse-hint","🖍 Draw to point things out — visible to both sides"),e.append(this.cobrowseCanvas,this.cobrowseToolbar,this.cobrowseHint),this.bindCobrowsePointerEvents();const g=b=>{e.classList.toggle("ocw-compact",b>0&&b<Bn)};g(e.clientWidth),typeof ResizeObserver<"u"&&(this.compactObserver=new ResizeObserver(b=>{var N;const P=((N=b[0])==null?void 0:N.contentRect.width)??e.clientWidth;g(P)}),this.compactObserver.observe(e))}getScrollEl(){return this.scroll}setScrollCleanup(e){var t;(t=this.scrollCleanup)==null||t.call(this),this.scrollCleanup=e}destroy(){var e,t;(e=this.scrollCleanup)==null||e.call(this),this.scrollCleanup=null,this.typingTimer&&(clearTimeout(this.typingTimer),this.typingTimer=null),(t=this.compactObserver)==null||t.disconnect(),this.compactObserver=null}flushSend(){this.hideDeflection();const e=this.input.value.trim();e&&(this.input.value="",this.sendBtn.disabled=!0,this.autoGrowInput(),this.h.onTyping(!1),this.h.onSend(e))}autoGrowInput(){this.input.style.height="auto";const e=this.input.scrollHeight;e>0?this.input.style.height=`${Math.min(e,120)}px`:this.input.style.removeProperty("height")}signalTyping(){const e=this.input.value.trim().slice(0,100)||void 0;this.h.onTyping(!0,e),this.typingTimer&&clearTimeout(this.typingTimer),this.typingTimer=setTimeout(()=>this.h.onTyping(!1),2e3)}render(e){var d,f,w,C,v;if(this.storeRef=e,this.cobrowseBtn.classList.toggle("show",!!e.subject),!e.subject&&this.cobrowseActive&&(this.cobrowseActive=!1,this.updateCobrowseUI()),this.cobrowseActive&&e.annotationVersion!==this.lastAnnotationVersion&&(this.lastAnnotationVersion=e.annotationVersion,this.resizeCobrowseCanvas(),this.redrawCobrowse()),e.accent&&this.root.style.setProperty("--ocw-accent",e.accent),this.e2eBadge.style.display=e.e2e?"inline-flex":"none",this.buildSubjectCard(e),e.subject){const g=(d=this.cfg.subject)==null?void 0:d.ownerLabel;g&&(this.headerName.textContent=g)}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 g of t)this.chips.append(this.chipEl(g));const o=this.scroll.scrollHeight,i=this.scroll.scrollTop;if(this.scroll.replaceChildren(),this.subjectCard.childNodes.length&&this.scroll.append(this.subjectCard),e.hasMoreHistory){const g=l("div","ocw-load-more");g.textContent="↑ Loading earlier messages…",g.style.pointerEvents="none",this.scroll.append(g)}let s=0;for(const g of e.messages())this.scroll.append(this.messageEl(g,e)),g.senderId!==this.me&&g.seq>s&&(s=g.seq);i>20?this.scroll.scrollTop=this.scroll.scrollHeight-o+i:this.scroll.scrollTop=this.scroll.scrollHeight,s>0&&this.h.onReadUpTo(s);const r=[...e.typing];this.typing.classList.toggle("active",r.length>0);const p=this.typing.querySelector(".ocw-typing-bubble");p&&p.setAttribute("aria-label",r.length?"typing":""),this.footer.style.display=e.whiteLabel?"none":"block";const c=e.messages().some(g=>g.senderRole==="guest");if(!!((f=e.preChat)!=null&&f.enabled)&&!this.preChatDone&&!c&&(e.preChat.showWhen!=="offline"||e.offline))this.preChatBuilt||this.buildPreChatPanel(e.preChat),this.preChatPanel.style.display="block",this.awayNotice.style.display="none",(w=this.root.querySelector(".ocw-input"))==null||w.style.setProperty("display","none");else{if(this.preChatPanel.style.display="none",e.offline){this.awayNotice.firstChild||this.awayNotice.append(l("span","ocw-away-icon","🌙"),l("span","",""));const g=this.awayNotice.lastChild;g.textContent=e.offlineMessage||((C=this.cfg.i18n)==null?void 0:C.offline)||"We're away right now — send your message and we'll reply as soon as we're back.",this.awayNotice.style.display="flex"}else this.awayNotice.style.display="none";(v=this.root.querySelector(".ocw-input"))==null||v.style.removeProperty("display")}const y=["resolved","closed","sold","issued","checked_out"];this.h.onCsat&&!this.csatSubmitted&&y.includes(e.state)&&e.messages().length>0&&(this.csatPanel.style.display==="none"&&this.buildCsatPanel(),this.csatPanel.style.display="block")}setConnStatus(e,t){if(e==="open"){this.connStatus.style.display="none";return}this.connStatus.style.display="";const o=e==="error";this.connStatus.className=`ocw-conn-status${o?" err":e==="reconnecting"?" warn":""}`,this.connStatus.textContent=o?`⚠ ${t??"Chat unavailable"}`:e==="reconnecting"?t??"↻ reconnecting…":"● connecting…"}buildPreChatPanel(e){var c;this.preChatBuilt=!0,this.preChatPanel.replaceChildren(),this.preChatPanel.append(l("div","ocw-prechat-title",e.title??"Before we start…"));const t=l("div","ocw-offline-form"),o={};for(const u of e.fields??["name","email"]){const y=l("input","ocw-offline-input");y.type=u==="email"?"email":u==="phone"?"tel":"text",y.placeholder=u==="name"?"Your name":u==="email"?"Your email":"Your phone number",o[u]=y,t.append(y)}let i=null;if((c=e.topics)!=null&&c.length){i=l("select",void 0);const u=document.createElement("option");u.value="",u.textContent="What is this about?",i.append(u);for(const y of e.topics){const d=document.createElement("option");d.value=y,d.textContent=y,i.append(d)}t.append(i)}let s=null,r=null;if(e.callbackOption){const u=l("label","ocw-prechat-cb");s=document.createElement("input"),s.type="checkbox",u.append(s,document.createTextNode("📞 Request a call back")),t.append(u),o.phone||(r=l("input","ocw-offline-input"),r.type="tel",r.placeholder="Phone number for the call",r.style.display="none",s.addEventListener("change",()=>r.style.setProperty("display",s.checked?"block":"none")),t.append(r))}const p=l("button","ocw-offline-submit","Start chat");p.type="button",p.addEventListener("click",()=>{var f,w,C,v,g,I,E;const u=(f=o.email)==null?void 0:f.value.trim();if(o.email&&(!u||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(u))){o.email.focus();return}const y=!!(s!=null&&s.checked),d=(((w=o.phone)==null?void 0:w.value)??(r==null?void 0:r.value)??"").trim();if(y&&!d){(C=o.phone??r)==null||C.focus();return}if(i&&((v=e.topics)!=null&&v.length)&&!i.value){i.focus();return}p.disabled=!0,this.completePreChat(),(E=(I=this.h).onPreChat)==null||E.call(I,{...(g=o.name)!=null&&g.value.trim()?{name:o.name.value.trim()}:{},...u?{email:u}:{},...d?{phone:d}:{},...i!=null&&i.value?{topic:i.value}:{},...y?{callback:!0}:{}})}),t.append(p),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(l("div","ocw-deflect-hint","Instant answers — tap to expand"));for(const t of e.slice(0,3)){const o=l("button","ocw-deflect-card");o.append(l("div","ocw-deflect-q",t.title),l("div","ocw-deflect-a",t.answer)),o.addEventListener("click",()=>o.classList.toggle("open")),this.deflectPanel.append(o)}this.deflectPanel.style.display="flex"}hideDeflection(){this.deflectPanel.style.display="none",this.deflectPanel.replaceChildren()}buildCsatPanel(){this.csatPanel.replaceChildren(),this.csatPanel.append(l("div","ocw-csat-title","How did we do?"));const e=l("div","ocw-csat-stars"),t=[];for(let o=1;o<=5;o++){const i=l("button","ocw-csat-star","★");i.dataset.score=String(o),i.addEventListener("mouseenter",()=>t.forEach((s,r)=>s.classList.toggle("lit",r<o))),i.addEventListener("mouseleave",()=>t.forEach(s=>s.classList.remove("lit"))),i.addEventListener("click",()=>{var s,r;this.csatSubmitted=!0,this.csatPanel.replaceChildren(l("div","ocw-csat-done",`Thanks for your ${o}★ rating!`)),(r=(s=this.h).onCsat)==null||r.call(s,o)}),t.push(i),e.append(i)}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 o=this.cobrowseCanvas.width,i=this.cobrowseCanvas.height;t.strokeStyle=e.color,t.lineWidth=Math.max(1,e.width*Math.min(o,i)),t.lineJoin="round",t.lineCap="round",t.beginPath(),t.moveTo(e.points[0].x*o,e.points[0].y*i);for(const s of e.points.slice(1))t.lineTo(s.x*o,s.y*i);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 o of((t=this.storeRef)==null?void 0:t.annotations)??[])this.drawStroke(o)}}bindCobrowsePointerEvents(){let e=!1,t=[];const o=r=>{const p=this.cobrowseCanvas.getBoundingClientRect(),c=p.width>0?(r.clientX-p.left)/p.width:0,u=p.height>0?(r.clientY-p.top)/p.height:0;return{x:Math.min(1,Math.max(0,c)),y:Math.min(1,Math.max(0,u))}},i=.006;this.cobrowseCanvas.addEventListener("pointerdown",r=>{this.cobrowseActive&&(e=!0,t=[o(r)],this.cobrowseCanvas.setPointerCapture(r.pointerId))}),this.cobrowseCanvas.addEventListener("pointermove",r=>{e&&(t.push(o(r)),this.redrawCobrowse(),this.drawStroke({points:t,color:this.cobrowseColor,width:i}))});const s=r=>{var p,c;if(e){e=!1,t.length>1&&((c=(p=this.h).onAnnotate)==null||c.call(p,{id:`an_${Date.now()}_${Math.random().toString(36).slice(2)}`,points:t,color:this.cobrowseColor,width:i})),t=[];try{this.cobrowseCanvas.releasePointerCapture(r.pointerId)}catch{}}};this.cobrowseCanvas.addEventListener("pointerup",s),this.cobrowseCanvas.addEventListener("pointercancel",s)}buildSubjectCard(e){if(this.subjectBuilt)return;const t=e.subject,o=this.cfg.subject,i=(t==null?void 0:t.title)??(o==null?void 0:o.title);if(!i)return;this.subjectBuilt=!0,this.subjectCard.replaceChildren(),this.subjectCard.append(l("div","ocw-subject-title",i)),o!=null&&o.subtitle&&this.subjectCard.append(l("div","ocw-subject-sub",o.subtitle));const s=l("div","ocw-tags");if(t)for(const[p,c]of Object.entries(t.fields))s.append(l("span","ocw-tag",`${p}: ${c}`));else for(const p of(o==null?void 0:o.tags)??[])s.append(l("span","ocw-tag",p));s.childNodes.length&&this.subjectCard.append(s);const r=(t==null?void 0:t.state)??(o==null?void 0:o.status);r&&(this.statusBadge.textContent=r,this.statusBadge.style.display="inline-flex")}chipEl(e){const t=l("button","ocw-chip",e.icon?`${e.icon} ${e.label}`:e.label);return t.dataset.actionId=e.id,t.addEventListener("click",async()=>{var o;e.confirm&&!await this.confirm(e.label)||((o=e.input)!=null&&o.length?this.openForm(e):this.h.onInvoke(e.id))}),t}confirm(e){return new Promise(t=>{const o=l("div","ocw-modal"),i=l("div","ocw-modal-card");i.append(l("div","ocw-modal-title",e)),i.append(l("div","ocw-modal-body",`Confirm “${e}”?`));const s=l("div","ocw-modal-actions"),r=l("button","ocw-modal-cancel","Cancel"),p=l("button","ocw-modal-ok","Confirm"),c=u=>{o.remove(),t(u)};r.addEventListener("click",()=>c(!1)),p.addEventListener("click",()=>c(!0)),o.addEventListener("click",u=>{u.target===o&&c(!1)}),s.append(r,p),i.append(s),o.append(i),this.root.append(o),p.focus()})}openForm(e){var p,c;this.formHost.replaceChildren();const t=l("div","ocw-form");t.append(l("div","ocw-form-title",e.icon?`${e.icon} ${e.label}`:e.label));const o=new Map;for(const u of e.input??[]){const y=l("label","ocw-form-row");if(y.append(l("span","ocw-form-lbl",u.label)),u.type==="select"&&((p=u.options)!=null&&p.length)){const d=l("select","ocw-form-input");u.required||d.append(l("option",void 0,"— select —"));for(const f of u.options){const w=l("option");w.value=f,w.textContent=f,d.append(w)}u.required&&(d.required=!0),y.append(d),o.set(u.name,d)}else{const d=l("input","ocw-form-input");d.type=u.type==="number"?"number":u.type==="date"?"datetime-local":"text",u.required&&(d.required=!0),y.append(d),o.set(u.name,d)}t.append(y)}const i=l("div","ocw-form-actions"),s=l("button","ocw-form-cancel","Cancel"),r=l("button","ocw-form-submit","Send");s.addEventListener("click",()=>this.formHost.replaceChildren()),r.addEventListener("click",()=>{const u={};for(const[y,d]of o){if(d.required&&!d.value){d.style.borderColor="#e5484d";return}u[y]=d.type==="number"?Number(d.value):d.value}this.formHost.replaceChildren(),this.h.onInvoke(e.id,u)}),i.append(s,r),t.append(i),this.formHost.append(t),(c=o.values().next().value)==null||c.focus()}messageEl(e,t){var d;if(e.senderRole==="system"){const f=l("div","ocw-sys");return f.textContent=e.deletedAt?"message deleted":Fe(e.content),f}const o=e.senderId===this.me,i=!!e.internal,s=l("div",`ocw-row ${i?"ocw-note mine":o?"mine":"theirs"} ${e.senderRole==="bot"?"ocw-bot":""}`);!o&&!i&&s.append(l("div","ocw-dot",e.senderRole==="bot"?"🤖":"🧑"));const r=l("div"),p=l("div","ocw-bubble-wrap");if(e.replyToId){const f=l("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 c=l("div","ocw-bubble");let u=null;if(e.deletedAt)c.append(l("span","ocw-deleted","message deleted"));else if(e.content.kind==="attachment"){const f=e.content;if((d=f.mime)!=null&&d.startsWith("image/")){const w=document.createElement("img");w.src=f.url,w.alt=f.name??"image",w.style.cssText="max-width:220px;max-height:160px;border-radius:10px;display:block;cursor:pointer",w.addEventListener("click",()=>window.open(f.url,"_blank")),c.append(w)}else{const w=document.createElement("a");w.href=f.url,w.target="_blank",w.rel="noopener",w.style.cssText="display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none",w.append(l("span",void 0,"📄"),l("span",void 0,f.name??"file")),c.append(w)}}else if(e.content.kind==="appointment"){const f=e.content,w=l("div","ocw-appt");w.append(l("div","ocw-appt-title",`📅 ${f.title}`)),w.append(l("div","ocw-appt-time",new Date(f.startIso).toLocaleString()+" – "+new Date(f.endIso).toLocaleTimeString())),f.location&&w.append(l("div","ocw-appt-loc",`📍 ${f.location}`)),f.description&&w.append(l("div","ocw-appt-desc",f.description));const C=l("div","ocw-appt-links"),v=document.createElement("a");v.href=f.googleUrl,v.target="_blank",v.rel="noopener",v.className="ocw-appt-btn",v.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",C.append(v,g),w.append(C),c.append(w)}else u=document.createTextNode(Fe(e.content)),c.append(u),e.editedAt&&c.append(l("span","ocw-edited","(edited)"));if(p.append(c),!o&&!i&&this.h.onTranslate&&e.content.kind==="text"&&!e.deletedAt&&e.seq>0&&u){const f=e.content.text;if(f.trim()){const w=l("button","ocw-translate-btn","🌐");w.type="button",w.title="Translate",w.addEventListener("click",C=>{if(C.stopPropagation(),this.showingTranslation.has(e.id)){this.showingTranslation.delete(e.id),u.textContent=f,w.textContent="🌐",w.title="Translate";return}const v=this.translationCache.get(e.id);if(v!==void 0){this.showingTranslation.add(e.id),u.textContent=v,w.textContent="↩",w.title="Show original";return}w.textContent="⏳",this.h.onTranslate(f).then(g=>{if(g===null){w.textContent="⚠️",w.title="Translation unavailable",setTimeout(()=>{w.textContent="🌐",w.title="Translate"},1500);return}this.translationCache.set(e.id,g),this.showingTranslation.add(e.id),u.textContent=g,w.textContent="↩",w.title="Show original"})}),p.append(w)}}if(o&&!e.deletedAt&&e.seq>0&&(this.h.onEdit??this.h.onDelete)){const f=l("div","ocw-msg-menu");if(this.h.onEdit){const w=l("button",void 0,"✏️");w.title="Edit",w.addEventListener("click",C=>{C.stopPropagation();const v=Fe(e.content),g=document.createElement("textarea");g.value=v,g.rows=Math.min(4,Math.ceil(v.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 I=l("button","ocw-form-submit","Save");I.style.cssText="margin-top:6px;padding:5px 14px;font-size:13px";const E=l("button","ocw-form-cancel","Cancel");E.style.cssText="margin-top:6px;padding:5px 10px;font-size:13px";const L=l("div");L.style.cssText="display:flex;gap:6px;justify-content:flex-end",L.append(E,I);const T=l("div");T.append(g,L),c.replaceChildren(T),g.focus(),g.select();const H=()=>c.replaceChildren(u??document.createTextNode(v));E.addEventListener("click",H),I.addEventListener("click",()=>{const D=g.value.trim();D&&D!==v&&this.h.onEdit(e.id,D),H()}),g.addEventListener("keydown",D=>{D.key==="Enter"&&!D.shiftKey&&(D.preventDefault(),I.click()),D.key==="Escape"&&H()})}),f.append(w)}if(this.h.onDelete){const w=l("button","del","🗑");w.title="Delete",w.addEventListener("click",C=>{C.stopPropagation(),this.h.onDelete(e.id)}),f.append(w)}p.append(f)}if(r.append(p),this.h.onReact&&!e.deletedAt&&e.seq>0){const f=l("div","ocw-react-wrap"),w=l("div","ocw-react");if(e.reactions&&Object.keys(e.reactions).length)for(const[g,I]of Object.entries(e.reactions)){const E=l("button",`ocw-react-pill${I.includes(this.me)?" mine":""}`,`${g} ${I.length}`);E.addEventListener("click",()=>{var L,T;return(T=(L=this.h).onReact)==null?void 0:T.call(L,e.id,g,I.includes(this.me))}),w.append(E)}const C=l("button","ocw-react-btn","+"),v=l("div","ocw-react-picker");for(const g of Pn){const I=l("button",void 0,g);I.addEventListener("click",E=>{var T,H,D,W;E.stopPropagation();const L=(H=(T=e.reactions)==null?void 0:T[g])==null?void 0:H.includes(this.me);(W=(D=this.h).onReact)==null||W.call(D,e.id,g,!!L),v.style.display="none"}),v.append(I)}v.style.display="none",C.addEventListener("click",g=>{g.stopPropagation();const I=v.style.display==="none";v.style.display=I?"flex":"none",I&&document.addEventListener("click",()=>{v.style.display="none"},{once:!0})}),w.append(C),f.append(w,v),r.append(f)}else e.reactions&&Object.keys(e.reactions).length&&r.append(l("div","ocw-react",Object.entries(e.reactions).map(([f,w])=>`${f}${w.length}`).join(" ")));const y=l("div","ocw-time ocw-meta",Kn(e.ts));if(o&&e.status){const f=l("span",`ocw-tick${e.status==="read"?" read":e.status==="delivered"?" delivered":""}`,Rn(e.status));y.append(f)}return o&&e.seq>0&&t.lastReadByOthers>=e.seq&&y.append(l("span","ocw-seen"," · Seen")),r.append(y),s.append(r),s}}function Rn(n){switch(n){case"read":return"✓✓";case"delivered":return"✓✓";case"sent":return"✓";default:return"🕓"}}const Dn=20;function Oe(n,e){var c;const t=n.trim().replace(/\/+$/,""),o=(c=t.match(/^(https|http|wss|ws):\/\//))==null?void 0:c[1],i=o?o==="https"||o==="wss":!0,s=(o?t.slice(o.length+3):t).replace(/\/ws$/,""),r=e?e.trim().replace(/\/+$/,""):`${i?"https":"http"}://${s}`;return{wsUrl:`${i?"wss":"ws"}://${s}/ws`,httpBase:r}}function _n(n){return Oe(n).httpBase}function jn(n,e,t,o){const i=`beforeSeq=${t}&limit=${o}`;return[`${n}/conversations/${e}/messages?${i}`,`${n}/conversations/${e}/history?${i}`]}async function ft(n,e,t,o,i=Dn){let s,r=!1;for(const p of jn(n,e,o,i))try{const c=await fetch(p,{headers:{authorization:`Bearer ${t}`}});if(r=!0,!c.ok)continue;const u=await c.json();return{messages:u.messages??[],hasMore:u.hasMore??!1}}catch(c){s=c}return r?console.error(`[chat-widget] history request to ${n} was rejected for conversation ${e}.`):console.error(`[chat-widget] could not load history from ${n} — the request never reached the server. This is almost always CORS: add this site's origin to the chatroom's allowed origins (dashboard → chatroom → allowed origins) or to the server's CORS_ORIGINS.`,s),null}async function Hn(n,e,t,o,i,s){const r=s?s.replace(/\/+$/,""):_n(n),p=await ft(r,t,e,Number.MAX_SAFE_INTEGER);if(!p||(p.messages.length?(o.apply({type:"sync",conversationId:t,messages:p.messages}),o.apply({type:"history",conversationId:t,messages:[],hasMore:p.hasMore}),i.render(o)):o.apply({type:"history",conversationId:t,messages:[],hasMore:!1}),!p.hasMore))return;let c=!1;const u=async()=>{if(c||!o.hasMoreHistory)return;c=!0;const w=o.messages()[0];if(!w){c=!1;return}const C=await ft(r,t,e,w.seq);C&&(o.apply({type:"history",conversationId:t,messages:C.messages,hasMore:C.hasMore}),i.render(o)),c=!1},y=i.getScrollEl();if(!y)return;let d=!1;setTimeout(()=>{d=!0},300);const f=()=>{d&&y.scrollTop<80&&o.hasMoreHistory&&!c&&u()};y.addEventListener("scroll",f,{passive:!0}),i.setScrollCleanup(()=>y.removeEventListener("scroll",f))}const xe=new WeakMap,Ue=new Map;function wt(n){return`relay-launcher::${n.profileId}::${n.subjectId??""}`}let ye=null;function qn(){if(ye&&ye.state!=="closed")return ye;try{return ye=new AudioContext,ye}catch{return null}}function gt(n){var Se,Ce,bt,mt,vt;xe.has(n.el)&&(xe.get(n.el).close(),xe.delete(n.el)),n.launcher&&((Se=Ue.get(wt(n)))==null||Se.close());const e=et();let t,o=!1;const i=n.token??n.userId??e,s=i!==e?e:void 0,{wsUrl:r,httpBase:p}=Oe(n.url,n.apiUrl);let c=new dn(i);const u=n.subjectId?`${i}::${n.subjectId}`:i,y=new yn(u);let d,f=!1,w=null,C=null,v=null,g=null;!n.launcher&&!n.el.style.height&&n.el.clientHeight===0&&(n.el.style.width=n.el.style.width||"100%",n.el.style.height="600px");for(const h of y.load())c.addOptimistic(h.clientMsgId,h.content);let I=null,E=null,L=0,T=!n.launcher;if(n.launcher){const x=(n.position??"bottom-right").includes("right");I=document.createElement("div"),I.style.cssText=`position:fixed;${x?"right:20px":"left:20px"};bottom:20px;z-index:9999;display:flex;flex-direction:column;align-items:${x?"flex-end":"flex-start"};gap:12px`;const S=document.createElement("div"),j=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(max-width: 479px)"):null,Le=R=>{n.el.classList.toggle("ocw-fs",R),S.style.cssText=R?["position:fixed","inset:0","width:100%","height:100dvh","border-radius:0","overflow:hidden","box-shadow:none","display:none","flex-direction:column","background:#fff","transition:opacity .18s","opacity:0","z-index:9998"].join(";"):["width:min(380px, calc(100vw - 40px))","height:min(600px, calc(100dvh - 108px))","border-radius:16px","overflow:hidden","box-shadow:0 8px 40px rgba(0,0,0,.18)","display:none","flex-direction:column","background:#fff","transform-origin:bottom "+(x?"right":"left"),"transition:opacity .18s,transform .18s","opacity:0","transform:scale(.95)"].join(";")};Le((j==null?void 0:j.matches)??!1);const Me=R=>Le(R.matches);j==null||j.addEventListener("change",Me),w=j,C=Me,n.el.style.cssText="width:100%;height:100%;overflow:hidden",S.append(n.el);const Xe='<svg viewBox="0 0 24 24" width="26" height="26" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',Ge='<svg viewBox="0 0 24 24" width="22" height="22" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/></svg>',V=document.createElement("button");V.type="button",V.style.cssText=["width:56px;height:56px;border-radius:50%",`background:${n.accent??"#4F63F5"}`,"color:#fff;border:none;cursor:pointer","box-shadow:0 4px 16px rgba(0,0,0,.25)","position:relative;flex:none","display:flex;align-items:center;justify-content:center","transition:transform .15s"].join(";"),V.onmouseenter=()=>{V.style.transform="scale(1.08)"},V.onmouseleave=()=>{V.style.transform="scale(1)"},E=document.createElement("span"),E.style.cssText="position:absolute;top:-4px;right:-4px;background:#ef4444;color:#fff;border-radius:50%;width:20px;height:20px;font-size:11px;font-weight:700;display:none;align-items:center;justify-content:center";const ze=()=>{V.innerHTML=T?Ge:Xe,V.setAttribute("aria-label",T?"Close chat":"Open chat"),V.setAttribute("aria-expanded",String(T)),V.append(E)};ze(),I.append(S,V),document.body.append(I);const Ye=`ocw-teaser-dismissed::${n.profileId}`,Ke=typeof n.launcherMessage=="string"?{title:n.launcherMessage}:n.launcherMessage;let K=null;const ei=()=>{try{return sessionStorage.getItem(Ye)==="1"}catch{return!1}},ti='<svg viewBox="0 0 24 24" width="15" height="15" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',kt=()=>{const R=Ke!=null&&Ke.title?Ke:c.launcherMessage??void 0;if(!(!!(R!=null&&R.title)&&!T&&!ei())){K&&(K.remove(),K=null);return}if(K)return;K=document.createElement("div"),K.setAttribute("role","button"),K.setAttribute("tabindex","0"),K.setAttribute("aria-label",R.title),K.style.cssText=["max-width:280px","background:#fff","border-radius:14px","box-shadow:0 6px 28px rgba(0,0,0,.16)","padding:14px 40px 14px 16px","position:relative","cursor:pointer","font-family:inherit",`align-self:${x?"flex-end":"flex-start"}`,"animation:ocw-teaser-in .22s ease-out"].join(";");const Ze=document.createElement("div");if(Ze.textContent=R.title,Ze.style.cssText="font-size:15px;font-weight:600;color:#111;line-height:1.35",K.append(Ze),R.subtitle){const ne=document.createElement("div");ne.style.cssText="display:flex;align-items:center;gap:6px;margin-top:6px;font-size:13px;color:#6b7280";const Qe=document.createElement("span");Qe.innerHTML=ti,Qe.style.cssText=`color:${n.accent??"#4F63F5"};display:inline-flex`;const Ct=document.createElement("span");Ct.textContent=R.subtitle,ne.append(Qe,Ct),K.append(ne)}const pe=document.createElement("button");pe.type="button",pe.setAttribute("aria-label","Dismiss"),pe.innerHTML='<svg viewBox="0 0 24 24" width="14" height="14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M18 6 6 18M6 6l12 12" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/></svg>',pe.style.cssText="position:absolute;top:8px;right:8px;width:24px;height:24px;border:none;border-radius:50%;background:#f3f4f6;color:#6b7280;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0",pe.addEventListener("click",ne=>{ne.stopPropagation();try{sessionStorage.setItem(Ye,"1")}catch{}K&&(K.remove(),K=null)}),K.append(pe);const St=()=>{T||(T=!0,Je(!0),ze(),L=0,E&&(E.style.display="none"),K&&(K.remove(),K=null))};K.addEventListener("click",St),K.addEventListener("keydown",ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),St())}),I.insertBefore(K,V)};if(!document.getElementById("ocw-teaser-style")){const R=document.createElement("style");R.id="ocw-teaser-style",R.textContent="@keyframes ocw-teaser-in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",document.head.append(R)}g=kt,kt();const Je=R=>{R?(S.style.display="flex",requestAnimationFrame(()=>{S.style.opacity="1",S.style.transform="scale(1)"})):(S.style.opacity="0",S.style.transform="scale(.95)",setTimeout(()=>{T||(S.style.display="none")},180))};V.addEventListener("click",()=>{if(T=!T,Je(T),ze(),T){L=0,E&&(E.style.display="none");try{sessionStorage.setItem(Ye,"1")}catch{}}g==null||g()}),v=R=>{R.key==="Escape"&&T&&(T=!1,Je(!1),ze())},document.addEventListener("keydown",v)}const H=()=>{T||(L++,E&&(E.textContent=String(L),E.style.display="flex"))},D=()=>{try{const h=qn();if(!h)return;h.state==="suspended"&&h.resume().catch(()=>{});const x=h.createOscillator(),S=h.createGain();x.connect(S),S.connect(h.destination),x.frequency.setValueAtTime(880,h.currentTime),x.frequency.exponentialRampToValueAtTime(440,h.currentTime+.15),S.gain.setValueAtTime(.3,h.currentTime),S.gain.exponentialRampToValueAtTime(.001,h.currentTime+.3),x.start(),x.stop(h.currentTime+.3)}catch{}},W=[],ee=h=>{for(;W.length;){const x=W.shift();y.add({clientMsgId:x.clientMsgId,content:x.content,ts:Date.now()}),k.send({type:"send",conversationId:h,clientMsgId:x.clientMsgId,content:x.content})}};let k;const $=new Un(`ocw-e2e-${n.profileId}`);let b=!1;const P=[],N=[];let ve=!1;const de=(h,x)=>{$.sealText(x).then(S=>{d&&k.send({type:"send",conversationId:d,clientMsgId:h,content:S})})},Be=(h,x,S)=>{$.sealText(x,S).then(j=>{d&&k.send({type:"send",conversationId:d,clientMsgId:h,content:j})})},m=()=>{for(;P.length;){const h=P.shift();de(h.clientMsgId,h.text)}for(;N.length;){const h=N.shift();de(h.clientMsgId,h.text)}},M=h=>{k.send({type:"fetchPrekey",targetUserId:h})},q=n.i18n??{},G=["ar","he","fa","ur"],F=typeof navigator<"u"?(navigator.language??"").slice(0,2).toLowerCase():"";G.includes(F)&&!n.el.dir&&(n.el.dir="rtl",n.el.style.fontFamily=n.el.style.fontFamily||"Tahoma,Arial,system-ui,sans-serif");const Y=new pn,U=`oc_prechat_${n.profileId}_${i.slice(-8)}`,z=new $n(n.el,i,{onSend(h){const x=`cm_${Math.random().toString(36).slice(2)}`,S={kind:"text",text:h};c.addOptimistic(x,S),z.render(c),c.e2e?$.ready?de(x,h):ve?N.push({clientMsgId:x,text:h}):(P.push({clientMsgId:x,text:h}),c.assignedAgentId&&M(c.assignedAgentId)):d?(y.add({clientMsgId:x,content:S,ts:Date.now()}),k.send({type:"send",conversationId:d,clientMsgId:x,content:S})):W.push({clientMsgId:x,content:S})},async onAttach(h){if(!d)return;const x=`${p}/upload?name=${encodeURIComponent(h.name)}`,S=`cm_${Math.random().toString(36).slice(2)}`;c.addOptimistic(S,{kind:"text",text:`📎 Uploading ${h.name}…`}),z.render(c);try{const j=await fetch(x,{method:"POST",headers:{"content-type":h.type,authorization:`Bearer ${i}`},body:h});if(!j.ok)throw new Error(`Upload failed: ${j.status}`);const{url:Le,name:Me,mime:Xe,size:Ge}=await j.json();k.send({type:"send",conversationId:d,clientMsgId:S,content:{kind:"attachment",url:Le,name:Me,mime:Xe,size:Ge}})}catch(j){c.addOptimistic(S,{kind:"text",text:`⚠️ Upload failed: ${j.message}`}),z.render(c)}},onInvoke(h,x){d&&k.send({type:"invoke",conversationId:d,actionId:h,clientInvokeId:`iv_${Math.random().toString(36).slice(2)}`,...x?{inputs:x}:{}})},onTyping(h,x){d&&k.send({type:"typing",conversationId:d,isTyping:h,...x?{preview:x}:{}})},onPreChat(h){try{localStorage.setItem(U,"1")}catch{}k.send({type:"open",profileId:n.profileId,...n.subjectId?{subjectId:n.subjectId}:{},userInfo:{...h.name?{name:h.name}:{},...h.email?{email:h.email}:{},...h.phone||h.topic?{meta:{...h.phone?{phone:h.phone}:{},...h.topic?{topic:h.topic}:{}}}:{}}});const x=h.callback?`📞 Call-back requested${h.phone?`: ${h.phone}`:""}${h.topic?` — ${h.topic}`:""}`:h.topic?`Topic: ${h.topic}`:"";x&&d&&!c.e2e&&k.send({type:"send",conversationId:d,clientMsgId:`pc_${Math.random().toString(36).slice(2,12)}`,content:{kind:"text",text:x}})},onDeflectQuery(h){if(o)return;clearTimeout(t);const x=h.trim();if(x.length<3){z.hideDeflection();return}t=setTimeout(()=>{fetch(`${p}/kb/search?profileId=${encodeURIComponent(n.profileId)}&q=${encodeURIComponent(x.slice(0,200))}`).then(S=>S.ok?S.json():{articles:[]}).then(S=>z.showDeflection(S.articles??[])).catch(()=>z.hideDeflection())},350)},onReadUpTo(h){d&&k.send({type:"read",conversationId:d,seq:h})},onLoadMore(){if(!d||!c.e2e)return;const h=c.messages()[0];h&&k.send({type:"history",conversationId:d,beforeSeq:h.seq,limit:20})},onEdit(h,x){d&&k.send({type:"edit",conversationId:d,messageId:h,content:{kind:"text",text:x}})},onDelete(h){d&&k.send({type:"delete",conversationId:d,messageId:h})},onReact(h,x,S){d&&k.send({type:"react",conversationId:d,messageId:h,emoji:x,remove:S})},onCsat(h){d&&fetch(`${p}/conversations/${d}/csat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({score:h})}).catch(()=>{})},onAnnotate(h){d&&k.send({type:"annotate",conversationId:d,stroke:h})},onAnnotateClear(){d&&k.send({type:"annotate_clear",conversationId:d})},...n.translateLang?{async onTranslate(h){try{const x=await fetch(`${p}/translate`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${i}`},body:JSON.stringify({text:h,targetLang:n.translateLang})});if(!x.ok)return null;const{translated:S}=await x.json();return S}catch{return null}}}:{},...n.onBack?{onBack:n.onBack}:{}},{...n.subject?{subject:n.subject}:{},...n.quickReplies?{quickReplies:n.quickReplies}:{},...n.accent?{accent:n.accent}:{},...(Ce=n.user)!=null&&Ce.name||(bt=n.user)!=null&&bt.avatar?{userInfo:{...n.user.name?{name:n.user.name}:{},...n.user.avatar?{avatar:n.user.avatar}:{}}}:{},i18n:q});try{localStorage.getItem(U)&&z.completePreChat()}catch{}const he=n.user&&(n.user.name||n.user.email||n.user.avatar||n.user.meta)?{...n.user.name?{name:n.user.name}:{},...n.user.email?{email:n.user.email}:{},...n.user.avatar?{avatar:n.user.avatar}:{},...n.user.meta?{meta:n.user.meta}:{}}:void 0,ke={type:"open",profileId:n.profileId,...n.kind==="direct"&&n.peerId?{kind:"direct",peerId:n.peerId}:n.subjectId?{subjectId:n.subjectId}:{},...s?{linkFrom:s}:{},...he?{userInfo:he}:{},...typeof location<"u"?{pageUrl:location.href}:{},...typeof document<"u"&&document.title?{pageTitle:document.title}:{},...(mt=n.subject)!=null&&mt.title?{subjectTitle:n.subject.title}:{},...(vt=n.subject)!=null&&vt.subtitle?{subjectMeta:n.subject.subtitle}:{}};k=new un({...n.refreshToken?{refreshToken:n.refreshToken}:{},url:r,token:i,open:ke,getCursor:()=>c.highestSeq(),onStatusChange:(h,x)=>z.setConnStatus(h,x),onFrame(h){if(Y.apply(h),h.type==="opened"){if(d=h.conversation.id,!f){f=!0;for(const x of y.load())k.send({type:"send",conversationId:d,clientMsgId:x.clientMsgId,content:x.content})}Hn(r,i,d,c,z,p),W.length&&ee(d)}if(h.type==="ack"&&y.remove(h.clientMsgId),h.type==="prekeyBundle"){h.bundle&&(ve=!0,$.x3dhSendTo(h.bundle).then(x=>{const S=[...P.splice(0),...N.splice(0)];for(const j of S)Be(j.clientMsgId,j.text,x);z.render(c)}));return}if(h.type==="message"&&c.e2e){const x=An(h.message.content);if(x&&!$.ready){$.x3dhReceiveFrom(x.x3dhIK,x.x3dhEK,x.x3dhSPK).then(async()=>{await $.openFrame(h),c.apply(h),z.render(c)});return}}if(h.type==="peerkey"){$.onPeerKey(h.key).then(()=>{m(),z.render(c)});return}(async()=>{if(c.e2e&&await $.openFrame(h),c.apply(h),h.type==="manifest"&&(g==null||g()),h.type==="message"&&h.message.senderId!==i&&!h.message.internal&&(H(),D()),c.e2e&&d&&!b){b=!0;const x=await $.initX3DH();k.send({type:"uploadPrekeys",...x});const S=await $.begin();k.send({type:"pubkey",conversationId:d,key:S})}z.render(c)})()}}),k.connect(),z.render(c);const ae=n.launcher?wt(n):null,te={close:()=>{o=!0,clearTimeout(t),k.close(),I==null||I.remove(),z.destroy(),Y.destroy(),w&&C&&w.removeEventListener("change",C),v&&(document.removeEventListener("keydown",v),v=null),xe.delete(n.el),ae&&Ue.get(ae)===te&&Ue.delete(ae)}};return xe.set(n.el,te),ae&&Ue.set(ae,te),te}const We="wss://api.paramms.com/ws";function Nn(n,e){const t=n.profileId??n.appId;if(!t)throw new Error("Relay: `profileId` is required (your chatroom id, e.g. 'p_...').");const o=n.subjectId??(n.listingId?`listing_${n.listingId}`:void 0),i=n.launcher??!0,s=n.contextTitle??n.listingTitle??n.subjectTitle,r=n.contextSubtitle??n.listingMeta??n.subjectMeta,p=n.contextStatus??n.listingStatus??n.subjectStatus,c=n.listingPrice??n.subjectPrice,u=s?{title:s,...r?{subtitle:r}:{},...c!=null?{tags:[`$${c.toLocaleString()}`]}:{},...p?{status:p}:{}}:void 0,y=n.subject??u,d=n.userName??n.name,f=n.userEmail??n.email,w=n.userAvatar??n.avatar,C=d||f||w?{...d?{name:d}:{},...f?{email:f}:{},...w?{avatar:w}:{}}:void 0,v=n.user??C,g=n.launcherMessage&&typeof n.launcherMessage=="object"?n.launcherMessage:n.launcherMessage?n.launcherSubtitle?{title:n.launcherMessage,subtitle:n.launcherSubtitle}:n.launcherMessage:void 0;return{el:e,url:n.url??We,profileId:t,...n.apiUrl?{apiUrl:n.apiUrl}:{},...o?{subjectId:o}:{},...n.token?{token:n.token}:{},...n.refreshToken?{refreshToken:n.refreshToken}:{},...n.userId?{userId:n.userId}:{},...y?{subject:y}:{},...v?{user:v}:{},...n.quickReplies?{quickReplies:n.quickReplies}:{},...n.i18n?{i18n:n.i18n}:{},...n.accent?{accent:n.accent}:{},...n.translateLang?{translateLang:n.translateLang}:{},...g?{launcherMessage:g}:{},...xt(n)&&!i?{onBack:()=>{be=!0,me=!1,Ae(re)}}:{},launcher:i,position:n.position??"bottom-right"}}let Z=null,_=null,se=!1,re={},be=!1,me=!1;function xt(n){return!!(n.inbox||n.inboxStart)}let Q=null;function Fn(n,e){const t=!e&&!!n.el;if(se&&!t&&(_.innerHTML="",_=null,se=!1),t){const o=typeof n.el=="string"?document.querySelector(n.el):n.el;o instanceof HTMLElement?(_&&_!==o&&!se&&_.remove(),_=o,se=!0):console.error(`[Relay] \`el\` ("${String(n.el)}") did not match any element — falling back to an auto-created host.`)}return(!_||!se&&!_.isConnected)&&(_=document.createElement("div"),_.id="relay-widget-root",document.body.appendChild(_),se=!1),!e&&n.height&&(_.style.height=n.height,_.style.width||(_.style.width="100%")),_}function Ae(n){try{const e=n.launcher??!0;Q==null||Q(),Q=null,Z==null||Z.close(),Z=null;const t=Fn(n,e);if(xt(n)&&!e&&be){On(n,t);return}Z=gt(Nn(n,t))}catch(e){console.error("[Relay]",e instanceof Error?e.message:e)}}async function On(n,e){const t=n.profileId??n.appId;if(!t&&!n.tenantId){console.error("[Relay] `inbox` requires `profileId` or `tenantId`.");return}e.innerHTML="";const o=document.createElement("div");o.style.cssText="position:relative;width:100%;height:100%;overflow:hidden;background:#fff";const i=document.createElement("div");i.style.cssText="position:absolute;inset:0";const s=document.createElement("div");s.style.cssText="position:absolute;inset:0;display:none";const r=document.createElement("button");r.type="button",r.setAttribute("aria-label","Close"),r.textContent="✕",r.style.cssText="position:absolute;top:8px;right:8px;z-index:20;width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.05);border:none;color:#1c1b1a;font-size:16px;line-height:1;cursor:pointer",r.onclick=()=>{be=!1,Ae(re)},o.append(i,s);const p=!me&&!!t;p&&o.append(r),e.appendChild(o);let c=null,u=null;Q=()=>{u==null||u.close(),c==null||c.close(),e.innerHTML=""};let y;try{({mountChatList:y}=await Promise.resolve().then(()=>Qn))}catch(f){console.error("[Relay] could not load the conversation list module.",f),i.isConnected&&(i.style.cssText+=";display:flex;align-items:center;justify-content:center;padding:16px;font:13px system-ui;color:#b91c1c;text-align:center",i.textContent="Could not load conversations.");return}if(!i.isConnected)return;const d=f=>{const w=f.profileId??t;if(!w){console.error("[Relay] conversation row has no chatroom; cannot open it.",f);return}r.style.display="none",u==null||u.close(),u=gt({el:s,url:n.url??We,...n.apiUrl?{apiUrl:n.apiUrl}:{},profileId:w,...f.kind==="direct"&&f.peerId?{kind:"direct",peerId:f.peerId}:f.subjectId?{subjectId:f.subjectId}:{},...n.token?{token:n.token}:{},...n.refreshToken?{refreshToken:n.refreshToken}:{},...n.userId?{userId:n.userId}:{},...n.userId||n.userName||n.userEmail||n.userAvatar?{user:{...n.userName?{name:n.userName}:{},...n.userEmail?{email:n.userEmail}:{},...n.userAvatar?{avatar:n.userAvatar}:{}}}:{},...f.subjectTitle?{subject:{title:f.subjectTitle,...f.subjectMeta?{subtitle:f.subjectMeta}:{}}}:{},...n.accent?{accent:n.accent}:{},launcher:!1,onBack:()=>{u==null||u.close(),u=null,s.style.display="none",i.style.display="",r.style.display="",c==null||c.refresh()}}),i.style.display="none",s.style.display=""};c=y({el:i,url:n.url??We,...n.apiUrl?{apiUrl:n.apiUrl}:{},...t?{profileId:t}:{},...n.tenantId?{tenantId:n.tenantId}:{},scope:n.inboxScope??"tenant",...p?{reserveCloseSpace:!0}:{},onSelect:d,onNewChat:()=>{const f=t??(c==null?void 0:c.defaultProfileId());f&&d({id:"__new__",profileId:f,state:"open",updatedAt:Date.now()})},...n.token?{token:n.token}:{},...n.userId?{userId:n.userId}:{},...n.accent?{accent:n.accent}:{}})}function yt(n){me=!!(n.inboxStart&&!(n.launcher??!0)),be=me,re={...n},Ae(re)}function Wn(n){re={...re,...n},Ae(re)}function Vn(){Q==null||Q(),Q=null,Z==null||Z.close(),Z=null,_&&!se&&_.remove(),_=null,se=!1,be=!1,me=!1,re={}}function Ve(n,e){switch(n){case"boot":yt(e??{});break;case"update":case"identify":Wn(e??{});break;case"shutdown":Vn();break;default:console.warn("[Relay] unknown command:",n)}}function Xn(){if(typeof document>"u")return null;const n=document.querySelector("script[data-relay-app]")??document.querySelector("script[data-relay-profile-id]")??document.querySelector("script[data-relay-tenant-id]"),e=n==null?void 0:n.dataset,t=(e==null?void 0:e.relayApp)??(e==null?void 0:e.relayProfileId),o=e==null?void 0:e.relayTenantId;if(!t&&!o)return null;const i=t?{profileId:t}:{};o&&(i.tenantId=o),e.relayUser&&(i.userId=e.relayUser),e.relayToken&&(i.token=e.relayToken),e.relayListing&&(i.listingId=e.relayListing),e.relayAccent&&(i.accent=e.relayAccent),e.relayUrl&&(i.url=e.relayUrl);const s=e.relayPosition;(s==="bottom-left"||s==="bottom-right")&&(i.position=s),e.relayLauncherMessage&&(i.launcherMessage=e.relayLauncherMessage),e.relayLauncherSubtitle&&(i.launcherSubtitle=e.relayLauncherSubtitle),e.relayLauncher==="false"&&(i.launcher=!1),e.relayUserName&&(i.userName=e.relayUserName),e.relayUserEmail&&(i.userEmail=e.relayUserEmail),e.relayUserAvatar&&(i.userAvatar=e.relayUserAvatar),e.relayContextTitle&&(i.contextTitle=e.relayContextTitle),e.relayContextSubtitle&&(i.contextSubtitle=e.relayContextSubtitle),e.relayContextStatus&&(i.contextStatus=e.relayContextStatus),e.relayListingTitle&&(i.listingTitle=e.relayListingTitle),e.relayListingMeta&&(i.listingMeta=e.relayListingMeta),e.relayListingPrice&&(i.listingPrice=Number(e.relayListingPrice)),e.relayListingStatus&&(i.listingStatus=e.relayListingStatus),e.relayTarget&&(i.el=e.relayTarget),e.relayHeight&&(i.height=e.relayHeight),e.relayInbox==="true"&&(i.inbox=!0),e.relayInbox==="false"&&(i.inbox=!1),e.relayInboxStart==="true"&&(i.inboxStart=!0),e.relayInboxStart==="false"&&(i.inboxStart=!1);const r=e.relayInboxScope;return(r==="tenant"||r==="profile")&&(i.inboxScope=r),i}if(typeof window<"u"){const n=window,e=n.Relay&&n.Relay.q?n.Relay.q:[];n.Relay=Ve;let t=!1;for(const o of e){const[i,s]=o;i==="boot"&&(t=!0),Ve(i,s)}if(!t){const o=n.relaySettings??Xn();o&&yt(o)}}function Gn(n){const e=Math.floor((Date.now()-n)/1e3);if(e<60)return"just now";if(e<3600)return`${Math.floor(e/60)}m`;if(e<86400)return`${Math.floor(e/3600)}h`;const t=Math.floor(e/86400);if(t<=7)return`${t}d`;try{return new Date(n).toLocaleDateString(void 0,{month:"short",day:"numeric"})}catch{return`${t}d`}}const Yn='<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="currentColor" fill-opacity="0.12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function A(n,e,t){const o=document.createElement(n);return e&&(o.className=e),t!==void 0&&(o.textContent=t),o}const Jn=`
|
|
190
190
|
.ocl { --ocl-accent:#f5713c; --ocl-bg:#f3efe9; --ocl-card:#fff; --ocl-line:#ececec; --ocl-ink:#1c1b1a; --ocl-mut:#9b9690;
|
|
191
191
|
display:flex; flex-direction:column; height:100%; background:var(--ocl-bg);
|
|
192
192
|
font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif; color:var(--ocl-ink); overflow:hidden; }
|
|
@@ -218,6 +218,10 @@ var RelayEmbed=function(J){"use strict";var ni=Object.defineProperty;var ii=(J,X
|
|
|
218
218
|
.ocl-spinner { padding:24px; text-align:center; color:var(--ocl-mut); font-size:13px; }
|
|
219
219
|
.ocl-compose { border:none; background:var(--ocl-bg); color:var(--ocl-ink); width:32px; height:32px; border-radius:50%; font-size:15px; cursor:pointer; }
|
|
220
220
|
.ocl-compose:hover { background:var(--ocl-line); }
|
|
221
|
+
/* When the HOST overlays a ✕ (ChatApp's onClose / embed's inbox stack), it is
|
|
222
|
+
absolutely positioned at top-right and used to land straight on top of the ✎
|
|
223
|
+
compose button. Reserve the space instead of stacking them. */
|
|
224
|
+
.ocl-has-close .ocl-head { padding-right:52px; }
|
|
221
225
|
.ocl-start { margin-top:12px; border:none; background:var(--ocl-accent); color:#fff; border-radius:20px; padding:8px 18px; font:inherit; font-size:13px; font-weight:600; cursor:pointer; }
|
|
222
226
|
/* Compact sizing keyed on the LIST'S OWN width (ResizeObserver toggles
|
|
223
227
|
* .ocl-compact below 400px) — covers phones and narrow desktop embeds alike.
|
|
@@ -225,5 +229,5 @@ var RelayEmbed=function(J){"use strict";var ni=Object.defineProperty;var ii=(J,X
|
|
|
225
229
|
.ocl-compact .ocl-row { padding:13px 14px; }
|
|
226
230
|
.ocl-compact .ocl-search { font-size:16px; }
|
|
227
231
|
.ocl-compact .ocl-compose { width:36px; height:36px; }
|
|
228
|
-
`;function Zn(n){const e=n.token??n.userId??et(),{httpBase:t,wsUrl:o}=Oe(n.url,n.apiUrl),i=n.i18n??{},s=n.accent??"#4F63F5";if(!document.getElementById("ocl-styles")){const m=document.createElement("style");m.id="ocl-styles",m.textContent=Jn,document.head.append(m)}const r=A("div","ocl");r.style.setProperty("--ocl-accent",s);const p=A("div","ocl-head"),
|
|
232
|
+
`;function Zn(n){const e=n.token??n.userId??et(),{httpBase:t,wsUrl:o}=Oe(n.url,n.apiUrl),i=n.i18n??{},s=n.accent??"#4F63F5";if(!document.getElementById("ocl-styles")){const m=document.createElement("style");m.id="ocl-styles",m.textContent=Jn,document.head.append(m)}const r=A("div","ocl");r.style.setProperty("--ocl-accent",s),n.reserveCloseSpace&&r.classList.add("ocl-has-close");const p=A("div","ocl-head"),c=A("span","ocl-title");if(c.setAttribute("role","img"),c.setAttribute("aria-label",i.title??"Messages"),c.innerHTML=Yn,p.append(c),n.onNewChat){const m=A("button","ocl-compose","✎");m.title=i.newChat??"New conversation",m.addEventListener("click",()=>n.onNewChat()),p.append(m)}const u=A("div","ocl-search-wrap"),y=A("input","ocl-search");y.placeholder=i.search??"🔍 Search",y.type="search",u.append(y);const d=A("div","ocl-body");d.append(A("div","ocl-spinner","Loading…")),r.append(p,u,d),n.el.replaceChildren(r);const f=m=>{r.classList.toggle("ocl-compact",m>0&&m<400)};f(r.clientWidth);let w=null;if(typeof ResizeObserver<"u"&&(w=new ResizeObserver(m=>{var M;return f(((M=m[0])==null?void 0:M.contentRect.width)??r.clientWidth)}),w.observe(r)),!n.profileId&&!n.tenantId)throw new Error("[relay chatlist] provide profileId or tenantId");let C;const v=`ocl_seen_${n.profileId??`t_${n.tenantId}`}_${(n.userId??e).slice(-8)}`;let g={};try{g=JSON.parse(localStorage.getItem(v)??"{}")}catch{}const I=()=>{try{localStorage.setItem(v,JSON.stringify(g))}catch{}};let E=[],L=!1;const T=async()=>{const m=n.profileId?`profileId=${encodeURIComponent(n.profileId)}${n.scope==="tenant"?"&scope=tenant":""}`:`tenantId=${encodeURIComponent(n.tenantId)}`,M=`${t}/conversations/mine?${m}`,q={authorization:`Bearer ${e}`};let G;try{G=await fetch(M,{headers:q})}catch{G=await fetch(M,{headers:q})}if(!G.ok)return[];const F=await G.json();return F.defaultProfileId&&(C=F.defaultProfileId),(F.conversations??[]).sort((Y,U)=>U.updatedAt-Y.updatedAt)},H=(m,M)=>{if(L)return;const q=M?m.filter(U=>D(U).toLowerCase().includes(M)||(U.lastMessage??"").toLowerCase().includes(M)):m;if(d.replaceChildren(),!q.length){const U=A("div","ocl-empty",M?"No results.":i.empty??"No conversations yet.");if(!M&&n.onNewChat){U.append(A("br"));const z=A("button","ocl-start",i.newChat??"Start a conversation");z.addEventListener("click",()=>n.onNewChat()),U.append(z)}d.append(U);return}const G=U=>(U.lastSeq??0)>(g[U.id]??0),F=q.filter(G),Y=q.filter(U=>!G(U));if(F.length){d.append(A("div","ocl-section",`${i.unread??"Unread"} (${F.length})`));for(const U of F)d.append(W(U,G(U)))}if(Y.length){d.append(A("div","ocl-section",F.length?i.all??"All conversations":""));for(const U of Y)d.append(W(U,!1))}},D=m=>m.subjectTitle??(m.kind==="direct"?m.peerId??"Direct message":"General enquiry"),W=(m,M)=>{var Se;const q=D(m),G=(((Se=q.match(new RegExp("\\p{L}","u")))==null?void 0:Se[0])??q.trim()[0]??"?").toUpperCase(),F=m.lastSeq??0,Y=M?Math.max(1,F-(g[m.id]??0)):0,U=A("button",`ocl-row${M?" unread":""}`),z=A("div","ocl-av",G),he=A("div","ocl-dot");m.state==="open"?he.classList.add("open"):m.state==="awaiting_staff"&&he.classList.add("waiting"),z.append(he),U.append(z);const ke=A("div","ocl-info");ke.append(A("div","ocl-name",q));const ae={open:"Open",awaiting_staff:"Waiting for reply…",resolved:"Resolved ✓",closed:"Closed"};ke.append(A("div","ocl-preview",m.lastMessage??ae[m.state]??m.state)),U.append(ke);const te=A("div","ocl-right");return te.append(A("div","ocl-time",Gn(m.updatedAt))),Y>0&&te.append(A("div","ocl-badge",String(Y>99?"99+":Y))),U.append(te),U.addEventListener("click",()=>{var Ce;F>0&&(g[m.id]=F,I()),U.classList.remove("unread"),(Ce=te.querySelector(".ocl-badge"))==null||Ce.remove(),n.onSelect(m)}),U},ee=()=>{L||T().then(m=>{L||(E=m,H(m,y.value.trim().toLowerCase()))}).catch(m=>{if(L)return;console.error(`[chat-widget] failed to load conversations from ${t}/conversations/mine — check the apiUrl/CORS config.`,m);const M=A("div","ocl-empty",i.error??"Could not load conversations.");M.append(A("br"));const q=A("button","ocl-retry",i.retry??"Retry");q.addEventListener("click",()=>{d.replaceChildren(A("div","ocl-spinner","Loading…")),ee()}),M.append(q),d.replaceChildren(M)})};y.addEventListener("input",()=>H(E,y.value.trim().toLowerCase())),ee();let k=null,$,b,P=0,N=!1;const ve=()=>{b||(b=setTimeout(()=>{b=void 0,ee()},300))},de=()=>{if(!L){try{k=new WebSocket(o)}catch{Be();return}k.binaryType="arraybuffer",k.onopen=()=>{P=0,k.send(qe({type:"auth",token:e})),k.send(qe({type:"subscribe_inbox"})),N&&ve(),N=!0},k.onmessage=m=>{const M=rt(new Uint8Array(m.data));M&&M.type==="inbox_event"&&ve()},k.onclose=()=>{k=null,Be()},k.onerror=()=>{try{k==null||k.close()}catch{}}}},Be=()=>{if(L||$)return;const m=Math.min(15e3,500*2**P++)+Math.random()*250;$=setTimeout(()=>{$=void 0,de()},m)};return de(),{refresh:ee,close(){L=!0,$&&clearTimeout($),b&&clearTimeout(b),w==null||w.disconnect(),w=null;try{k==null||k.close()}catch{}k=null,n.el.replaceChildren()},defaultProfileId(){return n.profileId??C}}}const Qn=Object.freeze(Object.defineProperty({__proto__:null,mountChatList:Zn},Symbol.toStringTag,{value:"Module"}));return J.Relay=Ve,Object.defineProperty(J,Symbol.toStringTag,{value:"Module"}),J}({});
|
|
229
233
|
//# sourceMappingURL=embed.js.map
|