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