@paramms/chat-widget 1.6.2 → 1.7.0

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