holostaff-widget 3.0.4 → 3.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{CanvasRenderer-DtJMGjQ-.js → CanvasRenderer-CNPW48Qw.js} +5 -5
- package/dist/{CanvasRenderer-DtJMGjQ-.js.map → CanvasRenderer-CNPW48Qw.js.map} +1 -1
- package/dist/{Filter-BZ0p_cLc.js → Filter-AM8DWlqL.js} +2 -2
- package/dist/{Filter-BZ0p_cLc.js.map → Filter-AM8DWlqL.js.map} +1 -1
- package/dist/{GpuStencilModesToPixi-BhdxrQzF.js → GpuStencilModesToPixi-BR9JEV9O.js} +3 -3
- package/dist/{GpuStencilModesToPixi-BhdxrQzF.js.map → GpuStencilModesToPixi-BR9JEV9O.js.map} +1 -1
- package/dist/{RenderTargetSystem-Cbru8Ci0.js → RenderTargetSystem-BpbroGT3.js} +3 -3
- package/dist/{RenderTargetSystem-Cbru8Ci0.js.map → RenderTargetSystem-BpbroGT3.js.map} +1 -1
- package/dist/{WebGLRenderer--845IaSu.js → WebGLRenderer-C8_IJOQx.js} +5 -5
- package/dist/{WebGLRenderer--845IaSu.js.map → WebGLRenderer-C8_IJOQx.js.map} +1 -1
- package/dist/{WebGPURenderer-DBDzoMAw.js → WebGPURenderer-C9gHL4Xl.js} +6 -6
- package/dist/{WebGPURenderer-DBDzoMAw.js.map → WebGPURenderer-C9gHL4Xl.js.map} +1 -1
- package/dist/{browserAll-CIOBMh08.js → browserAll-BHbeidFW.js} +3 -3
- package/dist/{browserAll-CIOBMh08.js.map → browserAll-BHbeidFW.js.map} +1 -1
- package/dist/{getTextureBatchBindGroup-DCKtteRk.js → getTextureBatchBindGroup-CNV1rYho.js} +3 -3
- package/dist/{getTextureBatchBindGroup-DCKtteRk.js.map → getTextureBatchBindGroup-CNV1rYho.js.map} +1 -1
- package/dist/hs-widget.es.js +1 -1
- package/dist/hs-widget.umd.js +5 -5
- package/dist/hs-widget.umd.js.map +1 -1
- package/dist/{index-BbQvHSpa.js → index-D4TjHcc0.js} +33 -12
- package/dist/index-D4TjHcc0.js.map +1 -0
- package/dist/{webworkerAll-EB5JX-2r.js → webworkerAll-Cqn374qg.js} +3 -3
- package/dist/{webworkerAll-EB5JX-2r.js.map → webworkerAll-Cqn374qg.js.map} +1 -1
- package/package.json +1 -1
- package/dist/index-BbQvHSpa.js.map +0 -1
package/dist/hs-widget.umd.js
CHANGED
|
@@ -894,7 +894,7 @@ fn mainFragment(
|
|
|
894
894
|
fn fragmentMain(@location(0) texCoord : vec2<f32>) -> @location(0) vec4<f32> {
|
|
895
895
|
return textureSample(img, imgSampler, texCoord);
|
|
896
896
|
}
|
|
897
|
-
`})),t=this.device.createRenderPipeline({layout:"auto",vertex:{module:this.mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this.mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:e}]}}),this.pipelines[e]=t),t}generateMipmap(e){const t=this._getMipmapPipeline(e.format);if(e.dimension==="3d"||e.dimension==="1d")throw new Error("Generating mipmaps for non-2d textures is currently unsupported!");let i=e;const r=e.depthOrArrayLayers||1,n=e.usage&GPUTextureUsage.RENDER_ATTACHMENT;if(!n){const l={size:{width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r},format:e.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:e.mipLevelCount-1};i=this.device.createTexture(l)}const o=this.device.createCommandEncoder({}),a=t.getBindGroupLayout(0);for(let l=0;l<r;++l){let c=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),h=n?1:0;for(let u=1;u<e.mipLevelCount;++u){const f=i.createView({baseMipLevel:h++,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),d=o.beginRenderPass({colorAttachments:[{view:f,storeOp:"store",loadOp:"clear",clearValue:{r:0,g:0,b:0,a:0}}]}),g=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.sampler},{binding:1,resource:c}]});d.setPipeline(t),d.setBindGroup(0,g),d.draw(3,1,0,0),d.end(),c=f}}if(!n){const l={width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r};for(let c=1;c<e.mipLevelCount;++c)o.copyTextureToTexture({texture:i,mipLevel:c-1},{texture:e,mipLevel:c},l),l.width=Math.ceil(l.width/2),l.height=Math.ceil(l.height/2)}return this.device.queue.submit([o.finish()]),n||i.destroy(),e}}class nx{constructor(e){this.textureView=null,this.gpuTexture=e}destroy(){this.gpuTexture.destroy(),this.textureView=null,this.gpuTexture=null}}class Eu{constructor(e){this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._renderer=e,e.gc.addCollection(this,"_bindGroupHash","hash"),this._managedTextures=new kt({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"gpuTextureSource"});const t={image:Su,buffer:Qb,video:sx,compressed:tx};this._uploads={...t,cube:ix(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gpu=e}initSource(e){var t;return((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuTexture)||this._initSource(e)}_initSource(e){if(e.autoGenerateMipmaps){const c=Math.max(e.pixelWidth,e.pixelHeight);e.mipLevelCount=Math.floor(Math.log2(c))+1}let t=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST;e.uploadMethodId!=="compressed"&&(t|=GPUTextureUsage.RENDER_ATTACHMENT,t|=GPUTextureUsage.COPY_SRC);const i=vu[e.format]||{blockWidth:1,blockHeight:1},r=Math.ceil(e.pixelWidth/i.blockWidth)*i.blockWidth,n=Math.ceil(e.pixelHeight/i.blockHeight)*i.blockHeight,o={label:e.label,size:{width:r,height:n,depthOrArrayLayers:e.arrayLayerCount},format:e.format,sampleCount:e.sampleCount,mipLevelCount:e.mipLevelCount,dimension:e.dimension,usage:t},a=this._gpu.device.createTexture(o);return e._gpuData[this._renderer.uid]=new nx(a),this._managedTextures.add(e)&&(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceResize,this),e.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(e),a}onSourceUpdate(e){const t=this.getGpuSource(e);t&&(this._uploads[e.uploadMethodId]&&this._uploads[e.uploadMethodId].upload(e,t,this._gpu),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e))}onUpdateMipmaps(e){this._mipmapGenerator||(this._mipmapGenerator=new rx(this._gpu.device));const t=this.getGpuSource(e);this._mipmapGenerator.generateMipmap(t)}onSourceUnload(e){e.off("update",this.onSourceUpdate,this),e.off("resize",this.onSourceResize,this),e.off("updateMipmaps",this.onUpdateMipmaps,this)}onSourceResize(e){e._gcLastUsed=this._renderer.gc.now;const t=e._gpuData[this._renderer.uid],i=t==null?void 0:t.gpuTexture;i?(i.width!==e.pixelWidth||i.height!==e.pixelHeight)&&(t.destroy(),this._bindGroupHash[e.uid]=null,e._gpuData[this._renderer.uid]=null,this.initSource(e)):this.initSource(e)}_initSampler(e){return this._gpuSamplers[e._resourceId]=this._gpu.device.createSampler(e),this._gpuSamplers[e._resourceId]}getGpuSampler(e){return this._gpuSamplers[e._resourceId]||this._initSampler(e)}getGpuSource(e){var t;return e._gcLastUsed=this._renderer.gc.now,((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuTexture)||this.initSource(e)}getTextureBindGroup(e){return this._bindGroupHash[e.uid]||this._createTextureBindGroup(e)}_createTextureBindGroup(e){const t=e.source;return this._bindGroupHash[e.uid]=new Gt({0:t,1:t.style,2:new ht({uTextureMatrix:{type:"mat3x3<f32>",value:e.textureMatrix.mapCoord}})}),this._bindGroupHash[e.uid]}getTextureView(e){const t=e.source;t._gcLastUsed=this._renderer.gc.now;let i=t._gpuData[this._renderer.uid];return i||(this.initSource(t),i=t._gpuData[this._renderer.uid]),i.textureView||(i.textureView=i.gpuTexture.createView({dimension:t.viewDimension})),i.textureView}generateCanvas(e){const t=this._renderer,i=t.gpu.device.createCommandEncoder(),r=pe.get().createCanvas();r.width=e.source.pixelWidth,r.height=e.source.pixelHeight;const n=r.getContext("webgpu");return n.configure({device:t.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:pe.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:"premultiplied"}),i.copyTextureToTexture({texture:t.texture.getGpuSource(e.source),origin:{x:0,y:0}},{texture:n.getCurrentTexture()},{width:r.width,height:r.height}),t.gpu.device.queue.submit([i.finish()]),r}getPixels(e){const t=this.generateCanvas(e),i=so.getOptimalCanvasAndContext(t.width,t.height),r=i.context;r.drawImage(t,0,0);const{width:n,height:o}=t,a=r.getImageData(0,0,n,o),l=new Uint8ClampedArray(a.data.buffer);return so.returnCanvasAndContext(i),{pixels:l,width:n,height:o}}destroy(){this._managedTextures.destroy();for(const e of Object.keys(this._bindGroupHash)){const t=Number(e),i=this._bindGroupHash[t];i==null||i.destroy()}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._gpuSamplers=null,this._bindGroupHash=null}}Eu.extension={type:[A.WebGPUSystem],name:"texture"};class Tu{constructor(){this._maxTextures=0}contextChange(e){const t=new ht({uTransformMatrix:{value:new H,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}});this._maxTextures=e.limits.maxBatchableTextures;const i=Gn({name:"graphics",bits:[vc,Sc(this._maxTextures),_y,Vn]});this.shader=new Mt({gpuProgram:i,resources:{localUniforms:t}})}execute(e,t){const i=t.context,r=i.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(i),c=n.encoder;c.setGeometry(a.geometry,r.gpuProgram);const h=n.globalUniforms.bindGroup;c.setBindGroup(0,h,r.gpuProgram);const u=n.renderPipes.uniformBatch.getUniformBindGroup(r.resources.localUniforms,!0);c.setBindGroup(2,u,r.gpuProgram);const f=l.instructions;let d=null;for(let g=0;g<l.instructionSize;g++){const _=f[g];if(_.topology!==d&&(d=_.topology,c.setPipelineFromGeometryProgramAndState(a.geometry,r.gpuProgram,e.state,_.topology)),r.groups[1]=_.bindGroup,!_.gpuBindGroup){const b=_.textures;_.bindGroup=Nn(b.textures,b.count,this._maxTextures),_.gpuBindGroup=n.bindGroup.getBindGroup(_.bindGroup,r.gpuProgram,1)}c.setBindGroup(1,_.bindGroup,r.gpuProgram),c.renderPassEncoder.drawIndexed(_.size,1,_.start)}}destroy(){this.shader.destroy(!0),this.shader=null}}Tu.extension={type:[A.WebGPUPipesAdaptor],name:"graphics"};class Au{init(){const e=Gn({name:"mesh",bits:[ur,vy,Vn]});this._shader=new Mt({gpuProgram:e,resources:{uTexture:j.EMPTY._source,uSampler:j.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new H}}}})}execute(e,t){const i=e.renderer;let r=t._shader;if(!r)r=this._shader,r.groups[2]=i.texture.getTextureBindGroup(t.texture);else if(!r.gpuProgram){se("Mesh shader has no gpuProgram",t.shader);return}const n=r.gpuProgram;if(n.autoAssignGlobalUniforms&&(r.groups[0]=i.globalUniforms.bindGroup),n.autoAssignLocalUniforms){const o=e.localUniforms;r.groups[1]=i.renderPipes.uniformBatch.getUniformBindGroup(o,!0)}i.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}Au.extension={type:[A.WebGPUPipesAdaptor],name:"mesh"};const ox=[...Ao,qr,fu,Oo,pu,uu,Eu,yu,bu,xu,_u,du,mu,hu],ax=[...Fh,gu],lx=[yh,Au,Tu],wu=[],Iu=[],Ru=[];Q.handleByNamedList(A.WebGPUSystem,wu),Q.handleByNamedList(A.WebGPUPipes,Iu),Q.handleByNamedList(A.WebGPUPipesAdaptor,Ru),Q.add(...ox,...ax,...lx);class cx extends vi{constructor(){const e={name:"webgpu",type:bt.WEBGPU,systems:wu,renderPipes:Iu,renderPipeAdaptors:Ru};super(e)}}const hx=Object.freeze(Object.defineProperty({__proto__:null,WebGPURenderer:cx},Symbol.toStringTag,{value:"Module"}));Q.add(Rm,Mm);const Bi=480,xs=480;class ux{constructor(){this.container=null,this.resizeObserver=null,this.mode="floating",this.targetEl=null,this.app=new nc}async init(e="floating",t){this.mode=e,e==="inline"&&t&&(this.targetEl=document.querySelector(t),this.targetEl||(console.warn(`[HolostaffWidget] Container "${t}" not found, falling back to floating mode`),this.mode="floating")),await this.app.init({width:Bi,height:xs,backgroundAlpha:0,antialias:!0,resolution:window.devicePixelRatio||1,autoDensity:!0,preference:"webgl"}),this.container=document.createElement("div"),this.container.id="holostaff-widget-root",this.mode==="inline"&&this.targetEl?(Object.assign(this.container.style,{position:"relative",width:"100%",height:"100%",overflow:"visible",pointerEvents:"none"}),this.targetEl.style.position="relative",this.targetEl.style.cursor="pointer",this.targetEl.appendChild(this.container)):(Object.assign(this.container.style,{position:"fixed",bottom:"0",left:"50%",transform:"translateX(-50%)",width:`${Bi}px`,height:`${xs}px`,zIndex:"2147483646",pointerEvents:"none",overflow:"visible"}),document.body.appendChild(this.container));const i=this.app.canvas;return Object.assign(i.style,{width:"100%",height:"100%",display:"block",pointerEvents:"auto"}),this.container.appendChild(i),this.setupResize(),i}setupResize(){const e=()=>{if(this.mode==="inline"&&this.targetEl){const t=this.targetEl.getBoundingClientRect();this.container&&(this.container.style.width=`${t.width}px`,this.container.style.height=`${t.height}px`)}else{const t=window.innerWidth,i=Math.min(Bi,t),r=i/Bi,n=xs*r;this.container&&(this.container.style.width=`${i}px`,this.container.style.height=`${n}px`)}this.app.renderer.resize(Bi,xs)};window.addEventListener("resize",e),this.mode==="inline"&&this.targetEl&&(this.resizeObserver=new ResizeObserver(e),this.resizeObserver.observe(this.targetEl)),e()}get isInline(){return this.mode==="inline"&&this.targetEl!==null}get inlineTarget(){return this.targetEl}get rootElement(){return this.container}get stageWidth(){return Bi}get stageHeight(){return xs}getInlineRect(){var e;return((e=this.targetEl)==null?void 0:e.getBoundingClientRect())??null}destroy(){var e,t;window.removeEventListener("resize",this.setupResize),(e=this.resizeObserver)==null||e.disconnect(),(t=this.container)==null||t.remove(),this.app.destroy(!0)}}function dx(){var s,e;return((e=(s=globalThis.matchMedia)==null?void 0:s.call(globalThis,"(prefers-reduced-motion: reduce)"))==null?void 0:e.matches)??!1}const vs={easeOutCubic:s=>1-Math.pow(1-s,3),easeInCubic:s=>s*s*s,easeOutBack:s=>1+2.70158*Math.pow(s-1,3)+1.70158*Math.pow(s-1,2),easeInOutSine:s=>-(Math.cos(Math.PI*s)-1)/2};function gr(s){const{target:e,props:t,duration:i,easing:r=vs.easeOutCubic,delay:n=0,onComplete:o,ticker:a}=s;if(dx()){for(const f of Object.keys(t))e[f]=t[f];return o==null||o(),()=>{}}const l={};for(const f of Object.keys(t))l[f]=e[f];let c=-n,h=!1;const u=f=>{if(h||(c+=f.deltaMS,c<0))return;const d=Math.min(c/i,1),g=r(d);for(const _ of Object.keys(t))e[_]=l[_]+(t[_]-l[_])*g;d>=1&&(a.remove(u),o==null||o())};return a.add(u),()=>{h=!0,a.remove(u)}}const Cs=200,Vt=Cs*(480/854),Mu=280;class fx{constructor(e,t){this.idleVideoEl=null,this.idleGroup=null,this.liveSprite=null,this.cancelGlow=null,this.cancelEntrance=null,this.visible=!1,this.widgetRoot=null,this.stageWidth=e,this.stageHeight=t,this.container=new Ve,this.container.visible=!1,this.container.x=e/2,this.container.y=t+Vt}async loadIdleVideo(e,t){this.widgetRoot=t,this.idleVideoEl=document.createElement("video"),this.idleVideoEl.src=e,this.idleVideoEl.loop=!0,this.idleVideoEl.muted=!0,this.idleVideoEl.playsInline=!0,this.idleVideoEl.crossOrigin="anonymous",Object.assign(this.idleVideoEl.style,{position:"absolute",bottom:"10px",left:"50%",transform:"translateX(-50%) translateY(100%)",width:`${Cs}px`,height:"auto",pointerEvents:"none",zIndex:"0",transition:"none"}),t.insertBefore(this.idleVideoEl,t.firstChild),await this.idleVideoEl.play(),this.idleGroup=new Ve,this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+Vt}async loadIdleImage(e){const t=j.from(e),i=new Ft(t);i.width=Cs,i.height=Vt,i.anchor.set(.5,1),this.idleGroup=new Ve,this.idleGroup.addChild(i),this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+Vt}slideIn(e){if(this.visible)return;this.visible=!0;const t=this.stageHeight-10;this.container.alpha=1,this.container.visible=!0,this.container.y=this.stageHeight+Vt,this.cancelEntrance=gr({target:this.container,props:{y:t},duration:700,easing:vs.easeOutBack,ticker:e}),this.idleVideoEl&&(this.idleVideoEl.style.transition="transform 0.7s cubic-bezier(0.34, 1.56, 0.64, 1)",this.idleVideoEl.style.transform="translateX(-50%) translateY(0)")}slideOut(e){var t;this.visible&&(this.visible=!1,(t=this.cancelGlow)==null||t.call(this),this.cancelGlow=null,gr({target:this.container,props:{y:this.stageHeight+Vt},duration:450,easing:vs.easeInCubic,ticker:e,onComplete:()=>{this.container.visible=!1}}),this.idleVideoEl&&(this.idleVideoEl.style.transition="transform 0.45s cubic-bezier(0.32, 0, 0.67, 0)",this.idleVideoEl.style.transform="translateX(-50%) translateY(100%)"))}get isVisible(){return this.visible}setInteractive(e){this.container.eventMode="static",this.container.cursor="pointer",this.container.hitArea=new Se(-Cs/2,-Vt,Cs,Vt),this.container.on("pointertap",e),this.idleVideoEl&&(this.idleVideoEl.style.pointerEvents="auto",this.idleVideoEl.style.cursor="pointer",this.idleVideoEl.addEventListener("click",e))}setLiveVideo(e,t){const i=()=>{var l;const r=j.from(e);this.liveSprite=new Ft(r);const n=e.videoWidth||1,o=e.videoHeight||1,a=Mu/n;this.liveSprite.width=Mu,this.liveSprite.height=o*a,this.liveSprite.anchor.set(.5,1),this.liveSprite.alpha=0,this.container.addChild(this.liveSprite),this.idleVideoEl&&(this.idleVideoEl.style.display="none"),this.idleGroup&&(this.idleGroup.visible=!1),(l=this.cancelGlow)==null||l.call(this),this.cancelGlow=null,gr({target:this.liveSprite,props:{alpha:1},duration:500,easing:vs.easeInOutSine,ticker:t})};if(e.videoWidth>0&&e.videoHeight>0)i();else{const r=()=>{e.removeEventListener("loadeddata",r),e.removeEventListener("resize",r),i()};e.addEventListener("loadeddata",r),e.addEventListener("resize",r)}}clearLiveVideo(e){this.liveSprite&&gr({target:this.liveSprite,props:{alpha:0},duration:400,easing:vs.easeInCubic,ticker:e,onComplete:()=>{var t;(t=this.liveSprite)==null||t.destroy(),this.liveSprite=null}}),this.idleVideoEl&&(this.idleVideoEl.style.display=""),this.idleGroup&&(this.idleGroup.visible=!0)}destroy(){var e,t;(e=this.cancelGlow)==null||e.call(this),(t=this.cancelEntrance)==null||t.call(this),this.idleVideoEl&&(this.idleVideoEl.pause(),this.idleVideoEl.remove()),this.container.destroy({children:!0})}}const px=[{urls:"stun:stun.l.google.com:19302"}],mx=3e3,gx="oai-events";class _x{constructor(e){this.onConnected=null,this.onDisconnected=null,this.onRemoteTrack=null,this.onDataMessage=null,this.onError=null,this.pc=null,this.dc=null,this.micStream=null,this._remoteAudioStream=null,this._connected=!1,this.opts={model:"gpt-4o-realtime-preview",voice:"verse",instructions:"",tools:[],...e}}get isConnected(){return this._connected}get dataChannel(){return this.dc}get remoteAudioStream(){return this._remoteAudioStream}async connect(){var e,t;try{console.log("[RealtimeSession] Requesting microphone..."),this.micStream=await navigator.mediaDevices.getUserMedia({audio:!0}),console.log("[RealtimeSession] Microphone granted"),this.pc=new RTCPeerConnection({iceServers:px}),this.setupPeerConnectionHandlers();for(const o of this.micStream.getAudioTracks())this.pc.addTrack(o,this.micStream);this.dc=this.pc.createDataChannel(gx),this.setupDataChannelHandlers();const i=await this.pc.createOffer();await this.pc.setLocalDescription(i),await this.waitForIceGathering();const r=(e=this.pc.localDescription)==null?void 0:e.sdp;if(!r)throw new Error("No local SDP after ICE gathering");console.log("[RealtimeSession] Exchanging SDP...");const n=await this.exchangeSDP(r);await this.pc.setRemoteDescription({type:"answer",sdp:n}),console.log("[RealtimeSession] Remote description set")}catch(i){const r=i instanceof Error?i:new Error(String(i));throw console.error("[RealtimeSession] Connection failed:",r.message),(t=this.onError)==null||t.call(this,r),this.close(),r}}sendJSON(e){if(!this.dc||this.dc.readyState!=="open"){console.warn("[RealtimeSession] Data channel not open, cannot send:",e);return}this.dc.send(JSON.stringify(e))}close(){var e;if(console.log("[RealtimeSession] Closing..."),this.dc){try{this.dc.close()}catch{}this.dc=null}if(this.pc){try{this.pc.close()}catch{}this.pc=null}if(this.micStream){for(const t of this.micStream.getTracks())t.stop();this.micStream=null}this._remoteAudioStream=null,this._connected&&(this._connected=!1,(e=this.onDisconnected)==null||e.call(this))}setupPeerConnectionHandlers(){this.pc&&(this.pc.ontrack=e=>{var t;console.log("[RealtimeSession] Remote audio track received"),this._remoteAudioStream=e.streams[0]??new MediaStream([e.track]),(t=this.onRemoteTrack)==null||t.call(this,this._remoteAudioStream)},this.pc.onconnectionstatechange=()=>{var t,i,r,n;const e=(t=this.pc)==null?void 0:t.connectionState;console.log("[RealtimeSession] Connection state:",e),e==="connected"?(this._connected=!0,(i=this.onConnected)==null||i.call(this)):(e==="failed"||e==="closed"||e==="disconnected")&&(this._connected&&(this._connected=!1,(r=this.onDisconnected)==null||r.call(this)),e==="failed"&&((n=this.onError)==null||n.call(this,new Error("WebRTC connection failed"))))})}waitForIceGathering(){return!this.pc||this.pc.iceGatheringState==="complete"?Promise.resolve():new Promise(e=>{const t=this.pc;let i;const r=()=>{clearTimeout(i);try{t.removeEventListener("icegatheringstatechange",n)}catch{}e()},n=()=>{t.iceGatheringState==="complete"&&r()};t.addEventListener("icegatheringstatechange",n),i=setTimeout(r,mx)})}async exchangeSDP(e){const{webrtcUrl:t,ephemeralKey:i,model:r,voice:n}=this.opts,o=t.includes("?")?"&":"?",a=`${t}${o}model=${encodeURIComponent(r)}&voice=${encodeURIComponent(n)}`,l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/sdp",Accept:"application/sdp"},body:e});if(!l.ok){const c=await l.text().catch(()=>"");throw new Error(`SDP exchange failed (${l.status}): ${c}`)}return l.text()}setupDataChannelHandlers(){this.dc&&(this.dc.onopen=()=>{console.log("[RealtimeSession] Data channel open"),this.sendSessionUpdate(),this.sendJSON({type:"response.create"})},this.dc.onmessage=e=>{var t;try{const i=JSON.parse(e.data);(t=this.onDataMessage)==null||t.call(this,i)}catch(i){console.warn("[RealtimeSession] Failed to parse data channel message:",i)}},this.dc.onclose=()=>{console.log("[RealtimeSession] Data channel closed")},this.dc.onerror=e=>{console.error("[RealtimeSession] Data channel error:",e)})}sendSessionUpdate(){const e={instructions:this.opts.instructions,modalities:["audio","text"],input_audio_transcription:{model:"whisper-1"},turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:300,silence_duration_ms:700,create_response:!0}};this.opts.tools&&this.opts.tools.length>0&&(e.tools=this.opts.tools),this.sendJSON({type:"session.update",session:e})}}const yx=24e3,bx=`
|
|
897
|
+
`})),t=this.device.createRenderPipeline({layout:"auto",vertex:{module:this.mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this.mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:e}]}}),this.pipelines[e]=t),t}generateMipmap(e){const t=this._getMipmapPipeline(e.format);if(e.dimension==="3d"||e.dimension==="1d")throw new Error("Generating mipmaps for non-2d textures is currently unsupported!");let i=e;const r=e.depthOrArrayLayers||1,n=e.usage&GPUTextureUsage.RENDER_ATTACHMENT;if(!n){const l={size:{width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r},format:e.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:e.mipLevelCount-1};i=this.device.createTexture(l)}const o=this.device.createCommandEncoder({}),a=t.getBindGroupLayout(0);for(let l=0;l<r;++l){let c=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),h=n?1:0;for(let u=1;u<e.mipLevelCount;++u){const f=i.createView({baseMipLevel:h++,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),d=o.beginRenderPass({colorAttachments:[{view:f,storeOp:"store",loadOp:"clear",clearValue:{r:0,g:0,b:0,a:0}}]}),g=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.sampler},{binding:1,resource:c}]});d.setPipeline(t),d.setBindGroup(0,g),d.draw(3,1,0,0),d.end(),c=f}}if(!n){const l={width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r};for(let c=1;c<e.mipLevelCount;++c)o.copyTextureToTexture({texture:i,mipLevel:c-1},{texture:e,mipLevel:c},l),l.width=Math.ceil(l.width/2),l.height=Math.ceil(l.height/2)}return this.device.queue.submit([o.finish()]),n||i.destroy(),e}}class nx{constructor(e){this.textureView=null,this.gpuTexture=e}destroy(){this.gpuTexture.destroy(),this.textureView=null,this.gpuTexture=null}}class Eu{constructor(e){this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._renderer=e,e.gc.addCollection(this,"_bindGroupHash","hash"),this._managedTextures=new kt({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"gpuTextureSource"});const t={image:Su,buffer:Qb,video:sx,compressed:tx};this._uploads={...t,cube:ix(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gpu=e}initSource(e){var t;return((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuTexture)||this._initSource(e)}_initSource(e){if(e.autoGenerateMipmaps){const c=Math.max(e.pixelWidth,e.pixelHeight);e.mipLevelCount=Math.floor(Math.log2(c))+1}let t=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST;e.uploadMethodId!=="compressed"&&(t|=GPUTextureUsage.RENDER_ATTACHMENT,t|=GPUTextureUsage.COPY_SRC);const i=vu[e.format]||{blockWidth:1,blockHeight:1},r=Math.ceil(e.pixelWidth/i.blockWidth)*i.blockWidth,n=Math.ceil(e.pixelHeight/i.blockHeight)*i.blockHeight,o={label:e.label,size:{width:r,height:n,depthOrArrayLayers:e.arrayLayerCount},format:e.format,sampleCount:e.sampleCount,mipLevelCount:e.mipLevelCount,dimension:e.dimension,usage:t},a=this._gpu.device.createTexture(o);return e._gpuData[this._renderer.uid]=new nx(a),this._managedTextures.add(e)&&(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceResize,this),e.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(e),a}onSourceUpdate(e){const t=this.getGpuSource(e);t&&(this._uploads[e.uploadMethodId]&&this._uploads[e.uploadMethodId].upload(e,t,this._gpu),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e))}onUpdateMipmaps(e){this._mipmapGenerator||(this._mipmapGenerator=new rx(this._gpu.device));const t=this.getGpuSource(e);this._mipmapGenerator.generateMipmap(t)}onSourceUnload(e){e.off("update",this.onSourceUpdate,this),e.off("resize",this.onSourceResize,this),e.off("updateMipmaps",this.onUpdateMipmaps,this)}onSourceResize(e){e._gcLastUsed=this._renderer.gc.now;const t=e._gpuData[this._renderer.uid],i=t==null?void 0:t.gpuTexture;i?(i.width!==e.pixelWidth||i.height!==e.pixelHeight)&&(t.destroy(),this._bindGroupHash[e.uid]=null,e._gpuData[this._renderer.uid]=null,this.initSource(e)):this.initSource(e)}_initSampler(e){return this._gpuSamplers[e._resourceId]=this._gpu.device.createSampler(e),this._gpuSamplers[e._resourceId]}getGpuSampler(e){return this._gpuSamplers[e._resourceId]||this._initSampler(e)}getGpuSource(e){var t;return e._gcLastUsed=this._renderer.gc.now,((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuTexture)||this.initSource(e)}getTextureBindGroup(e){return this._bindGroupHash[e.uid]||this._createTextureBindGroup(e)}_createTextureBindGroup(e){const t=e.source;return this._bindGroupHash[e.uid]=new Gt({0:t,1:t.style,2:new ht({uTextureMatrix:{type:"mat3x3<f32>",value:e.textureMatrix.mapCoord}})}),this._bindGroupHash[e.uid]}getTextureView(e){const t=e.source;t._gcLastUsed=this._renderer.gc.now;let i=t._gpuData[this._renderer.uid];return i||(this.initSource(t),i=t._gpuData[this._renderer.uid]),i.textureView||(i.textureView=i.gpuTexture.createView({dimension:t.viewDimension})),i.textureView}generateCanvas(e){const t=this._renderer,i=t.gpu.device.createCommandEncoder(),r=pe.get().createCanvas();r.width=e.source.pixelWidth,r.height=e.source.pixelHeight;const n=r.getContext("webgpu");return n.configure({device:t.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:pe.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:"premultiplied"}),i.copyTextureToTexture({texture:t.texture.getGpuSource(e.source),origin:{x:0,y:0}},{texture:n.getCurrentTexture()},{width:r.width,height:r.height}),t.gpu.device.queue.submit([i.finish()]),r}getPixels(e){const t=this.generateCanvas(e),i=so.getOptimalCanvasAndContext(t.width,t.height),r=i.context;r.drawImage(t,0,0);const{width:n,height:o}=t,a=r.getImageData(0,0,n,o),l=new Uint8ClampedArray(a.data.buffer);return so.returnCanvasAndContext(i),{pixels:l,width:n,height:o}}destroy(){this._managedTextures.destroy();for(const e of Object.keys(this._bindGroupHash)){const t=Number(e),i=this._bindGroupHash[t];i==null||i.destroy()}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._gpuSamplers=null,this._bindGroupHash=null}}Eu.extension={type:[A.WebGPUSystem],name:"texture"};class Tu{constructor(){this._maxTextures=0}contextChange(e){const t=new ht({uTransformMatrix:{value:new H,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}});this._maxTextures=e.limits.maxBatchableTextures;const i=Gn({name:"graphics",bits:[vc,Sc(this._maxTextures),_y,Vn]});this.shader=new Mt({gpuProgram:i,resources:{localUniforms:t}})}execute(e,t){const i=t.context,r=i.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(i),c=n.encoder;c.setGeometry(a.geometry,r.gpuProgram);const h=n.globalUniforms.bindGroup;c.setBindGroup(0,h,r.gpuProgram);const u=n.renderPipes.uniformBatch.getUniformBindGroup(r.resources.localUniforms,!0);c.setBindGroup(2,u,r.gpuProgram);const f=l.instructions;let d=null;for(let g=0;g<l.instructionSize;g++){const _=f[g];if(_.topology!==d&&(d=_.topology,c.setPipelineFromGeometryProgramAndState(a.geometry,r.gpuProgram,e.state,_.topology)),r.groups[1]=_.bindGroup,!_.gpuBindGroup){const b=_.textures;_.bindGroup=Nn(b.textures,b.count,this._maxTextures),_.gpuBindGroup=n.bindGroup.getBindGroup(_.bindGroup,r.gpuProgram,1)}c.setBindGroup(1,_.bindGroup,r.gpuProgram),c.renderPassEncoder.drawIndexed(_.size,1,_.start)}}destroy(){this.shader.destroy(!0),this.shader=null}}Tu.extension={type:[A.WebGPUPipesAdaptor],name:"graphics"};class Au{init(){const e=Gn({name:"mesh",bits:[ur,vy,Vn]});this._shader=new Mt({gpuProgram:e,resources:{uTexture:j.EMPTY._source,uSampler:j.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new H}}}})}execute(e,t){const i=e.renderer;let r=t._shader;if(!r)r=this._shader,r.groups[2]=i.texture.getTextureBindGroup(t.texture);else if(!r.gpuProgram){se("Mesh shader has no gpuProgram",t.shader);return}const n=r.gpuProgram;if(n.autoAssignGlobalUniforms&&(r.groups[0]=i.globalUniforms.bindGroup),n.autoAssignLocalUniforms){const o=e.localUniforms;r.groups[1]=i.renderPipes.uniformBatch.getUniformBindGroup(o,!0)}i.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}Au.extension={type:[A.WebGPUPipesAdaptor],name:"mesh"};const ox=[...Ao,qr,fu,Oo,pu,uu,Eu,yu,bu,xu,_u,du,mu,hu],ax=[...Fh,gu],lx=[yh,Au,Tu],wu=[],Iu=[],Ru=[];Q.handleByNamedList(A.WebGPUSystem,wu),Q.handleByNamedList(A.WebGPUPipes,Iu),Q.handleByNamedList(A.WebGPUPipesAdaptor,Ru),Q.add(...ox,...ax,...lx);class cx extends vi{constructor(){const e={name:"webgpu",type:bt.WEBGPU,systems:wu,renderPipes:Iu,renderPipeAdaptors:Ru};super(e)}}const hx=Object.freeze(Object.defineProperty({__proto__:null,WebGPURenderer:cx},Symbol.toStringTag,{value:"Module"}));Q.add(Rm,Mm);const Bi=480,xs=480;class ux{constructor(){this.container=null,this.resizeObserver=null,this.mode="floating",this.targetEl=null,this.app=new nc}async init(e="floating",t){this.mode=e,e==="inline"&&t&&(this.targetEl=document.querySelector(t),this.targetEl||(console.warn(`[HolostaffWidget] Container "${t}" not found, falling back to floating mode`),this.mode="floating")),await this.app.init({width:Bi,height:xs,backgroundAlpha:0,antialias:!0,resolution:window.devicePixelRatio||1,autoDensity:!0,preference:"webgl"}),this.container=document.createElement("div"),this.container.id="holostaff-widget-root",this.mode==="inline"&&this.targetEl?(Object.assign(this.container.style,{position:"relative",width:"100%",height:"100%",overflow:"visible",pointerEvents:"none"}),this.targetEl.style.position="relative",this.targetEl.style.cursor="pointer",this.targetEl.appendChild(this.container)):(Object.assign(this.container.style,{position:"fixed",bottom:"0",left:"50%",transform:"translateX(-50%)",width:`${Bi}px`,height:`${xs}px`,zIndex:"2147483646",pointerEvents:"none",overflow:"visible"}),document.documentElement.appendChild(this.container));const i=this.app.canvas;return Object.assign(i.style,{width:"100%",height:"100%",display:"block",pointerEvents:"auto"}),this.container.appendChild(i),this.setupResize(),i}setupResize(){const e=()=>{if(this.mode==="inline"&&this.targetEl){const t=this.targetEl.getBoundingClientRect();this.container&&(this.container.style.width=`${t.width}px`,this.container.style.height=`${t.height}px`)}else{const t=window.innerWidth,i=Math.min(Bi,t),r=i/Bi,n=xs*r;this.container&&(this.container.style.width=`${i}px`,this.container.style.height=`${n}px`)}this.app.renderer.resize(Bi,xs)};window.addEventListener("resize",e),this.mode==="inline"&&this.targetEl&&(this.resizeObserver=new ResizeObserver(e),this.resizeObserver.observe(this.targetEl)),e()}get isInline(){return this.mode==="inline"&&this.targetEl!==null}get inlineTarget(){return this.targetEl}get rootElement(){return this.container}get stageWidth(){return Bi}get stageHeight(){return xs}getInlineRect(){var e;return((e=this.targetEl)==null?void 0:e.getBoundingClientRect())??null}destroy(){var e,t;window.removeEventListener("resize",this.setupResize),(e=this.resizeObserver)==null||e.disconnect(),(t=this.container)==null||t.remove(),this.app.destroy(!0)}}function dx(){var s,e;return((e=(s=globalThis.matchMedia)==null?void 0:s.call(globalThis,"(prefers-reduced-motion: reduce)"))==null?void 0:e.matches)??!1}const vs={easeOutCubic:s=>1-Math.pow(1-s,3),easeInCubic:s=>s*s*s,easeOutBack:s=>1+2.70158*Math.pow(s-1,3)+1.70158*Math.pow(s-1,2),easeInOutSine:s=>-(Math.cos(Math.PI*s)-1)/2};function gr(s){const{target:e,props:t,duration:i,easing:r=vs.easeOutCubic,delay:n=0,onComplete:o,ticker:a}=s;if(dx()){for(const f of Object.keys(t))e[f]=t[f];return o==null||o(),()=>{}}const l={};for(const f of Object.keys(t))l[f]=e[f];let c=-n,h=!1;const u=f=>{if(h||(c+=f.deltaMS,c<0))return;const d=Math.min(c/i,1),g=r(d);for(const _ of Object.keys(t))e[_]=l[_]+(t[_]-l[_])*g;d>=1&&(a.remove(u),o==null||o())};return a.add(u),()=>{h=!0,a.remove(u)}}const Cs=200,Vt=Cs*(480/854),Mu=280;class fx{constructor(e,t){this.idleVideoEl=null,this.idleGroup=null,this.liveSprite=null,this.cancelGlow=null,this.cancelEntrance=null,this.visible=!1,this.widgetRoot=null,this.stageWidth=e,this.stageHeight=t,this.container=new Ve,this.container.visible=!1,this.container.x=e/2,this.container.y=t+Vt}async loadIdleVideo(e,t){this.widgetRoot=t,this.idleVideoEl=document.createElement("video"),this.idleVideoEl.src=e,this.idleVideoEl.loop=!0,this.idleVideoEl.muted=!0,this.idleVideoEl.playsInline=!0,this.idleVideoEl.crossOrigin="anonymous",Object.assign(this.idleVideoEl.style,{position:"absolute",bottom:"10px",left:"50%",transform:"translateX(-50%) translateY(100%)",width:`${Cs}px`,height:"auto",pointerEvents:"none",zIndex:"0",transition:"none"}),t.insertBefore(this.idleVideoEl,t.firstChild),await this.idleVideoEl.play(),this.idleGroup=new Ve,this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+Vt}async loadIdleImage(e){const t=j.from(e),i=new Ft(t);i.width=Cs,i.height=Vt,i.anchor.set(.5,1),this.idleGroup=new Ve,this.idleGroup.addChild(i),this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+Vt}slideIn(e){if(this.visible)return;this.visible=!0;const t=this.stageHeight-10;this.container.alpha=1,this.container.visible=!0,this.container.y=this.stageHeight+Vt,this.cancelEntrance=gr({target:this.container,props:{y:t},duration:700,easing:vs.easeOutBack,ticker:e}),this.idleVideoEl&&(this.idleVideoEl.style.transition="transform 0.7s cubic-bezier(0.34, 1.56, 0.64, 1)",this.idleVideoEl.style.transform="translateX(-50%) translateY(0)")}slideOut(e){var t;this.visible&&(this.visible=!1,(t=this.cancelGlow)==null||t.call(this),this.cancelGlow=null,gr({target:this.container,props:{y:this.stageHeight+Vt},duration:450,easing:vs.easeInCubic,ticker:e,onComplete:()=>{this.container.visible=!1}}),this.idleVideoEl&&(this.idleVideoEl.style.transition="transform 0.45s cubic-bezier(0.32, 0, 0.67, 0)",this.idleVideoEl.style.transform="translateX(-50%) translateY(100%)"))}get isVisible(){return this.visible}setInteractive(e){this.container.eventMode="static",this.container.cursor="pointer",this.container.hitArea=new Se(-Cs/2,-Vt,Cs,Vt),this.container.on("pointertap",e),this.idleVideoEl&&(this.idleVideoEl.style.pointerEvents="auto",this.idleVideoEl.style.cursor="pointer",this.idleVideoEl.addEventListener("click",e))}setLiveVideo(e,t){const i=()=>{var l;const r=j.from(e);this.liveSprite=new Ft(r);const n=e.videoWidth||1,o=e.videoHeight||1,a=Mu/n;this.liveSprite.width=Mu,this.liveSprite.height=o*a,this.liveSprite.anchor.set(.5,1),this.liveSprite.alpha=0,this.container.addChild(this.liveSprite),this.idleVideoEl&&(this.idleVideoEl.style.display="none"),this.idleGroup&&(this.idleGroup.visible=!1),(l=this.cancelGlow)==null||l.call(this),this.cancelGlow=null,gr({target:this.liveSprite,props:{alpha:1},duration:500,easing:vs.easeInOutSine,ticker:t})};if(e.videoWidth>0&&e.videoHeight>0)i();else{const r=()=>{e.removeEventListener("loadeddata",r),e.removeEventListener("resize",r),i()};e.addEventListener("loadeddata",r),e.addEventListener("resize",r)}}clearLiveVideo(e){this.liveSprite&&gr({target:this.liveSprite,props:{alpha:0},duration:400,easing:vs.easeInCubic,ticker:e,onComplete:()=>{var t;(t=this.liveSprite)==null||t.destroy(),this.liveSprite=null}}),this.idleVideoEl&&(this.idleVideoEl.style.display=""),this.idleGroup&&(this.idleGroup.visible=!0)}destroy(){var e,t;(e=this.cancelGlow)==null||e.call(this),(t=this.cancelEntrance)==null||t.call(this),this.idleVideoEl&&(this.idleVideoEl.pause(),this.idleVideoEl.remove()),this.container.destroy({children:!0})}}const px=[{urls:"stun:stun.l.google.com:19302"}],mx=3e3,gx="oai-events";class _x{constructor(e){this.onConnected=null,this.onDisconnected=null,this.onRemoteTrack=null,this.onDataMessage=null,this.onError=null,this.pc=null,this.dc=null,this.micStream=null,this._remoteAudioStream=null,this._connected=!1,this.opts={model:"gpt-4o-realtime-preview",voice:"verse",instructions:"",tools:[],...e}}get isConnected(){return this._connected}get dataChannel(){return this.dc}get remoteAudioStream(){return this._remoteAudioStream}async connect(){var e,t;try{console.log("[RealtimeSession] Requesting microphone..."),this.micStream=await navigator.mediaDevices.getUserMedia({audio:!0}),console.log("[RealtimeSession] Microphone granted"),this.pc=new RTCPeerConnection({iceServers:px}),this.setupPeerConnectionHandlers();for(const o of this.micStream.getAudioTracks())this.pc.addTrack(o,this.micStream);this.dc=this.pc.createDataChannel(gx),this.setupDataChannelHandlers();const i=await this.pc.createOffer();await this.pc.setLocalDescription(i),await this.waitForIceGathering();const r=(e=this.pc.localDescription)==null?void 0:e.sdp;if(!r)throw new Error("No local SDP after ICE gathering");console.log("[RealtimeSession] Exchanging SDP...");const n=await this.exchangeSDP(r);await this.pc.setRemoteDescription({type:"answer",sdp:n}),console.log("[RealtimeSession] Remote description set")}catch(i){const r=i instanceof Error?i:new Error(String(i));throw console.error("[RealtimeSession] Connection failed:",r.message),(t=this.onError)==null||t.call(this,r),this.close(),r}}sendJSON(e){if(!this.dc||this.dc.readyState!=="open"){console.warn("[RealtimeSession] Data channel not open, cannot send:",e);return}this.dc.send(JSON.stringify(e))}close(){var e;if(console.log("[RealtimeSession] Closing..."),this.dc){try{this.dc.close()}catch{}this.dc=null}if(this.pc){try{this.pc.close()}catch{}this.pc=null}if(this.micStream){for(const t of this.micStream.getTracks())t.stop();this.micStream=null}this._remoteAudioStream=null,this._connected&&(this._connected=!1,(e=this.onDisconnected)==null||e.call(this))}setupPeerConnectionHandlers(){this.pc&&(this.pc.ontrack=e=>{var t;console.log("[RealtimeSession] Remote audio track received"),this._remoteAudioStream=e.streams[0]??new MediaStream([e.track]),(t=this.onRemoteTrack)==null||t.call(this,this._remoteAudioStream)},this.pc.onconnectionstatechange=()=>{var t,i,r,n;const e=(t=this.pc)==null?void 0:t.connectionState;console.log("[RealtimeSession] Connection state:",e),e==="connected"?(this._connected=!0,(i=this.onConnected)==null||i.call(this)):(e==="failed"||e==="closed"||e==="disconnected")&&(this._connected&&(this._connected=!1,(r=this.onDisconnected)==null||r.call(this)),e==="failed"&&((n=this.onError)==null||n.call(this,new Error("WebRTC connection failed"))))})}waitForIceGathering(){return!this.pc||this.pc.iceGatheringState==="complete"?Promise.resolve():new Promise(e=>{const t=this.pc;let i;const r=()=>{clearTimeout(i);try{t.removeEventListener("icegatheringstatechange",n)}catch{}e()},n=()=>{t.iceGatheringState==="complete"&&r()};t.addEventListener("icegatheringstatechange",n),i=setTimeout(r,mx)})}async exchangeSDP(e){const{webrtcUrl:t,ephemeralKey:i,model:r,voice:n}=this.opts,o=t.includes("?")?"&":"?",a=`${t}${o}model=${encodeURIComponent(r)}&voice=${encodeURIComponent(n)}`,l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/sdp",Accept:"application/sdp"},body:e});if(!l.ok){const c=await l.text().catch(()=>"");throw new Error(`SDP exchange failed (${l.status}): ${c}`)}return l.text()}setupDataChannelHandlers(){this.dc&&(this.dc.onopen=()=>{console.log("[RealtimeSession] Data channel open"),this.sendSessionUpdate(),this.sendJSON({type:"response.create"})},this.dc.onmessage=e=>{var t;try{const i=JSON.parse(e.data);(t=this.onDataMessage)==null||t.call(this,i)}catch(i){console.warn("[RealtimeSession] Failed to parse data channel message:",i)}},this.dc.onclose=()=>{console.log("[RealtimeSession] Data channel closed")},this.dc.onerror=e=>{console.error("[RealtimeSession] Data channel error:",e)})}sendSessionUpdate(){const e={instructions:this.opts.instructions,modalities:["audio","text"],input_audio_transcription:{model:"whisper-1"},turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:300,silence_duration_ms:700,create_response:!0}};this.opts.tools&&this.opts.tools.length>0&&(e.tools=this.opts.tools),this.sendJSON({type:"session.update",session:e})}}const yx=24e3,bx=`
|
|
898
898
|
class PcmBufferProcessor extends AudioWorkletProcessor {
|
|
899
899
|
constructor() {
|
|
900
900
|
super()
|
|
@@ -953,7 +953,7 @@ registerProcessor('pcm-buffer-processor', PcmBufferProcessor)
|
|
|
953
953
|
pointer-events: none;
|
|
954
954
|
display: none;
|
|
955
955
|
`,document.body.appendChild(this.videoElement),this.client.addListener(te.CONNECTION_ESTABLISHED,()=>{var i;console.log("[AnamSession] Connection established"),this._connected=!0,(i=this.onConnected)==null||i.call(this)}),this.client.addListener(te.VIDEO_PLAY_STARTED,()=>{var i;console.log("[AnamSession] Video playing"),this.videoElement&&(this.videoElement.style.display="",(i=this.onVideoReady)==null||i.call(this,this.videoElement))}),this.client.addListener(te.TALK_STREAM_INTERRUPTED,()=>{var i;console.log("[AnamSession] Talk stream interrupted"),(i=this.onTalkStreamInterrupted)==null||i.call(this)}),this.client.addListener(te.CONNECTION_CLOSED,i=>{var r;console.log("[AnamSession] Connection closed:",i),this._connected=!1,(r=this.onDisconnected)==null||r.call(this,String(i))}),await this.client.streamToVideoElement(t),this.audioInputStream=this.client.createAgentAudioInputStream({encoding:"pcm_s16le",sampleRate:24e3,channels:1}),console.log("[AnamSession] BYO audio input stream ready")}catch(t){const i=t instanceof Error?t:new Error(String(t));throw console.error("[AnamSession] Connection failed:",i.message),(e=this.onError)==null||e.call(this,i),this.close(),i}}sendAudioChunk(e){var t;(t=this.audioInputStream)==null||t.sendAudioChunk(e)}endSequence(){var e;(e=this.audioInputStream)==null||e.endSequence()}interrupt(){this.client.interruptPersona()}close(){if(!this._closing){this._closing=!0,console.log("[AnamSession] Closing...");try{this.client.stopStreaming()}catch{}this.videoElement&&(this.videoElement.pause(),this.videoElement.srcObject=null,this.videoElement.remove(),this.videoElement=null),document.querySelectorAll('video[id^="anam-avatar-video"]').forEach(e=>{e.pause(),e.remove()}),this.audioInputStream=null,this._connected=!1}}}const tv=new Set(["a","button","input","select","textarea","details","summary","label","option"]),iv=new Set(["button","link","menuitem","menuitemcheckbox","menuitemradio","tab","switch","slider","combobox","listbox","option","radio","checkbox","textbox","searchbox","scrollbar"]),sv=new Set(["h1","h2","h3","h4","h5","h6"]),rv=["type","role","aria-label","placeholder","value","href","alt","title","name","checked","aria-expanded"];class nv{constructor(){this.elementMap=new Map}analyze(){this.elementMap.clear();let e=0;const t=[];t.push(`Page: ${document.title}`),t.push(`URL: ${location.href}`),t.push("");const i=r=>{if(r.nodeType===Node.TEXT_NODE){const c=(r.textContent??"").trim();c&&c.length>1&&t.push(c);return}if(r.nodeType!==Node.ELEMENT_NODE)return;const n=r,o=n.tagName.toLowerCase();if(!this.isVisible(n)||["script","style","svg","noscript","link","meta"].includes(o)||n.id==="holostaff-widget-root"||n.closest("#holostaff-widget-root"))return;const a=this.isInteractive(n),l=sv.has(o);if(a||l){const c=e++;this.elementMap.set(c,n);const h=this.getUsefulAttrs(n),u=h?" "+h:"",f=this.getDirectText(n).slice(0,200);if(l){const d=parseInt(o[1]),g="#".repeat(d);t.push(""),t.push(`${g} [${c}]${f}`)}else t.push(`[${c}]<${o}${u}>${f}</${o}>`);return}for(const c of n.childNodes)i(c)};return i(document.body),{text:t.join(`
|
|
956
|
-
`),elementMap:this.elementMap}}getElementByIndex(e){return this.elementMap.get(e)??null}isVisible(e){const t=getComputedStyle(e);return!(t.display==="none"||t.visibility==="hidden")}isInteractive(e){const t=e.tagName.toLowerCase();if(tv.has(t))return!e.disabled;const i=e.getAttribute("role");if(i&&iv.has(i))return!0;try{if(getComputedStyle(e).cursor==="pointer")return!0}catch{}return!!(e.hasAttribute("tabindex")&&e.getAttribute("tabindex")!=="-1"||e.isContentEditable&&e.getAttribute("contenteditable")!=="false")}getDirectText(e){return(e.textContent??"").replace(/\s+/g," ").trim()}getUsefulAttrs(e){const t=[];for(const i of rv){const r=e.getAttribute(i);r&&r.length>0&&r.length<100&&t.push(`${i}="${r}"`)}return t.join(" ")}}const ov=new Set(["scroll_to","click","highlight"]);class av{constructor(e){this.onToolCall=null,this.fnArgBufs=new Map,this.fnNames=new Map,this.fnCallIds=new Map,this.realtimeSession=e.realtimeSession,this.domAnalyzer=e.domAnalyzer,this.pageActions=e.pageActions,this.overlayActions=e.overlayActions,this.confirmationPrompt=e.confirmationPrompt,this.staffId=e.staffId,this.backendUrl=e.backendUrl}handleMessage(e){var i;switch(e.type){case"response.output_item.added":if(((i=e.item)==null?void 0:i.type)==="function_call"){const r=e.item.id,n=e.item.name,o=e.item.call_id||e.item.id;return this.fnNames.set(r,n),this.fnCallIds.set(r,o),this.fnArgBufs.set(r,""),console.log(`[ToolHandler] Function call started: ${n} (${r})`),!0}return!1;case"response.function_call_arguments.delta":if(e.item_id&&this.fnArgBufs.has(e.item_id)){const r=this.fnArgBufs.get(e.item_id)??"";return this.fnArgBufs.set(e.item_id,r+(e.delta??"")),!0}return!1;case"response.function_call_arguments.done":return e.item_id&&this.fnArgBufs.has(e.item_id)?(this.handleFunctionCallDone(e.item_id),!0):!1;default:return!1}}async handleFunctionCallDone(e){var a;const t=this.fnNames.get(e)??"unknown",i=this.fnCallIds.get(e)??e,r=this.fnArgBufs.get(e)??"{}";this.fnArgBufs.delete(e),this.fnNames.delete(e),this.fnCallIds.delete(e);let n;try{n=JSON.parse(r)}catch{console.warn(`[ToolHandler] Failed to parse args for ${t}:`,r),this.sendToolResult(i,{error:"Malformed JSON in function call arguments"});return}console.log(`[ToolHandler] Executing: ${t}`,n),(a=this.onToolCall)==null||a.call(this,t,n);let o=null;switch(t){case"page_action":await this.handlePageAction(i,n.instruction??"");return;case"show_text_card":o=this.overlayActions.showTextCard(n.title??"",n.body??"");break;case"show_image_card":o=this.overlayActions.showImageCard(n.image_url??"",n.caption);break;case"show_bullet_list":o=this.overlayActions.showBulletList(n.title??"",n.items??[]);break;case"dismiss_overlays":o=this.overlayActions.dismissAll();break;default:console.warn(`[ToolHandler] Unknown tool: ${t}`),o={error:`Unknown tool: ${t}`}}this.sendToolResult(i,o)}async handlePageAction(e,t){try{const i=t.toLowerCase();if(i.includes("scroll")&&(i.includes("top")||i.includes("beginning"))){const l=this.pageActions.scrollTo(-1);this.sendToolResult(e,{results:[{action:"scroll_to",...l}]});return}if(i.includes("scroll")&&(i.includes("bottom")||i.includes("end"))){const l=this.pageActions.scrollTo(-2);this.sendToolResult(e,{results:[{action:"scroll_to",...l}]});return}const{text:r}=this.domAnalyzer.analyze();console.log(`[ToolHandler] DOM snapshot: ${r.length} chars, instruction: "${t}"`);const o=(await Uf(this.staffId,r,t,this.backendUrl)).actions??[];console.log(`[ToolHandler] Page agent returned ${o.length} actions:`,o);const a=[];for(const l of o){if(l.action==="describe"){a.push({action:"describe",status:"ok",description:l.description});continue}if(ov.has(l.action)&&!await this.confirmationPrompt.ask(`${l.description}?`)){a.push({action:l.action,status:"declined",description:"Visitor declined"});continue}let c;switch(l.action){case"scroll_to":c=this.pageActions.scrollTo(l.index);break;case"highlight":c=this.pageActions.highlight(l.index);break;case"click":c=this.pageActions.click(l.index);break;case"fill":c=this.pageActions.fill(l.index,l.value??"");break;default:c={status:"error",description:`Unknown action: ${l.action}`}}a.push({action:l.action,...c})}this.sendToolResult(e,{results:a})}catch(i){const r=i instanceof Error?i.message:String(i);console.error("[ToolHandler] Page action failed:",r),this.sendToolResult(e,{error:r})}}sendToolResult(e,t){this.realtimeSession.sendJSON({type:"conversation.item.create",item:{type:"function_call_output",call_id:e,output:JSON.stringify(t)}}),this.realtimeSession.sendJSON({type:"response.create"})}}class lv{constructor(e,t){this.analyzer=e,this.highlightRenderer=t}scrollTo(e){if(e===-1)return window.scrollTo({top:0,behavior:"smooth"}),document.documentElement.scrollTop=0,document.body.scrollTop=0,console.log("[PageActions] Scrolled to top"),{status:"scrolled",description:"Top of page"};if(e===-2)return window.scrollTo({top:document.body.scrollHeight,behavior:"smooth"}),console.log("[PageActions] Scrolled to bottom"),{status:"scrolled",description:"Bottom of page"};const t=this.analyzer.getElementByIndex(e);if(!t)return{status:"error",description:`Element [${e}] not found`};t.scrollIntoView({behavior:"smooth",block:"center"});let i=t.parentElement;for(;i;){const n=getComputedStyle(i).overflowY;if(n==="auto"||n==="scroll"){const o=t.getBoundingClientRect().top-i.getBoundingClientRect().top+i.scrollTop;i.scrollTo({top:o-i.clientHeight/2,behavior:"smooth"});break}i=i.parentElement}const r=this.describeElement(t);return console.log(`[PageActions] Scrolled to [${e}] ${r}`),{status:"scrolled",description:r}}highlight(e,t=3e3){const i=this.analyzer.getElementByIndex(e);if(!i)return{status:"error",description:`Element [${e}] not found`};this.highlightRenderer.highlight(i,t);const r=this.describeElement(i);return console.log(`[PageActions] Highlighting [${e}] ${r} for ${t}ms`),{status:"highlighted",description:r}}click(e){const t=this.analyzer.getElementByIndex(e);if(!t)return{status:"error",description:`Element [${e}] not found`};t.click();const i=this.describeElement(t);return console.log(`[PageActions] Clicked [${e}] ${i}`),{status:"clicked",description:i}}fill(e,t){var a,l;const i=this.analyzer.getElementByIndex(e);if(!i)return{status:"error",description:`Element [${e}] not found`};const r=i.tagName.toLowerCase(),n=(a=i.type)==null?void 0:a.toLowerCase();if(r==="select"){const c=i,h=Array.from(c.options).find(u=>u.text.toLowerCase().includes(t.toLowerCase())||u.value.toLowerCase()===t.toLowerCase());if(h)c.value=h.value,c.dispatchEvent(new Event("change",{bubbles:!0}));else return{status:"error",description:`No option matching "${t}"`}}else if(n==="checkbox"||n==="radio"){const c=i;c.checked=t==="true"||t==="1",c.dispatchEvent(new Event("change",{bubbles:!0}))}else{const c=(l=Object.getOwnPropertyDescriptor(r==="textarea"?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value"))==null?void 0:l.set;c?c.call(i,t):i.value=t,i.dispatchEvent(new Event("input",{bubbles:!0})),i.dispatchEvent(new Event("change",{bubbles:!0}))}const o=this.describeElement(i);return console.log(`[PageActions] Filled [${e}] ${o} with "${t}"`),{status:"filled",description:`${o} = "${t}"`}}describeElement(e){const t=e.tagName.toLowerCase(),i=(e.textContent??"").trim().slice(0,50),r=e.getAttribute("aria-label")||e.getAttribute("placeholder")||i;return`<${t}>${r}</${t}>`}}class cv{constructor(e){this.renderer=e}showTextCard(e,t){return this.renderer.showTextCard(e,t),console.log(`[OverlayActions] Showing text card: "${e}"`),{status:"shown"}}showImageCard(e,t){return this.renderer.showImageCard(e,t),console.log(`[OverlayActions] Showing image card: "${t??e}"`),{status:"shown"}}showBulletList(e,t){return this.renderer.showBulletList(e,t),console.log(`[OverlayActions] Showing bullet list: "${e}" (${t.length} items)`),{status:"shown"}}dismissAll(){return this.renderer.dismissAll(),console.log("[OverlayActions] Dismissed all overlays"),{status:"dismissed"}}}const hv="https://us-central1-holostaff-ai.cloudfunctions.net";class uv{constructor(e){this.messages={},this.actions=[],this.msgCounter=0,this.staffId=e.staffId,this.staffName=e.staffName,this.backendUrl=e.backendUrl??hv,this.startTime=new Date().toISOString(),this.userId=`visitor_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}addUserMessage(e){if(!e.trim())return;const t=`msg_${this.msgCounter++}`;this.messages[t]={sender:"user",text:e.trim(),timestamp:new Date().toISOString()}}addStaffMessage(e){if(!e.trim())return;const t=`msg_${this.msgCounter++}`;this.messages[t]={sender:"staff",text:e.trim(),timestamp:new Date().toISOString()}}addAction(e,t){this.actions.push({tool:e,args:t,timestamp:new Date().toISOString()})}getSummary(){const e=Object.values(this.messages);return e.length===0?"No conversation took place.":e.slice(-6).map(i=>`${i.sender==="user"?"User":"Agent"}: ${i.text.slice(0,80)}`).join(" | ")}async flush(){if(Object.keys(this.messages).length===0){console.log("[Logger] No messages to log, skipping");return}const e=Object.values(this.messages).pop(),t={staffId:this.staffId,staffName:this.staffName,userId:this.userId,startTime:this.startTime,lastMessageAt:(e==null?void 0:e.timestamp)??this.startTime,messages:this.messages,actions:this.actions,source:"widget_v2"};console.log("[Logger] Flushing conversation log:",{messages:Object.keys(this.messages).length,actions:this.actions.length});const i=`${this.backendUrl}/logConversation`,r=JSON.stringify(t);try{const n=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!0});if(n.ok){const o=await n.json();console.log("[Logger] Conversation logged:",o.id)}else console.warn("[Logger] Failed to log conversation:",n.status)}catch(n){console.warn("[Logger] Error logging conversation:",n)}}}var We;(function(s){s[s.Document=0]="Document",s[s.DocumentType=1]="DocumentType",s[s.Element=2]="Element",s[s.Text=3]="Text",s[s.CDATA=4]="CDATA",s[s.Comment=5]="Comment"})(We||(We={}));function dv(s){return s.nodeType===s.ELEMENT_NODE}function Es(s){var e=s==null?void 0:s.host;return(e==null?void 0:e.shadowRoot)===s}function Ts(s){return Object.prototype.toString.call(s)==="[object ShadowRoot]"}function fv(s){return s.includes(" background-clip: text;")&&!s.includes(" -webkit-background-clip: text;")&&(s=s.replace(" background-clip: text;"," -webkit-background-clip: text; background-clip: text;")),s}function Go(s){try{var e=s.rules||s.cssRules;return e?fv(Array.from(e).map(Hu).join("")):null}catch{return null}}function Hu(s){var e=s.cssText;if(pv(s))try{e=Go(s.styleSheet)||e}catch{}return e}function pv(s){return"styleSheet"in s}var Vu=(function(){function s(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}return s.prototype.getId=function(e){var t;if(!e)return-1;var i=(t=this.getMeta(e))===null||t===void 0?void 0:t.id;return i??-1},s.prototype.getNode=function(e){return this.idNodeMap.get(e)||null},s.prototype.getIds=function(){return Array.from(this.idNodeMap.keys())},s.prototype.getMeta=function(e){return this.nodeMetaMap.get(e)||null},s.prototype.removeNodeFromMap=function(e){var t=this,i=this.getId(e);this.idNodeMap.delete(i),e.childNodes&&e.childNodes.forEach(function(r){return t.removeNodeFromMap(r)})},s.prototype.has=function(e){return this.idNodeMap.has(e)},s.prototype.hasNode=function(e){return this.nodeMetaMap.has(e)},s.prototype.add=function(e,t){var i=t.id;this.idNodeMap.set(i,e),this.nodeMetaMap.set(e,t)},s.prototype.replace=function(e,t){var i=this.getNode(e);if(i){var r=this.nodeMetaMap.get(i);r&&this.nodeMetaMap.set(t,r)}this.idNodeMap.set(e,t)},s.prototype.reset=function(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap},s})();function mv(){return new Vu}function Lo(s){var e=s.maskInputOptions,t=s.tagName,i=s.type,r=s.value,n=s.maskInputFn,o=r||"";return(e[t.toLowerCase()]||e[i])&&(n?o=n(o):o="*".repeat(o.length)),o}var zu="__rrweb_original__";function gv(s){var e=s.getContext("2d");if(!e)return!0;for(var t=50,i=0;i<s.width;i+=t)for(var r=0;r<s.height;r+=t){var n=e.getImageData,o=zu in n?n[zu]:n,a=new Uint32Array(o.call(e,i,r,Math.min(t,s.width-i),Math.min(t,s.height-r)).data.buffer);if(a.some(function(l){return l!==0}))return!1}return!0}var _v=1,yv=new RegExp("[^a-z0-9-_:]"),As=-2;function $u(){return _v++}function bv(s){if(s instanceof HTMLFormElement)return"form";var e=s.tagName.toLowerCase().trim();return yv.test(e)?"div":e}function xv(s){return s.cssRules?Array.from(s.cssRules).map(function(e){return e.cssText||""}).join(""):""}function vv(s){var e="";return s.indexOf("//")>-1?e=s.split("/").slice(0,3).join("/"):e=s.split("/")[0],e=e.split("?")[0],e}var Ui,ju,Cv=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,Sv=/^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/|#).*/,Ev=/^(data:)([^,]*),(.*)/i;function br(s,e){return(s||"").replace(Cv,function(t,i,r,n,o,a){var l=r||o||a,c=i||n||"";if(!l)return t;if(!Sv.test(l)||Ev.test(l))return"url(".concat(c).concat(l).concat(c,")");if(l[0]==="/")return"url(".concat(c).concat(vv(e)+l).concat(c,")");var h=e.split("/"),u=l.split("/");h.pop();for(var f=0,d=u;f<d.length;f++){var g=d[f];g!=="."&&(g===".."?h.pop():h.push(g))}return"url(".concat(c).concat(h.join("/")).concat(c,")")})}var Tv=/^[^ \t\n\r\u000c]+/,Av=/^[, \t\n\r\u000c]+/;function wv(s,e){if(e.trim()==="")return e;var t=0;function i(c){var h,u=c.exec(e.substring(t));return u?(h=u[0],t+=h.length,h):""}for(var r=[];i(Av),!(t>=e.length);){var n=i(Tv);if(n.slice(-1)===",")n=Fi(s,n.substring(0,n.length-1)),r.push(n);else{var o="";n=Fi(s,n);for(var a=!1;;){var l=e.charAt(t);if(l===""){r.push((n+o).trim());break}else if(a)l===")"&&(a=!1);else if(l===","){t+=1,r.push((n+o).trim());break}else l==="("&&(a=!0);o+=l,t+=1}}}return r.join(", ")}function Fi(s,e){if(!e||e.trim()==="")return e;var t=s.createElement("a");return t.href=e,t.href}function Iv(s){return!!(s.tagName==="svg"||s.ownerSVGElement)}function Wo(){var s=document.createElement("a");return s.href="",s.href}function Xu(s,e,t,i){return t==="src"||t==="href"&&i&&!(e==="use"&&i[0]==="#")||t==="xlink:href"&&i&&i[0]!=="#"||t==="background"&&i&&(e==="table"||e==="td"||e==="th")?Fi(s,i):t==="srcset"&&i?wv(s,i):t==="style"&&i?br(i,Wo()):e==="object"&&t==="data"&&i?Fi(s,i):i}function Rv(s,e,t){if(typeof e=="string"){if(s.classList.contains(e))return!0}else for(var i=s.classList.length;i--;){var r=s.classList[i];if(e.test(r))return!0}return t?s.matches(t):!1}function xr(s,e,t){if(!s)return!1;if(s.nodeType!==s.ELEMENT_NODE)return t?xr(s.parentNode,e,t):!1;for(var i=s.classList.length;i--;){var r=s.classList[i];if(e.test(r))return!0}return t?xr(s.parentNode,e,t):!1}function Yu(s,e,t){var i=s.nodeType===s.ELEMENT_NODE?s:s.parentElement;if(i===null)return!1;if(typeof e=="string"){if(i.classList.contains(e)||i.closest(".".concat(e)))return!0}else if(xr(i,e,!0))return!0;return!!(t&&(i.matches(t)||i.closest(t)))}function Mv(s,e,t){var i=s.contentWindow;if(i){var r=!1,n;try{n=i.document.readyState}catch{return}if(n!=="complete"){var o=setTimeout(function(){r||(e(),r=!0)},t);s.addEventListener("load",function(){clearTimeout(o),r=!0,e()});return}var a="about:blank";if(i.location.href!==a||s.src===a||s.src==="")return setTimeout(e,0),s.addEventListener("load",e);s.addEventListener("load",e)}}function Pv(s,e,t){var i=!1,r;try{r=s.sheet}catch{return}if(!r){var n=setTimeout(function(){i||(e(),i=!0)},t);s.addEventListener("load",function(){clearTimeout(n),i=!0,e()})}}function kv(s,e){var t=e.doc,i=e.mirror,r=e.blockClass,n=e.blockSelector,o=e.maskTextClass,a=e.maskTextSelector,l=e.inlineStylesheet,c=e.maskInputOptions,h=c===void 0?{}:c,u=e.maskTextFn,f=e.maskInputFn,d=e.dataURLOptions,g=d===void 0?{}:d,_=e.inlineImages,b=e.recordCanvas,x=e.keepIframeSrcFn,C=e.newlyAddedElement,S=C===void 0?!1:C,E=Ov(t,i);switch(s.nodeType){case s.DOCUMENT_NODE:return s.compatMode!=="CSS1Compat"?{type:We.Document,childNodes:[],compatMode:s.compatMode}:{type:We.Document,childNodes:[]};case s.DOCUMENT_TYPE_NODE:return{type:We.DocumentType,name:s.name,publicId:s.publicId,systemId:s.systemId,rootId:E};case s.ELEMENT_NODE:return Dv(s,{doc:t,blockClass:r,blockSelector:n,inlineStylesheet:l,maskInputOptions:h,maskInputFn:f,dataURLOptions:g,inlineImages:_,recordCanvas:b,keepIframeSrcFn:x,newlyAddedElement:S,rootId:E});case s.TEXT_NODE:return Bv(s,{maskTextClass:o,maskTextSelector:a,maskTextFn:u,rootId:E});case s.CDATA_SECTION_NODE:return{type:We.CDATA,textContent:"",rootId:E};case s.COMMENT_NODE:return{type:We.Comment,textContent:s.textContent||"",rootId:E};default:return!1}}function Ov(s,e){if(e.hasNode(s)){var t=e.getId(s);return t===1?void 0:t}}function Bv(s,e){var t,i=e.maskTextClass,r=e.maskTextSelector,n=e.maskTextFn,o=e.rootId,a=s.parentNode&&s.parentNode.tagName,l=s.textContent,c=a==="STYLE"?!0:void 0,h=a==="SCRIPT"?!0:void 0;if(c&&l){try{s.nextSibling||s.previousSibling||!((t=s.parentNode.sheet)===null||t===void 0)&&t.cssRules&&(l=xv(s.parentNode.sheet))}catch(u){console.warn("Cannot get CSS styles from text's parentNode. Error: ".concat(u),s)}l=br(l,Wo())}return h&&(l="SCRIPT_PLACEHOLDER"),!c&&!h&&l&&Yu(s,i,r)&&(l=n?n(l):l.replace(/[\S]/g,"*")),{type:We.Text,textContent:l||"",isStyle:c,rootId:o}}function Dv(s,e){for(var t=e.doc,i=e.blockClass,r=e.blockSelector,n=e.inlineStylesheet,o=e.maskInputOptions,a=o===void 0?{}:o,l=e.maskInputFn,c=e.dataURLOptions,h=c===void 0?{}:c,u=e.inlineImages,f=e.recordCanvas,d=e.keepIframeSrcFn,g=e.newlyAddedElement,_=g===void 0?!1:g,b=e.rootId,x=Rv(s,i,r),C=bv(s),S={},E=s.attributes.length,w=0;w<E;w++){var R=s.attributes[w];S[R.name]=Xu(t,C,R.name,R.value)}if(C==="link"&&n){var M=Array.from(t.styleSheets).find(function(K){return K.href===s.href}),D=null;M&&(D=Go(M)),D&&(delete S.rel,delete S.href,S._cssText=br(D,M.href))}if(C==="style"&&s.sheet&&!(s.innerText||s.textContent||"").trim().length){var D=Go(s.sheet);D&&(S._cssText=br(D,Wo()))}if(C==="input"||C==="textarea"||C==="select"){var F=s.value,k=s.checked;S.type!=="radio"&&S.type!=="checkbox"&&S.type!=="submit"&&S.type!=="button"&&F?S.value=Lo({type:S.type,tagName:C,value:F,maskInputOptions:a,maskInputFn:l}):k&&(S.checked=k)}if(C==="option"&&(s.selected&&!a.select?S.selected=!0:delete S.selected),C==="canvas"&&f){if(s.__context==="2d")gv(s)||(S.rr_dataURL=s.toDataURL(h.type,h.quality));else if(!("__context"in s)){var O=s.toDataURL(h.type,h.quality),V=document.createElement("canvas");V.width=s.width,V.height=s.height;var X=V.toDataURL(h.type,h.quality);O!==X&&(S.rr_dataURL=O)}}if(C==="img"&&u){Ui||(Ui=t.createElement("canvas"),ju=Ui.getContext("2d"));var z=s,de=z.crossOrigin;z.crossOrigin="anonymous";var B=function(){try{Ui.width=z.naturalWidth,Ui.height=z.naturalHeight,ju.drawImage(z,0,0),S.rr_dataURL=Ui.toDataURL(h.type,h.quality)}catch(K){console.warn("Cannot inline img src=".concat(z.currentSrc,"! Error: ").concat(K))}de?S.crossOrigin=de:z.removeAttribute("crossorigin")};z.complete&&z.naturalWidth!==0?B():z.onload=B}if((C==="audio"||C==="video")&&(S.rr_mediaState=s.paused?"paused":"played",S.rr_mediaCurrentTime=s.currentTime),_||(s.scrollLeft&&(S.rr_scrollLeft=s.scrollLeft),s.scrollTop&&(S.rr_scrollTop=s.scrollTop)),x){var U=s.getBoundingClientRect(),q=U.width,N=U.height;S={class:S.class,rr_width:"".concat(q,"px"),rr_height:"".concat(N,"px")}}return C==="iframe"&&!d(S.src)&&(s.contentDocument||(S.rr_src=S.src),delete S.src),{type:We.Element,tagName:C,attributes:S,childNodes:[],isSVG:Iv(s)||void 0,needBlock:x,rootId:b}}function ve(s){return s===void 0?"":s.toLowerCase()}function Nv(s,e){if(e.comment&&s.type===We.Comment)return!0;if(s.type===We.Element){if(e.script&&(s.tagName==="script"||s.tagName==="link"&&s.attributes.rel==="preload"&&s.attributes.as==="script"||s.tagName==="link"&&s.attributes.rel==="prefetch"&&typeof s.attributes.href=="string"&&s.attributes.href.endsWith(".js")))return!0;if(e.headFavicon&&(s.tagName==="link"&&s.attributes.rel==="shortcut icon"||s.tagName==="meta"&&(ve(s.attributes.name).match(/^msapplication-tile(image|color)$/)||ve(s.attributes.name)==="application-name"||ve(s.attributes.rel)==="icon"||ve(s.attributes.rel)==="apple-touch-icon"||ve(s.attributes.rel)==="shortcut icon")))return!0;if(s.tagName==="meta"){if(e.headMetaDescKeywords&&ve(s.attributes.name).match(/^description|keywords$/))return!0;if(e.headMetaSocial&&(ve(s.attributes.property).match(/^(og|twitter|fb):/)||ve(s.attributes.name).match(/^(og|twitter):/)||ve(s.attributes.name)==="pinterest"))return!0;if(e.headMetaRobots&&(ve(s.attributes.name)==="robots"||ve(s.attributes.name)==="googlebot"||ve(s.attributes.name)==="bingbot"))return!0;if(e.headMetaHttpEquiv&&s.attributes["http-equiv"]!==void 0)return!0;if(e.headMetaAuthorship&&(ve(s.attributes.name)==="author"||ve(s.attributes.name)==="generator"||ve(s.attributes.name)==="framework"||ve(s.attributes.name)==="publisher"||ve(s.attributes.name)==="progid"||ve(s.attributes.property).match(/^article:/)||ve(s.attributes.property).match(/^product:/)))return!0;if(e.headMetaVerification&&(ve(s.attributes.name)==="google-site-verification"||ve(s.attributes.name)==="yandex-verification"||ve(s.attributes.name)==="csrf-token"||ve(s.attributes.name)==="p:domain_verify"||ve(s.attributes.name)==="verify-v1"||ve(s.attributes.name)==="verification"||ve(s.attributes.name)==="shopify-checkout-api-token"))return!0}}return!1}function Gi(s,e){var t=e.doc,i=e.mirror,r=e.blockClass,n=e.blockSelector,o=e.maskTextClass,a=e.maskTextSelector,l=e.skipChild,c=l===void 0?!1:l,h=e.inlineStylesheet,u=h===void 0?!0:h,f=e.maskInputOptions,d=f===void 0?{}:f,g=e.maskTextFn,_=e.maskInputFn,b=e.slimDOMOptions,x=e.dataURLOptions,C=x===void 0?{}:x,S=e.inlineImages,E=S===void 0?!1:S,w=e.recordCanvas,R=w===void 0?!1:w,M=e.onSerialize,D=e.onIframeLoad,F=e.iframeLoadTimeout,k=F===void 0?5e3:F,O=e.onStylesheetLoad,V=e.stylesheetLoadTimeout,X=V===void 0?5e3:V,z=e.keepIframeSrcFn,de=z===void 0?function(){return!1}:z,B=e.newlyAddedElement,U=B===void 0?!1:B,q=e.preserveWhiteSpace,N=q===void 0?!0:q,K=kv(s,{doc:t,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,dataURLOptions:C,inlineImages:E,recordCanvas:R,keepIframeSrcFn:de,newlyAddedElement:U});if(!K)return console.warn(s,"not serialized"),null;var Z;i.hasNode(s)?Z=i.getId(s):Nv(K,b)||!N&&K.type===We.Text&&!K.isStyle&&!K.textContent.replace(/^\s+|\s+$/gm,"").length?Z=As:Z=$u();var $=Object.assign(K,{id:Z});if(i.add(s,$),Z===As)return null;M&&M(s);var ae=!c;if($.type===We.Element){ae=ae&&!$.needBlock,delete $.needBlock;var Ce=s.shadowRoot;Ce&&Ts(Ce)&&($.isShadowHost=!0)}if(($.type===We.Document||$.type===We.Element)&&ae){b.headWhitespace&&$.type===We.Element&&$.tagName==="head"&&(N=!1);for(var Ee={doc:t,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:c,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:b,dataURLOptions:C,inlineImages:E,recordCanvas:R,preserveWhiteSpace:N,onSerialize:M,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:X,keepIframeSrcFn:de},G=0,fe=Array.from(s.childNodes);G<fe.length;G++){var le=fe[G],L=Gi(le,Ee);L&&$.childNodes.push(L)}if(dv(s)&&s.shadowRoot)for(var me=0,Y=Array.from(s.shadowRoot.childNodes);me<Y.length;me++){var le=Y[me],L=Gi(le,Ee);L&&(Ts(s.shadowRoot)&&(L.isShadow=!0),$.childNodes.push(L))}}return s.parentNode&&Es(s.parentNode)&&Ts(s.parentNode)&&($.isShadow=!0),$.type===We.Element&&$.tagName==="iframe"&&Mv(s,function(){var ie=s.contentDocument;if(ie&&D){var we=Gi(ie,{doc:ie,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:b,dataURLOptions:C,inlineImages:E,recordCanvas:R,preserveWhiteSpace:N,onSerialize:M,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:X,keepIframeSrcFn:de});we&&D(s,we)}},k),$.type===We.Element&&$.tagName==="link"&&$.attributes.rel==="stylesheet"&&Pv(s,function(){if(O){var ie=Gi(s,{doc:t,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:b,dataURLOptions:C,inlineImages:E,recordCanvas:R,preserveWhiteSpace:N,onSerialize:M,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:X,keepIframeSrcFn:de});ie&&O(s,ie)}},X),$}function Uv(s,e){var t=e||{},i=t.mirror,r=i===void 0?new Vu:i,n=t.blockClass,o=n===void 0?"rr-block":n,a=t.blockSelector,l=a===void 0?null:a,c=t.maskTextClass,h=c===void 0?"rr-mask":c,u=t.maskTextSelector,f=u===void 0?null:u,d=t.inlineStylesheet,g=d===void 0?!0:d,_=t.inlineImages,b=_===void 0?!1:_,x=t.recordCanvas,C=x===void 0?!1:x,S=t.maskAllInputs,E=S===void 0?!1:S,w=t.maskTextFn,R=t.maskInputFn,M=t.slimDOM,D=M===void 0?!1:M,F=t.dataURLOptions,k=t.preserveWhiteSpace,O=t.onSerialize,V=t.onIframeLoad,X=t.iframeLoadTimeout,z=t.onStylesheetLoad,de=t.stylesheetLoadTimeout,B=t.keepIframeSrcFn,U=B===void 0?function(){return!1}:B,q=E===!0?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:E===!1?{password:!0}:E,N=D===!0||D==="all"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:D==="all",headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:D===!1?{}:D;return Gi(s,{doc:s,mirror:r,blockClass:o,blockSelector:l,maskTextClass:h,maskTextSelector:f,skipChild:!1,inlineStylesheet:g,maskInputOptions:q,maskTextFn:w,maskInputFn:R,slimDOMOptions:N,dataURLOptions:F,inlineImages:b,recordCanvas:C,preserveWhiteSpace:k,onSerialize:O,onIframeLoad:V,iframeLoadTimeout:X,onStylesheetLoad:z,stylesheetLoadTimeout:de,keepIframeSrcFn:U,newlyAddedElement:!1})}function Ze(s,e,t=document){const i={capture:!0,passive:!0};return t.addEventListener(s,e,i),()=>t.removeEventListener(s,e,i)}const Li=`Please stop import mirror directly. Instead of that,\r
|
|
956
|
+
`),elementMap:this.elementMap}}getElementByIndex(e){return this.elementMap.get(e)??null}isVisible(e){const t=getComputedStyle(e);return!(t.display==="none"||t.visibility==="hidden")}isInteractive(e){const t=e.tagName.toLowerCase();if(tv.has(t))return!e.disabled;const i=e.getAttribute("role");if(i&&iv.has(i))return!0;try{if(getComputedStyle(e).cursor==="pointer")return!0}catch{}return!!(e.hasAttribute("tabindex")&&e.getAttribute("tabindex")!=="-1"||e.isContentEditable&&e.getAttribute("contenteditable")!=="false")}getDirectText(e){return(e.textContent??"").replace(/\s+/g," ").trim()}getUsefulAttrs(e){const t=[];for(const i of rv){const r=e.getAttribute(i);r&&r.length>0&&r.length<100&&t.push(`${i}="${r}"`)}return t.join(" ")}}const ov=new Set(["scroll_to","click","highlight"]);class av{constructor(e){this.onToolCall=null,this.fnArgBufs=new Map,this.fnNames=new Map,this.fnCallIds=new Map,this.realtimeSession=e.realtimeSession,this.domAnalyzer=e.domAnalyzer,this.pageActions=e.pageActions,this.overlayActions=e.overlayActions,this.confirmationPrompt=e.confirmationPrompt,this.staffId=e.staffId,this.backendUrl=e.backendUrl,this.skills=e.skills??{}}handleMessage(e){var i;switch(e.type){case"response.output_item.added":if(((i=e.item)==null?void 0:i.type)==="function_call"){const r=e.item.id,n=e.item.name,o=e.item.call_id||e.item.id;return this.fnNames.set(r,n),this.fnCallIds.set(r,o),this.fnArgBufs.set(r,""),console.log(`[ToolHandler] Function call started: ${n} (${r})`),!0}return!1;case"response.function_call_arguments.delta":if(e.item_id&&this.fnArgBufs.has(e.item_id)){const r=this.fnArgBufs.get(e.item_id)??"";return this.fnArgBufs.set(e.item_id,r+(e.delta??"")),!0}return!1;case"response.function_call_arguments.done":return e.item_id&&this.fnArgBufs.has(e.item_id)?(this.handleFunctionCallDone(e.item_id),!0):!1;default:return!1}}async handleFunctionCallDone(e){var a;const t=this.fnNames.get(e)??"unknown",i=this.fnCallIds.get(e)??e,r=this.fnArgBufs.get(e)??"{}";this.fnArgBufs.delete(e),this.fnNames.delete(e),this.fnCallIds.delete(e);let n;try{n=JSON.parse(r)}catch{console.warn(`[ToolHandler] Failed to parse args for ${t}:`,r),this.sendToolResult(i,{error:"Malformed JSON in function call arguments"});return}console.log(`[ToolHandler] Executing: ${t}`,n),(a=this.onToolCall)==null||a.call(this,t,n);let o=null;switch(t){case"page_action":await this.handlePageAction(i,n.instruction??"");return;case"show_text_card":o=this.overlayActions.showTextCard(n.title??"",n.body??"");break;case"show_image_card":o=this.overlayActions.showImageCard(n.image_url??"",n.caption);break;case"show_bullet_list":o=this.overlayActions.showBulletList(n.title??"",n.items??[]);break;case"dismiss_overlays":o=this.overlayActions.dismissAll();break;case"get_skill_instructions":{const l=n.skill_name??"",c=this.skills[l];c?(console.log(`[ToolHandler] Serving skill instructions for "${l}" (${c.length} chars)`),o={instructions:c}):(console.warn(`[ToolHandler] Skill not found: "${l}". Available: ${Object.keys(this.skills).join(", ")}`),o={error:`No skill found with name "${l}". Available skills: ${Object.keys(this.skills).join(", ")}`});break}default:console.warn(`[ToolHandler] Unknown tool: ${t}`),o={error:`Unknown tool: ${t}`}}this.sendToolResult(i,o)}async handlePageAction(e,t){try{const i=t.toLowerCase();if(i.includes("scroll")&&(i.includes("top")||i.includes("beginning"))){const l=this.pageActions.scrollTo(-1);this.sendToolResult(e,{results:[{action:"scroll_to",...l}]});return}if(i.includes("scroll")&&(i.includes("bottom")||i.includes("end"))){const l=this.pageActions.scrollTo(-2);this.sendToolResult(e,{results:[{action:"scroll_to",...l}]});return}const{text:r}=this.domAnalyzer.analyze();console.log(`[ToolHandler] DOM snapshot: ${r.length} chars, instruction: "${t}"`);const o=(await Uf(this.staffId,r,t,this.backendUrl)).actions??[];console.log(`[ToolHandler] Page agent returned ${o.length} actions:`,o);const a=[];for(const l of o){if(l.action==="describe"){a.push({action:"describe",status:"ok",description:l.description});continue}if(ov.has(l.action)&&!await this.confirmationPrompt.ask(`${l.description}?`)){a.push({action:l.action,status:"declined",description:"Visitor declined"});continue}let c;switch(l.action){case"scroll_to":c=this.pageActions.scrollTo(l.index);break;case"highlight":c=this.pageActions.highlight(l.index);break;case"click":c=this.pageActions.click(l.index);break;case"fill":c=this.pageActions.fill(l.index,l.value??"");break;default:c={status:"error",description:`Unknown action: ${l.action}`}}a.push({action:l.action,...c})}this.sendToolResult(e,{results:a})}catch(i){const r=i instanceof Error?i.message:String(i);console.error("[ToolHandler] Page action failed:",r),this.sendToolResult(e,{error:r})}}sendToolResult(e,t){this.realtimeSession.sendJSON({type:"conversation.item.create",item:{type:"function_call_output",call_id:e,output:JSON.stringify(t)}}),this.realtimeSession.sendJSON({type:"response.create"})}}class lv{constructor(e,t){this.analyzer=e,this.highlightRenderer=t}scrollTo(e){if(e===-1)return window.scrollTo({top:0,behavior:"smooth"}),document.documentElement.scrollTop=0,document.body.scrollTop=0,console.log("[PageActions] Scrolled to top"),{status:"scrolled",description:"Top of page"};if(e===-2)return window.scrollTo({top:document.body.scrollHeight,behavior:"smooth"}),console.log("[PageActions] Scrolled to bottom"),{status:"scrolled",description:"Bottom of page"};const t=this.analyzer.getElementByIndex(e);if(!t)return{status:"error",description:`Element [${e}] not found`};t.scrollIntoView({behavior:"smooth",block:"center"});let i=t.parentElement;for(;i;){const n=getComputedStyle(i).overflowY;if(n==="auto"||n==="scroll"){const o=t.getBoundingClientRect().top-i.getBoundingClientRect().top+i.scrollTop;i.scrollTo({top:o-i.clientHeight/2,behavior:"smooth"});break}i=i.parentElement}const r=this.describeElement(t);return console.log(`[PageActions] Scrolled to [${e}] ${r}`),{status:"scrolled",description:r}}highlight(e,t=3e3){const i=this.analyzer.getElementByIndex(e);if(!i)return{status:"error",description:`Element [${e}] not found`};this.highlightRenderer.highlight(i,t);const r=this.describeElement(i);return console.log(`[PageActions] Highlighting [${e}] ${r} for ${t}ms`),{status:"highlighted",description:r}}click(e){const t=this.analyzer.getElementByIndex(e);if(!t)return{status:"error",description:`Element [${e}] not found`};t.click();const i=this.describeElement(t);return console.log(`[PageActions] Clicked [${e}] ${i}`),{status:"clicked",description:i}}fill(e,t){var a,l;const i=this.analyzer.getElementByIndex(e);if(!i)return{status:"error",description:`Element [${e}] not found`};const r=i.tagName.toLowerCase(),n=(a=i.type)==null?void 0:a.toLowerCase();if(r==="select"){const c=i,h=Array.from(c.options).find(u=>u.text.toLowerCase().includes(t.toLowerCase())||u.value.toLowerCase()===t.toLowerCase());if(h)c.value=h.value,c.dispatchEvent(new Event("change",{bubbles:!0}));else return{status:"error",description:`No option matching "${t}"`}}else if(n==="checkbox"||n==="radio"){const c=i;c.checked=t==="true"||t==="1",c.dispatchEvent(new Event("change",{bubbles:!0}))}else{const c=(l=Object.getOwnPropertyDescriptor(r==="textarea"?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value"))==null?void 0:l.set;c?c.call(i,t):i.value=t,i.dispatchEvent(new Event("input",{bubbles:!0})),i.dispatchEvent(new Event("change",{bubbles:!0}))}const o=this.describeElement(i);return console.log(`[PageActions] Filled [${e}] ${o} with "${t}"`),{status:"filled",description:`${o} = "${t}"`}}describeElement(e){const t=e.tagName.toLowerCase(),i=(e.textContent??"").trim().slice(0,50),r=e.getAttribute("aria-label")||e.getAttribute("placeholder")||i;return`<${t}>${r}</${t}>`}}class cv{constructor(e){this.renderer=e}showTextCard(e,t){return this.renderer.showTextCard(e,t),console.log(`[OverlayActions] Showing text card: "${e}"`),{status:"shown"}}showImageCard(e,t){return this.renderer.showImageCard(e,t),console.log(`[OverlayActions] Showing image card: "${t??e}"`),{status:"shown"}}showBulletList(e,t){return this.renderer.showBulletList(e,t),console.log(`[OverlayActions] Showing bullet list: "${e}" (${t.length} items)`),{status:"shown"}}dismissAll(){return this.renderer.dismissAll(),console.log("[OverlayActions] Dismissed all overlays"),{status:"dismissed"}}}const hv="https://us-central1-holostaff-ai.cloudfunctions.net";class uv{constructor(e){this.messages={},this.actions=[],this.msgCounter=0,this.staffId=e.staffId,this.staffName=e.staffName,this.backendUrl=e.backendUrl??hv,this.startTime=new Date().toISOString(),this.userId=`visitor_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}addUserMessage(e){if(!e.trim())return;const t=`msg_${this.msgCounter++}`;this.messages[t]={sender:"user",text:e.trim(),timestamp:new Date().toISOString()}}addStaffMessage(e){if(!e.trim())return;const t=`msg_${this.msgCounter++}`;this.messages[t]={sender:"staff",text:e.trim(),timestamp:new Date().toISOString()}}addAction(e,t){this.actions.push({tool:e,args:t,timestamp:new Date().toISOString()})}getSummary(){const e=Object.values(this.messages);return e.length===0?"No conversation took place.":e.slice(-6).map(i=>`${i.sender==="user"?"User":"Agent"}: ${i.text.slice(0,80)}`).join(" | ")}async flush(){if(Object.keys(this.messages).length===0){console.log("[Logger] No messages to log, skipping");return}const e=Object.values(this.messages).pop(),t={staffId:this.staffId,staffName:this.staffName,userId:this.userId,startTime:this.startTime,lastMessageAt:(e==null?void 0:e.timestamp)??this.startTime,messages:this.messages,actions:this.actions,source:"widget_v2"};console.log("[Logger] Flushing conversation log:",{messages:Object.keys(this.messages).length,actions:this.actions.length});const i=`${this.backendUrl}/logConversation`,r=JSON.stringify(t);try{const n=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!0});if(n.ok){const o=await n.json();console.log("[Logger] Conversation logged:",o.id)}else console.warn("[Logger] Failed to log conversation:",n.status)}catch(n){console.warn("[Logger] Error logging conversation:",n)}}}var We;(function(s){s[s.Document=0]="Document",s[s.DocumentType=1]="DocumentType",s[s.Element=2]="Element",s[s.Text=3]="Text",s[s.CDATA=4]="CDATA",s[s.Comment=5]="Comment"})(We||(We={}));function dv(s){return s.nodeType===s.ELEMENT_NODE}function Es(s){var e=s==null?void 0:s.host;return(e==null?void 0:e.shadowRoot)===s}function Ts(s){return Object.prototype.toString.call(s)==="[object ShadowRoot]"}function fv(s){return s.includes(" background-clip: text;")&&!s.includes(" -webkit-background-clip: text;")&&(s=s.replace(" background-clip: text;"," -webkit-background-clip: text; background-clip: text;")),s}function Go(s){try{var e=s.rules||s.cssRules;return e?fv(Array.from(e).map(Hu).join("")):null}catch{return null}}function Hu(s){var e=s.cssText;if(pv(s))try{e=Go(s.styleSheet)||e}catch{}return e}function pv(s){return"styleSheet"in s}var Vu=(function(){function s(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}return s.prototype.getId=function(e){var t;if(!e)return-1;var i=(t=this.getMeta(e))===null||t===void 0?void 0:t.id;return i??-1},s.prototype.getNode=function(e){return this.idNodeMap.get(e)||null},s.prototype.getIds=function(){return Array.from(this.idNodeMap.keys())},s.prototype.getMeta=function(e){return this.nodeMetaMap.get(e)||null},s.prototype.removeNodeFromMap=function(e){var t=this,i=this.getId(e);this.idNodeMap.delete(i),e.childNodes&&e.childNodes.forEach(function(r){return t.removeNodeFromMap(r)})},s.prototype.has=function(e){return this.idNodeMap.has(e)},s.prototype.hasNode=function(e){return this.nodeMetaMap.has(e)},s.prototype.add=function(e,t){var i=t.id;this.idNodeMap.set(i,e),this.nodeMetaMap.set(e,t)},s.prototype.replace=function(e,t){var i=this.getNode(e);if(i){var r=this.nodeMetaMap.get(i);r&&this.nodeMetaMap.set(t,r)}this.idNodeMap.set(e,t)},s.prototype.reset=function(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap},s})();function mv(){return new Vu}function Lo(s){var e=s.maskInputOptions,t=s.tagName,i=s.type,r=s.value,n=s.maskInputFn,o=r||"";return(e[t.toLowerCase()]||e[i])&&(n?o=n(o):o="*".repeat(o.length)),o}var zu="__rrweb_original__";function gv(s){var e=s.getContext("2d");if(!e)return!0;for(var t=50,i=0;i<s.width;i+=t)for(var r=0;r<s.height;r+=t){var n=e.getImageData,o=zu in n?n[zu]:n,a=new Uint32Array(o.call(e,i,r,Math.min(t,s.width-i),Math.min(t,s.height-r)).data.buffer);if(a.some(function(l){return l!==0}))return!1}return!0}var _v=1,yv=new RegExp("[^a-z0-9-_:]"),As=-2;function $u(){return _v++}function bv(s){if(s instanceof HTMLFormElement)return"form";var e=s.tagName.toLowerCase().trim();return yv.test(e)?"div":e}function xv(s){return s.cssRules?Array.from(s.cssRules).map(function(e){return e.cssText||""}).join(""):""}function vv(s){var e="";return s.indexOf("//")>-1?e=s.split("/").slice(0,3).join("/"):e=s.split("/")[0],e=e.split("?")[0],e}var Ui,ju,Cv=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,Sv=/^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/|#).*/,Ev=/^(data:)([^,]*),(.*)/i;function br(s,e){return(s||"").replace(Cv,function(t,i,r,n,o,a){var l=r||o||a,c=i||n||"";if(!l)return t;if(!Sv.test(l)||Ev.test(l))return"url(".concat(c).concat(l).concat(c,")");if(l[0]==="/")return"url(".concat(c).concat(vv(e)+l).concat(c,")");var h=e.split("/"),u=l.split("/");h.pop();for(var f=0,d=u;f<d.length;f++){var g=d[f];g!=="."&&(g===".."?h.pop():h.push(g))}return"url(".concat(c).concat(h.join("/")).concat(c,")")})}var Tv=/^[^ \t\n\r\u000c]+/,Av=/^[, \t\n\r\u000c]+/;function wv(s,e){if(e.trim()==="")return e;var t=0;function i(c){var h,u=c.exec(e.substring(t));return u?(h=u[0],t+=h.length,h):""}for(var r=[];i(Av),!(t>=e.length);){var n=i(Tv);if(n.slice(-1)===",")n=Fi(s,n.substring(0,n.length-1)),r.push(n);else{var o="";n=Fi(s,n);for(var a=!1;;){var l=e.charAt(t);if(l===""){r.push((n+o).trim());break}else if(a)l===")"&&(a=!1);else if(l===","){t+=1,r.push((n+o).trim());break}else l==="("&&(a=!0);o+=l,t+=1}}}return r.join(", ")}function Fi(s,e){if(!e||e.trim()==="")return e;var t=s.createElement("a");return t.href=e,t.href}function Iv(s){return!!(s.tagName==="svg"||s.ownerSVGElement)}function Wo(){var s=document.createElement("a");return s.href="",s.href}function Xu(s,e,t,i){return t==="src"||t==="href"&&i&&!(e==="use"&&i[0]==="#")||t==="xlink:href"&&i&&i[0]!=="#"||t==="background"&&i&&(e==="table"||e==="td"||e==="th")?Fi(s,i):t==="srcset"&&i?wv(s,i):t==="style"&&i?br(i,Wo()):e==="object"&&t==="data"&&i?Fi(s,i):i}function Rv(s,e,t){if(typeof e=="string"){if(s.classList.contains(e))return!0}else for(var i=s.classList.length;i--;){var r=s.classList[i];if(e.test(r))return!0}return t?s.matches(t):!1}function xr(s,e,t){if(!s)return!1;if(s.nodeType!==s.ELEMENT_NODE)return t?xr(s.parentNode,e,t):!1;for(var i=s.classList.length;i--;){var r=s.classList[i];if(e.test(r))return!0}return t?xr(s.parentNode,e,t):!1}function Yu(s,e,t){var i=s.nodeType===s.ELEMENT_NODE?s:s.parentElement;if(i===null)return!1;if(typeof e=="string"){if(i.classList.contains(e)||i.closest(".".concat(e)))return!0}else if(xr(i,e,!0))return!0;return!!(t&&(i.matches(t)||i.closest(t)))}function Mv(s,e,t){var i=s.contentWindow;if(i){var r=!1,n;try{n=i.document.readyState}catch{return}if(n!=="complete"){var o=setTimeout(function(){r||(e(),r=!0)},t);s.addEventListener("load",function(){clearTimeout(o),r=!0,e()});return}var a="about:blank";if(i.location.href!==a||s.src===a||s.src==="")return setTimeout(e,0),s.addEventListener("load",e);s.addEventListener("load",e)}}function Pv(s,e,t){var i=!1,r;try{r=s.sheet}catch{return}if(!r){var n=setTimeout(function(){i||(e(),i=!0)},t);s.addEventListener("load",function(){clearTimeout(n),i=!0,e()})}}function kv(s,e){var t=e.doc,i=e.mirror,r=e.blockClass,n=e.blockSelector,o=e.maskTextClass,a=e.maskTextSelector,l=e.inlineStylesheet,c=e.maskInputOptions,h=c===void 0?{}:c,u=e.maskTextFn,f=e.maskInputFn,d=e.dataURLOptions,g=d===void 0?{}:d,_=e.inlineImages,b=e.recordCanvas,x=e.keepIframeSrcFn,C=e.newlyAddedElement,S=C===void 0?!1:C,E=Ov(t,i);switch(s.nodeType){case s.DOCUMENT_NODE:return s.compatMode!=="CSS1Compat"?{type:We.Document,childNodes:[],compatMode:s.compatMode}:{type:We.Document,childNodes:[]};case s.DOCUMENT_TYPE_NODE:return{type:We.DocumentType,name:s.name,publicId:s.publicId,systemId:s.systemId,rootId:E};case s.ELEMENT_NODE:return Dv(s,{doc:t,blockClass:r,blockSelector:n,inlineStylesheet:l,maskInputOptions:h,maskInputFn:f,dataURLOptions:g,inlineImages:_,recordCanvas:b,keepIframeSrcFn:x,newlyAddedElement:S,rootId:E});case s.TEXT_NODE:return Bv(s,{maskTextClass:o,maskTextSelector:a,maskTextFn:u,rootId:E});case s.CDATA_SECTION_NODE:return{type:We.CDATA,textContent:"",rootId:E};case s.COMMENT_NODE:return{type:We.Comment,textContent:s.textContent||"",rootId:E};default:return!1}}function Ov(s,e){if(e.hasNode(s)){var t=e.getId(s);return t===1?void 0:t}}function Bv(s,e){var t,i=e.maskTextClass,r=e.maskTextSelector,n=e.maskTextFn,o=e.rootId,a=s.parentNode&&s.parentNode.tagName,l=s.textContent,c=a==="STYLE"?!0:void 0,h=a==="SCRIPT"?!0:void 0;if(c&&l){try{s.nextSibling||s.previousSibling||!((t=s.parentNode.sheet)===null||t===void 0)&&t.cssRules&&(l=xv(s.parentNode.sheet))}catch(u){console.warn("Cannot get CSS styles from text's parentNode. Error: ".concat(u),s)}l=br(l,Wo())}return h&&(l="SCRIPT_PLACEHOLDER"),!c&&!h&&l&&Yu(s,i,r)&&(l=n?n(l):l.replace(/[\S]/g,"*")),{type:We.Text,textContent:l||"",isStyle:c,rootId:o}}function Dv(s,e){for(var t=e.doc,i=e.blockClass,r=e.blockSelector,n=e.inlineStylesheet,o=e.maskInputOptions,a=o===void 0?{}:o,l=e.maskInputFn,c=e.dataURLOptions,h=c===void 0?{}:c,u=e.inlineImages,f=e.recordCanvas,d=e.keepIframeSrcFn,g=e.newlyAddedElement,_=g===void 0?!1:g,b=e.rootId,x=Rv(s,i,r),C=bv(s),S={},E=s.attributes.length,w=0;w<E;w++){var R=s.attributes[w];S[R.name]=Xu(t,C,R.name,R.value)}if(C==="link"&&n){var M=Array.from(t.styleSheets).find(function(K){return K.href===s.href}),D=null;M&&(D=Go(M)),D&&(delete S.rel,delete S.href,S._cssText=br(D,M.href))}if(C==="style"&&s.sheet&&!(s.innerText||s.textContent||"").trim().length){var D=Go(s.sheet);D&&(S._cssText=br(D,Wo()))}if(C==="input"||C==="textarea"||C==="select"){var F=s.value,k=s.checked;S.type!=="radio"&&S.type!=="checkbox"&&S.type!=="submit"&&S.type!=="button"&&F?S.value=Lo({type:S.type,tagName:C,value:F,maskInputOptions:a,maskInputFn:l}):k&&(S.checked=k)}if(C==="option"&&(s.selected&&!a.select?S.selected=!0:delete S.selected),C==="canvas"&&f){if(s.__context==="2d")gv(s)||(S.rr_dataURL=s.toDataURL(h.type,h.quality));else if(!("__context"in s)){var O=s.toDataURL(h.type,h.quality),V=document.createElement("canvas");V.width=s.width,V.height=s.height;var X=V.toDataURL(h.type,h.quality);O!==X&&(S.rr_dataURL=O)}}if(C==="img"&&u){Ui||(Ui=t.createElement("canvas"),ju=Ui.getContext("2d"));var z=s,de=z.crossOrigin;z.crossOrigin="anonymous";var B=function(){try{Ui.width=z.naturalWidth,Ui.height=z.naturalHeight,ju.drawImage(z,0,0),S.rr_dataURL=Ui.toDataURL(h.type,h.quality)}catch(K){console.warn("Cannot inline img src=".concat(z.currentSrc,"! Error: ").concat(K))}de?S.crossOrigin=de:z.removeAttribute("crossorigin")};z.complete&&z.naturalWidth!==0?B():z.onload=B}if((C==="audio"||C==="video")&&(S.rr_mediaState=s.paused?"paused":"played",S.rr_mediaCurrentTime=s.currentTime),_||(s.scrollLeft&&(S.rr_scrollLeft=s.scrollLeft),s.scrollTop&&(S.rr_scrollTop=s.scrollTop)),x){var U=s.getBoundingClientRect(),q=U.width,N=U.height;S={class:S.class,rr_width:"".concat(q,"px"),rr_height:"".concat(N,"px")}}return C==="iframe"&&!d(S.src)&&(s.contentDocument||(S.rr_src=S.src),delete S.src),{type:We.Element,tagName:C,attributes:S,childNodes:[],isSVG:Iv(s)||void 0,needBlock:x,rootId:b}}function ve(s){return s===void 0?"":s.toLowerCase()}function Nv(s,e){if(e.comment&&s.type===We.Comment)return!0;if(s.type===We.Element){if(e.script&&(s.tagName==="script"||s.tagName==="link"&&s.attributes.rel==="preload"&&s.attributes.as==="script"||s.tagName==="link"&&s.attributes.rel==="prefetch"&&typeof s.attributes.href=="string"&&s.attributes.href.endsWith(".js")))return!0;if(e.headFavicon&&(s.tagName==="link"&&s.attributes.rel==="shortcut icon"||s.tagName==="meta"&&(ve(s.attributes.name).match(/^msapplication-tile(image|color)$/)||ve(s.attributes.name)==="application-name"||ve(s.attributes.rel)==="icon"||ve(s.attributes.rel)==="apple-touch-icon"||ve(s.attributes.rel)==="shortcut icon")))return!0;if(s.tagName==="meta"){if(e.headMetaDescKeywords&&ve(s.attributes.name).match(/^description|keywords$/))return!0;if(e.headMetaSocial&&(ve(s.attributes.property).match(/^(og|twitter|fb):/)||ve(s.attributes.name).match(/^(og|twitter):/)||ve(s.attributes.name)==="pinterest"))return!0;if(e.headMetaRobots&&(ve(s.attributes.name)==="robots"||ve(s.attributes.name)==="googlebot"||ve(s.attributes.name)==="bingbot"))return!0;if(e.headMetaHttpEquiv&&s.attributes["http-equiv"]!==void 0)return!0;if(e.headMetaAuthorship&&(ve(s.attributes.name)==="author"||ve(s.attributes.name)==="generator"||ve(s.attributes.name)==="framework"||ve(s.attributes.name)==="publisher"||ve(s.attributes.name)==="progid"||ve(s.attributes.property).match(/^article:/)||ve(s.attributes.property).match(/^product:/)))return!0;if(e.headMetaVerification&&(ve(s.attributes.name)==="google-site-verification"||ve(s.attributes.name)==="yandex-verification"||ve(s.attributes.name)==="csrf-token"||ve(s.attributes.name)==="p:domain_verify"||ve(s.attributes.name)==="verify-v1"||ve(s.attributes.name)==="verification"||ve(s.attributes.name)==="shopify-checkout-api-token"))return!0}}return!1}function Gi(s,e){var t=e.doc,i=e.mirror,r=e.blockClass,n=e.blockSelector,o=e.maskTextClass,a=e.maskTextSelector,l=e.skipChild,c=l===void 0?!1:l,h=e.inlineStylesheet,u=h===void 0?!0:h,f=e.maskInputOptions,d=f===void 0?{}:f,g=e.maskTextFn,_=e.maskInputFn,b=e.slimDOMOptions,x=e.dataURLOptions,C=x===void 0?{}:x,S=e.inlineImages,E=S===void 0?!1:S,w=e.recordCanvas,R=w===void 0?!1:w,M=e.onSerialize,D=e.onIframeLoad,F=e.iframeLoadTimeout,k=F===void 0?5e3:F,O=e.onStylesheetLoad,V=e.stylesheetLoadTimeout,X=V===void 0?5e3:V,z=e.keepIframeSrcFn,de=z===void 0?function(){return!1}:z,B=e.newlyAddedElement,U=B===void 0?!1:B,q=e.preserveWhiteSpace,N=q===void 0?!0:q,K=kv(s,{doc:t,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,dataURLOptions:C,inlineImages:E,recordCanvas:R,keepIframeSrcFn:de,newlyAddedElement:U});if(!K)return console.warn(s,"not serialized"),null;var Z;i.hasNode(s)?Z=i.getId(s):Nv(K,b)||!N&&K.type===We.Text&&!K.isStyle&&!K.textContent.replace(/^\s+|\s+$/gm,"").length?Z=As:Z=$u();var $=Object.assign(K,{id:Z});if(i.add(s,$),Z===As)return null;M&&M(s);var ae=!c;if($.type===We.Element){ae=ae&&!$.needBlock,delete $.needBlock;var Ce=s.shadowRoot;Ce&&Ts(Ce)&&($.isShadowHost=!0)}if(($.type===We.Document||$.type===We.Element)&&ae){b.headWhitespace&&$.type===We.Element&&$.tagName==="head"&&(N=!1);for(var Ee={doc:t,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:c,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:b,dataURLOptions:C,inlineImages:E,recordCanvas:R,preserveWhiteSpace:N,onSerialize:M,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:X,keepIframeSrcFn:de},G=0,fe=Array.from(s.childNodes);G<fe.length;G++){var le=fe[G],L=Gi(le,Ee);L&&$.childNodes.push(L)}if(dv(s)&&s.shadowRoot)for(var me=0,Y=Array.from(s.shadowRoot.childNodes);me<Y.length;me++){var le=Y[me],L=Gi(le,Ee);L&&(Ts(s.shadowRoot)&&(L.isShadow=!0),$.childNodes.push(L))}}return s.parentNode&&Es(s.parentNode)&&Ts(s.parentNode)&&($.isShadow=!0),$.type===We.Element&&$.tagName==="iframe"&&Mv(s,function(){var ie=s.contentDocument;if(ie&&D){var we=Gi(ie,{doc:ie,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:b,dataURLOptions:C,inlineImages:E,recordCanvas:R,preserveWhiteSpace:N,onSerialize:M,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:X,keepIframeSrcFn:de});we&&D(s,we)}},k),$.type===We.Element&&$.tagName==="link"&&$.attributes.rel==="stylesheet"&&Pv(s,function(){if(O){var ie=Gi(s,{doc:t,mirror:i,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:b,dataURLOptions:C,inlineImages:E,recordCanvas:R,preserveWhiteSpace:N,onSerialize:M,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:X,keepIframeSrcFn:de});ie&&O(s,ie)}},X),$}function Uv(s,e){var t=e||{},i=t.mirror,r=i===void 0?new Vu:i,n=t.blockClass,o=n===void 0?"rr-block":n,a=t.blockSelector,l=a===void 0?null:a,c=t.maskTextClass,h=c===void 0?"rr-mask":c,u=t.maskTextSelector,f=u===void 0?null:u,d=t.inlineStylesheet,g=d===void 0?!0:d,_=t.inlineImages,b=_===void 0?!1:_,x=t.recordCanvas,C=x===void 0?!1:x,S=t.maskAllInputs,E=S===void 0?!1:S,w=t.maskTextFn,R=t.maskInputFn,M=t.slimDOM,D=M===void 0?!1:M,F=t.dataURLOptions,k=t.preserveWhiteSpace,O=t.onSerialize,V=t.onIframeLoad,X=t.iframeLoadTimeout,z=t.onStylesheetLoad,de=t.stylesheetLoadTimeout,B=t.keepIframeSrcFn,U=B===void 0?function(){return!1}:B,q=E===!0?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:E===!1?{password:!0}:E,N=D===!0||D==="all"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:D==="all",headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:D===!1?{}:D;return Gi(s,{doc:s,mirror:r,blockClass:o,blockSelector:l,maskTextClass:h,maskTextSelector:f,skipChild:!1,inlineStylesheet:g,maskInputOptions:q,maskTextFn:w,maskInputFn:R,slimDOMOptions:N,dataURLOptions:F,inlineImages:b,recordCanvas:C,preserveWhiteSpace:k,onSerialize:O,onIframeLoad:V,iframeLoadTimeout:X,onStylesheetLoad:z,stylesheetLoadTimeout:de,keepIframeSrcFn:U,newlyAddedElement:!1})}function Ze(s,e,t=document){const i={capture:!0,passive:!0};return t.addEventListener(s,e,i),()=>t.removeEventListener(s,e,i)}const Li=`Please stop import mirror directly. Instead of that,\r
|
|
957
957
|
now you can use replayer.getMirror() to access the mirror instance of a replayer,\r
|
|
958
958
|
or you can use record.mirror to access the mirror instance during recording.`;let qu={map:{},getId(){return console.error(Li),-1},getNode(){return console.error(Li),null},removeNodeFromMap(){console.error(Li)},has(){return console.error(Li),!1},reset(){console.error(Li)}};typeof window<"u"&&window.Proxy&&window.Reflect&&(qu=new Proxy(qu,{get(s,e,t){return e==="map"&&console.error(Li),Reflect.get(s,e,t)}}));function ws(s,e,t={}){let i=null,r=0;return function(...n){const o=Date.now();!r&&t.leading===!1&&(r=o);const a=e-(o-r),l=this;a<=0||a>e?(i&&(clearTimeout(i),i=null),r=o,s.apply(l,n)):!i&&t.trailing!==!1&&(i=setTimeout(()=>{r=t.leading===!1?0:Date.now(),i=null,s.apply(l,n)},a))}}function vr(s,e,t,i,r=window){const n=r.Object.getOwnPropertyDescriptor(s,e);return r.Object.defineProperty(s,e,i?t:{set(o){setTimeout(()=>{t.set.call(this,o)},0),n&&n.set&&n.set.call(this,o)}}),()=>vr(s,e,n||{},!0)}function Wi(s,e,t){try{if(!(e in s))return()=>{};const i=s[e],r=t(i);return typeof r=="function"&&(r.prototype=r.prototype||{},Object.defineProperties(r,{__rrweb_original__:{enumerable:!1,value:i}})),s[e]=r,()=>{s[e]=i}}catch{return()=>{}}}function Ku(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function Zu(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function Je(s,e,t,i){if(!s)return!1;const r=s.nodeType===s.ELEMENT_NODE?s:s.parentElement;if(!r)return!1;if(typeof e=="string"){if(r.classList.contains(e)||i&&r.closest("."+e)!==null)return!0}else if(xr(r,e,i))return!0;return!!(t&&(s.matches(t)||i&&r.closest(t)!==null))}function Fv(s,e){return e.getId(s)!==-1}function Ho(s,e){return e.getId(s)===As}function Ju(s,e){if(Es(s))return!1;const t=e.getId(s);return e.has(t)?s.parentNode&&s.parentNode.nodeType===s.DOCUMENT_NODE?!1:s.parentNode?Ju(s.parentNode,e):!0:!0}function Qu(s){return!!s.changedTouches}function Gv(s=window){"NodeList"in s&&!s.NodeList.prototype.forEach&&(s.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in s&&!s.DOMTokenList.prototype.forEach&&(s.DOMTokenList.prototype.forEach=Array.prototype.forEach),Node.prototype.contains||(Node.prototype.contains=(...e)=>{let t=e[0];if(!(0 in e))throw new TypeError("1 argument is required");do if(this===t)return!0;while(t=t&&t.parentNode);return!1})}function ed(s,e){return!!(s.nodeName==="IFRAME"&&e.getMeta(s))}function td(s,e){return!!(s.nodeName==="LINK"&&s.nodeType===s.ELEMENT_NODE&&s.getAttribute&&s.getAttribute("rel")==="stylesheet"&&e.getMeta(s))}function id(s){return!!(s!=null&&s.shadowRoot)}class Lv{constructor(){this.id=1,this.styleIDMap=new WeakMap,this.idStyleMap=new Map}getId(e){var t;return(t=this.styleIDMap.get(e))!==null&&t!==void 0?t:-1}has(e){return this.styleIDMap.has(e)}add(e,t){if(this.has(e))return this.getId(e);let i;return t===void 0?i=this.id++:i=t,this.styleIDMap.set(e,i),this.idStyleMap.set(i,e),i}getStyle(e){return this.idStyleMap.get(e)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}}var ue=(s=>(s[s.DomContentLoaded=0]="DomContentLoaded",s[s.Load=1]="Load",s[s.FullSnapshot=2]="FullSnapshot",s[s.IncrementalSnapshot=3]="IncrementalSnapshot",s[s.Meta=4]="Meta",s[s.Custom=5]="Custom",s[s.Plugin=6]="Plugin",s))(ue||{}),oe=(s=>(s[s.Mutation=0]="Mutation",s[s.MouseMove=1]="MouseMove",s[s.MouseInteraction=2]="MouseInteraction",s[s.Scroll=3]="Scroll",s[s.ViewportResize=4]="ViewportResize",s[s.Input=5]="Input",s[s.TouchMove=6]="TouchMove",s[s.MediaInteraction=7]="MediaInteraction",s[s.StyleSheetRule=8]="StyleSheetRule",s[s.CanvasMutation=9]="CanvasMutation",s[s.Font=10]="Font",s[s.Log=11]="Log",s[s.Drag=12]="Drag",s[s.StyleDeclaration=13]="StyleDeclaration",s[s.Selection=14]="Selection",s[s.AdoptedStyleSheet=15]="AdoptedStyleSheet",s))(oe||{}),Vo=(s=>(s[s.MouseUp=0]="MouseUp",s[s.MouseDown=1]="MouseDown",s[s.Click=2]="Click",s[s.ContextMenu=3]="ContextMenu",s[s.DblClick=4]="DblClick",s[s.Focus=5]="Focus",s[s.Blur=6]="Blur",s[s.TouchStart=7]="TouchStart",s[s.TouchMove_Departed=8]="TouchMove_Departed",s[s.TouchEnd=9]="TouchEnd",s[s.TouchCancel=10]="TouchCancel",s))(Vo||{}),Hi=(s=>(s[s["2D"]=0]="2D",s[s.WebGL=1]="WebGL",s[s.WebGL2=2]="WebGL2",s))(Hi||{});function sd(s){return"__ln"in s}class Wv{constructor(){this.length=0,this.head=null}get(e){if(e>=this.length)throw new Error("Position outside of list range");let t=this.head;for(let i=0;i<e;i++)t=(t==null?void 0:t.next)||null;return t}addNode(e){const t={value:e,previous:null,next:null};if(e.__ln=t,e.previousSibling&&sd(e.previousSibling)){const i=e.previousSibling.__ln.next;t.next=i,t.previous=e.previousSibling.__ln,e.previousSibling.__ln.next=t,i&&(i.previous=t)}else if(e.nextSibling&&sd(e.nextSibling)&&e.nextSibling.__ln.previous){const i=e.nextSibling.__ln.previous;t.previous=i,t.next=e.nextSibling.__ln,e.nextSibling.__ln.previous=t,i&&(i.next=t)}else this.head&&(this.head.previous=t),t.next=this.head,this.head=t;this.length++}removeNode(e){const t=e.__ln;this.head&&(t.previous?(t.previous.next=t.next,t.next&&(t.next.previous=t.previous)):(this.head=t.next,this.head&&(this.head.previous=null)),e.__ln&&delete e.__ln,this.length--)}}const rd=(s,e)=>`${s}@${e}`;class Hv{constructor(){this.frozen=!1,this.locked=!1,this.texts=[],this.attributes=[],this.removes=[],this.mapRemoves=[],this.movedMap={},this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.processMutations=e=>{e.forEach(this.processMutation),this.emit()},this.emit=()=>{if(this.frozen||this.locked)return;const e=[],t=new Wv,i=a=>{let l=a,c=As;for(;c===As;)l=l&&l.nextSibling,c=l&&this.mirror.getId(l);return c},r=a=>{var l,c,h,u;let f=null;((c=(l=a.getRootNode)===null||l===void 0?void 0:l.call(a))===null||c===void 0?void 0:c.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&a.getRootNode().host&&(f=a.getRootNode().host);let d=f;for(;((u=(h=d==null?void 0:d.getRootNode)===null||h===void 0?void 0:h.call(d))===null||u===void 0?void 0:u.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&d.getRootNode().host;)d=d.getRootNode().host;const g=!this.doc.contains(a)&&(!d||!this.doc.contains(d));if(!a.parentNode||g)return;const _=Es(a.parentNode)?this.mirror.getId(f):this.mirror.getId(a.parentNode),b=i(a);if(_===-1||b===-1)return t.addNode(a);const x=Gi(a,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskTextClass:this.maskTextClass,maskTextSelector:this.maskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:C=>{ed(C,this.mirror)&&this.iframeManager.addIframe(C),td(C,this.mirror)&&this.stylesheetManager.trackLinkElement(C),id(a)&&this.shadowDomManager.addShadowRoot(a.shadowRoot,this.doc)},onIframeLoad:(C,S)=>{this.iframeManager.attachIframe(C,S),this.shadowDomManager.observeAttachShadow(C)},onStylesheetLoad:(C,S)=>{this.stylesheetManager.attachLinkElement(C,S)}});x&&e.push({parentId:_,nextId:b,node:x})};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const a of Array.from(this.movedSet.values()))nd(this.removes,a,this.mirror)&&!this.movedSet.has(a.parentNode)||r(a);for(const a of Array.from(this.addedSet.values()))!ad(this.droppedSet,a)&&!nd(this.removes,a,this.mirror)||ad(this.movedSet,a)?r(a):this.droppedSet.add(a);let n=null;for(;t.length;){let a=null;if(n){const l=this.mirror.getId(n.value.parentNode),c=i(n.value);l!==-1&&c!==-1&&(a=n)}if(!a)for(let l=t.length-1;l>=0;l--){const c=t.get(l);if(c){const h=this.mirror.getId(c.value.parentNode);if(i(c.value)===-1)continue;if(h!==-1){a=c;break}else{const f=c.value;if(f.parentNode&&f.parentNode.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const d=f.parentNode.host;if(this.mirror.getId(d)!==-1){a=c;break}}}}}if(!a){for(;t.head;)t.removeNode(t.head.value);break}n=a.previous,t.removeNode(a.value),r(a.value)}const o={texts:this.texts.map(a=>({id:this.mirror.getId(a.node),value:a.value})).filter(a=>this.mirror.has(a.id)),attributes:this.attributes.map(a=>({id:this.mirror.getId(a.node),attributes:a.attributes})).filter(a=>this.mirror.has(a.id)),removes:this.removes,adds:e};!o.texts.length&&!o.attributes.length&&!o.removes.length&&!o.adds.length||(this.texts=[],this.attributes=[],this.removes=[],this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.movedMap={},this.mutationCb(o))},this.processMutation=e=>{if(!Ho(e.target,this.mirror))switch(e.type){case"characterData":{const t=e.target.textContent;!Je(e.target,this.blockClass,this.blockSelector,!1)&&t!==e.oldValue&&this.texts.push({value:Yu(e.target,this.maskTextClass,this.maskTextSelector)&&t?this.maskTextFn?this.maskTextFn(t):t.replace(/[\S]/g,"*"):t,node:e.target});break}case"attributes":{const t=e.target;let i=e.target.getAttribute(e.attributeName);if(e.attributeName==="value"&&(i=Lo({maskInputOptions:this.maskInputOptions,tagName:e.target.tagName,type:e.target.getAttribute("type"),value:i,maskInputFn:this.maskInputFn})),Je(e.target,this.blockClass,this.blockSelector,!1)||i===e.oldValue)return;let r=this.attributes.find(n=>n.node===e.target);if(t.tagName==="IFRAME"&&e.attributeName==="src"&&!this.keepIframeSrcFn(i))if(!t.contentDocument)e.attributeName="rr_src";else return;if(r||(r={node:e.target,attributes:{}},this.attributes.push(r)),e.attributeName==="style"){const n=this.doc.createElement("span");e.oldValue&&n.setAttribute("style",e.oldValue),(r.attributes.style===void 0||r.attributes.style===null)&&(r.attributes.style={});const o=r.attributes.style;for(const a of Array.from(t.style)){const l=t.style.getPropertyValue(a),c=t.style.getPropertyPriority(a);(l!==n.style.getPropertyValue(a)||c!==n.style.getPropertyPriority(a))&&(c===""?o[a]=l:o[a]=[l,c])}for(const a of Array.from(n.style))t.style.getPropertyValue(a)===""&&(o[a]=!1)}else r.attributes[e.attributeName]=Xu(this.doc,t.tagName,e.attributeName,i);break}case"childList":{if(Je(e.target,this.blockClass,this.blockSelector,!0))return;e.addedNodes.forEach(t=>this.genAdds(t,e.target)),e.removedNodes.forEach(t=>{const i=this.mirror.getId(t),r=Es(e.target)?this.mirror.getId(e.target.host):this.mirror.getId(e.target);Je(e.target,this.blockClass,this.blockSelector,!1)||Ho(t,this.mirror)||!Fv(t,this.mirror)||(this.addedSet.has(t)?(zo(this.addedSet,t),this.droppedSet.add(t)):this.addedSet.has(e.target)&&i===-1||Ju(e.target,this.mirror)||(this.movedSet.has(t)&&this.movedMap[rd(i,r)]?zo(this.movedSet,t):this.removes.push({parentId:r,id:i,isShadow:Es(e.target)&&Ts(e.target)?!0:void 0})),this.mapRemoves.push(t))});break}}},this.genAdds=(e,t)=>{if(this.mirror.hasNode(e)){if(Ho(e,this.mirror))return;this.movedSet.add(e);let i=null;t&&this.mirror.hasNode(t)&&(i=this.mirror.getId(t)),i&&i!==-1&&(this.movedMap[rd(this.mirror.getId(e),i)]=!0)}else this.addedSet.add(e),this.droppedSet.delete(e);Je(e,this.blockClass,this.blockSelector,!1)||e.childNodes.forEach(i=>this.genAdds(i))}}init(e){["mutationCb","blockClass","blockSelector","maskTextClass","maskTextSelector","inlineStylesheet","maskInputOptions","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager"].forEach(t=>{this[t]=e[t]})}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}}function zo(s,e){s.delete(e),e.childNodes.forEach(t=>zo(s,t))}function nd(s,e,t){return s.length===0?!1:od(s,e,t)}function od(s,e,t){const{parentNode:i}=e;if(!i)return!1;const r=t.getId(i);return s.some(n=>n.id===r)?!0:od(s,i,t)}function ad(s,e){return s.size===0?!1:ld(s,e)}function ld(s,e){const{parentNode:t}=e;return t?s.has(t)?!0:ld(s,t):!1}const ci=[],cd=typeof CSSGroupingRule<"u",hd=typeof CSSMediaRule<"u",ud=typeof CSSSupportsRule<"u",dd=typeof CSSConditionRule<"u";function Is(s){try{if("composedPath"in s){const e=s.composedPath();if(e.length)return e[0]}else if("path"in s&&s.path.length)return s.path[0];return s.target}catch{return s.target}}function fd(s,e){var t,i;const r=new Hv;ci.push(r),r.init(s);let n=window.MutationObserver||window.__rrMutationObserver;const o=(i=(t=window==null?void 0:window.Zone)===null||t===void 0?void 0:t.__symbol__)===null||i===void 0?void 0:i.call(t,"MutationObserver");o&&window[o]&&(n=window[o]);const a=new n(r.processMutations.bind(r));return a.observe(e,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),a}function Vv({mousemoveCb:s,sampling:e,doc:t,mirror:i}){if(e.mousemove===!1)return()=>{};const r=typeof e.mousemove=="number"?e.mousemove:50,n=typeof e.mousemoveCallback=="number"?e.mousemoveCallback:500;let o=[],a;const l=ws(u=>{const f=Date.now()-a;s(o.map(d=>(d.timeOffset-=f,d)),u),o=[],a=null},n),c=ws(u=>{const f=Is(u),{clientX:d,clientY:g}=Qu(u)?u.changedTouches[0]:u;a||(a=Date.now()),o.push({x:d,y:g,id:i.getId(f),timeOffset:Date.now()-a}),l(typeof DragEvent<"u"&&u instanceof DragEvent?oe.Drag:u instanceof MouseEvent?oe.MouseMove:oe.TouchMove)},r,{trailing:!1}),h=[Ze("mousemove",c,t),Ze("touchmove",c,t),Ze("drag",c,t)];return()=>{h.forEach(u=>u())}}function zv({mouseInteractionCb:s,doc:e,mirror:t,blockClass:i,blockSelector:r,sampling:n}){if(n.mouseInteraction===!1)return()=>{};const o=n.mouseInteraction===!0||n.mouseInteraction===void 0?{}:n.mouseInteraction,a=[],l=c=>h=>{const u=Is(h);if(Je(u,i,r,!0))return;const f=Qu(h)?h.changedTouches[0]:h;if(!f)return;const d=t.getId(u),{clientX:g,clientY:_}=f;s({type:Vo[c],id:d,x:g,y:_})};return Object.keys(Vo).filter(c=>Number.isNaN(Number(c))&&!c.endsWith("_Departed")&&o[c]!==!1).forEach(c=>{const h=c.toLowerCase(),u=l(c);a.push(Ze(h,u,e))}),()=>{a.forEach(c=>c())}}function pd({scrollCb:s,doc:e,mirror:t,blockClass:i,blockSelector:r,sampling:n}){const o=ws(a=>{const l=Is(a);if(!l||Je(l,i,r,!0))return;const c=t.getId(l);if(l===e){const h=e.scrollingElement||e.documentElement;s({id:c,x:h.scrollLeft,y:h.scrollTop})}else s({id:c,x:l.scrollLeft,y:l.scrollTop})},n.scroll||100);return Ze("scroll",o,e)}function $v({viewportResizeCb:s}){let e=-1,t=-1;const i=ws(()=>{const r=Ku(),n=Zu();(e!==r||t!==n)&&(s({width:Number(n),height:Number(r)}),e=r,t=n)},200);return Ze("resize",i,window)}function md(s,e){const t=Object.assign({},s);return e||delete t.userTriggered,t}const jv=["INPUT","TEXTAREA","SELECT"],gd=new WeakMap;function Xv({inputCb:s,doc:e,mirror:t,blockClass:i,blockSelector:r,ignoreClass:n,maskInputOptions:o,maskInputFn:a,sampling:l,userTriggeredOnInput:c}){function h(x){let C=Is(x);const S=x.isTrusted;if(C&&C.tagName==="OPTION"&&(C=C.parentElement),!C||!C.tagName||jv.indexOf(C.tagName)<0||Je(C,i,r,!0))return;const E=C.type;if(C.classList.contains(n))return;let w=C.value,R=!1;E==="radio"||E==="checkbox"?R=C.checked:(o[C.tagName.toLowerCase()]||o[E])&&(w=Lo({maskInputOptions:o,tagName:C.tagName,type:E,value:w,maskInputFn:a})),u(C,md({text:w,isChecked:R,userTriggered:S},c));const M=C.name;E==="radio"&&M&&R&&e.querySelectorAll(`input[type="radio"][name="${M}"]`).forEach(D=>{D!==C&&u(D,md({text:D.value,isChecked:!R,userTriggered:!1},c))})}function u(x,C){const S=gd.get(x);if(!S||S.text!==C.text||S.isChecked!==C.isChecked){gd.set(x,C);const E=t.getId(x);s(Object.assign(Object.assign({},C),{id:E}))}}const d=(l.input==="last"?["change"]:["input","change"]).map(x=>Ze(x,h,e)),g=e.defaultView;if(!g)return()=>{d.forEach(x=>x())};const _=g.Object.getOwnPropertyDescriptor(g.HTMLInputElement.prototype,"value"),b=[[g.HTMLInputElement.prototype,"value"],[g.HTMLInputElement.prototype,"checked"],[g.HTMLSelectElement.prototype,"value"],[g.HTMLTextAreaElement.prototype,"value"],[g.HTMLSelectElement.prototype,"selectedIndex"],[g.HTMLOptionElement.prototype,"selected"]];return _&&_.set&&d.push(...b.map(x=>vr(x[0],x[1],{set(){h({target:this})}},!1,g))),()=>{d.forEach(x=>x())}}function Cr(s){const e=[];function t(i,r){if(cd&&i.parentRule instanceof CSSGroupingRule||hd&&i.parentRule instanceof CSSMediaRule||ud&&i.parentRule instanceof CSSSupportsRule||dd&&i.parentRule instanceof CSSConditionRule){const o=Array.from(i.parentRule.cssRules).indexOf(i);r.unshift(o)}else if(i.parentStyleSheet){const o=Array.from(i.parentStyleSheet.cssRules).indexOf(i);r.unshift(o)}return r}return t(s,e)}function qt(s,e,t){let i,r;return s?(s.ownerNode?i=e.getId(s.ownerNode):r=t.getId(s),{styleId:r,id:i}):{}}function Yv({styleSheetRuleCb:s,mirror:e,stylesheetManager:t},{win:i}){const r=i.CSSStyleSheet.prototype.insertRule;i.CSSStyleSheet.prototype.insertRule=function(h,u){const{id:f,styleId:d}=qt(this,e,t.styleMirror);return(f&&f!==-1||d&&d!==-1)&&s({id:f,styleId:d,adds:[{rule:h,index:u}]}),r.apply(this,[h,u])};const n=i.CSSStyleSheet.prototype.deleteRule;i.CSSStyleSheet.prototype.deleteRule=function(h){const{id:u,styleId:f}=qt(this,e,t.styleMirror);return(u&&u!==-1||f&&f!==-1)&&s({id:u,styleId:f,removes:[{index:h}]}),n.apply(this,[h])};let o;i.CSSStyleSheet.prototype.replace&&(o=i.CSSStyleSheet.prototype.replace,i.CSSStyleSheet.prototype.replace=function(h){const{id:u,styleId:f}=qt(this,e,t.styleMirror);return(u&&u!==-1||f&&f!==-1)&&s({id:u,styleId:f,replace:h}),o.apply(this,[h])});let a;i.CSSStyleSheet.prototype.replaceSync&&(a=i.CSSStyleSheet.prototype.replaceSync,i.CSSStyleSheet.prototype.replaceSync=function(h){const{id:u,styleId:f}=qt(this,e,t.styleMirror);return(u&&u!==-1||f&&f!==-1)&&s({id:u,styleId:f,replaceSync:h}),a.apply(this,[h])});const l={};cd?l.CSSGroupingRule=i.CSSGroupingRule:(hd&&(l.CSSMediaRule=i.CSSMediaRule),dd&&(l.CSSConditionRule=i.CSSConditionRule),ud&&(l.CSSSupportsRule=i.CSSSupportsRule));const c={};return Object.entries(l).forEach(([h,u])=>{c[h]={insertRule:u.prototype.insertRule,deleteRule:u.prototype.deleteRule},u.prototype.insertRule=function(f,d){const{id:g,styleId:_}=qt(this.parentStyleSheet,e,t.styleMirror);return(g&&g!==-1||_&&_!==-1)&&s({id:g,styleId:_,adds:[{rule:f,index:[...Cr(this),d||0]}]}),c[h].insertRule.apply(this,[f,d])},u.prototype.deleteRule=function(f){const{id:d,styleId:g}=qt(this.parentStyleSheet,e,t.styleMirror);return(d&&d!==-1||g&&g!==-1)&&s({id:d,styleId:g,removes:[{index:[...Cr(this),f]}]}),c[h].deleteRule.apply(this,[f])}}),()=>{i.CSSStyleSheet.prototype.insertRule=r,i.CSSStyleSheet.prototype.deleteRule=n,o&&(i.CSSStyleSheet.prototype.replace=o),a&&(i.CSSStyleSheet.prototype.replaceSync=a),Object.entries(l).forEach(([h,u])=>{u.prototype.insertRule=c[h].insertRule,u.prototype.deleteRule=c[h].deleteRule})}}function _d({mirror:s,stylesheetManager:e},t){var i,r,n;let o=null;t.nodeName==="#document"?o=s.getId(t):o=s.getId(t.host);const a=t.nodeName==="#document"?(i=t.defaultView)===null||i===void 0?void 0:i.Document:(n=(r=t.ownerDocument)===null||r===void 0?void 0:r.defaultView)===null||n===void 0?void 0:n.ShadowRoot,l=Object.getOwnPropertyDescriptor(a==null?void 0:a.prototype,"adoptedStyleSheets");return o===null||o===-1||!a||!l?()=>{}:(Object.defineProperty(t,"adoptedStyleSheets",{configurable:l.configurable,enumerable:l.enumerable,get(){var c;return(c=l.get)===null||c===void 0?void 0:c.call(this)},set(c){var h;const u=(h=l.set)===null||h===void 0?void 0:h.call(this,c);if(o!==null&&o!==-1)try{e.adoptStyleSheets(c,o)}catch{}return u}}),()=>{Object.defineProperty(t,"adoptedStyleSheets",{configurable:l.configurable,enumerable:l.enumerable,get:l.get,set:l.set})})}function qv({styleDeclarationCb:s,mirror:e,ignoreCSSAttributes:t,stylesheetManager:i},{win:r}){const n=r.CSSStyleDeclaration.prototype.setProperty;r.CSSStyleDeclaration.prototype.setProperty=function(a,l,c){var h;if(t.has(a))return n.apply(this,[a,l,c]);const{id:u,styleId:f}=qt((h=this.parentRule)===null||h===void 0?void 0:h.parentStyleSheet,e,i.styleMirror);return(u&&u!==-1||f&&f!==-1)&&s({id:u,styleId:f,set:{property:a,value:l,priority:c},index:Cr(this.parentRule)}),n.apply(this,[a,l,c])};const o=r.CSSStyleDeclaration.prototype.removeProperty;return r.CSSStyleDeclaration.prototype.removeProperty=function(a){var l;if(t.has(a))return o.apply(this,[a]);const{id:c,styleId:h}=qt((l=this.parentRule)===null||l===void 0?void 0:l.parentStyleSheet,e,i.styleMirror);return(c&&c!==-1||h&&h!==-1)&&s({id:c,styleId:h,remove:{property:a},index:Cr(this.parentRule)}),o.apply(this,[a])},()=>{r.CSSStyleDeclaration.prototype.setProperty=n,r.CSSStyleDeclaration.prototype.removeProperty=o}}function Kv({mediaInteractionCb:s,blockClass:e,blockSelector:t,mirror:i,sampling:r}){const n=a=>ws(l=>{const c=Is(l);if(!c||Je(c,e,t,!0))return;const{currentTime:h,volume:u,muted:f,playbackRate:d}=c;s({type:a,id:i.getId(c),currentTime:h,volume:u,muted:f,playbackRate:d})},r.media||500),o=[Ze("play",n(0)),Ze("pause",n(1)),Ze("seeked",n(2)),Ze("volumechange",n(3)),Ze("ratechange",n(4))];return()=>{o.forEach(a=>a())}}function Zv({fontCb:s,doc:e}){const t=e.defaultView;if(!t)return()=>{};const i=[],r=new WeakMap,n=t.FontFace;t.FontFace=function(l,c,h){const u=new n(l,c,h);return r.set(u,{family:l,buffer:typeof c!="string",descriptors:h,fontSource:typeof c=="string"?c:JSON.stringify(Array.from(new Uint8Array(c)))}),u};const o=Wi(e.fonts,"add",function(a){return function(l){return setTimeout(()=>{const c=r.get(l);c&&(s(c),r.delete(l))},0),a.apply(this,[l])}});return i.push(()=>{t.FontFace=n}),i.push(o),()=>{i.forEach(a=>a())}}function Jv(s){const{doc:e,mirror:t,blockClass:i,blockSelector:r,selectionCb:n}=s;let o=!0;const a=()=>{const l=e.getSelection();if(!l||o&&(l!=null&&l.isCollapsed))return;o=l.isCollapsed||!1;const c=[],h=l.rangeCount||0;for(let u=0;u<h;u++){const f=l.getRangeAt(u),{startContainer:d,startOffset:g,endContainer:_,endOffset:b}=f;Je(d,i,r,!0)||Je(_,i,r,!0)||c.push({start:t.getId(d),startOffset:g,end:t.getId(_),endOffset:b})}n({ranges:c})};return a(),Ze("selectionchange",a)}function Qv(s,e){const{mutationCb:t,mousemoveCb:i,mouseInteractionCb:r,scrollCb:n,viewportResizeCb:o,inputCb:a,mediaInteractionCb:l,styleSheetRuleCb:c,styleDeclarationCb:h,canvasMutationCb:u,fontCb:f,selectionCb:d}=s;s.mutationCb=(...g)=>{e.mutation&&e.mutation(...g),t(...g)},s.mousemoveCb=(...g)=>{e.mousemove&&e.mousemove(...g),i(...g)},s.mouseInteractionCb=(...g)=>{e.mouseInteraction&&e.mouseInteraction(...g),r(...g)},s.scrollCb=(...g)=>{e.scroll&&e.scroll(...g),n(...g)},s.viewportResizeCb=(...g)=>{e.viewportResize&&e.viewportResize(...g),o(...g)},s.inputCb=(...g)=>{e.input&&e.input(...g),a(...g)},s.mediaInteractionCb=(...g)=>{e.mediaInteaction&&e.mediaInteaction(...g),l(...g)},s.styleSheetRuleCb=(...g)=>{e.styleSheetRule&&e.styleSheetRule(...g),c(...g)},s.styleDeclarationCb=(...g)=>{e.styleDeclaration&&e.styleDeclaration(...g),h(...g)},s.canvasMutationCb=(...g)=>{e.canvasMutation&&e.canvasMutation(...g),u(...g)},s.fontCb=(...g)=>{e.font&&e.font(...g),f(...g)},s.selectionCb=(...g)=>{e.selection&&e.selection(...g),d(...g)}}function e0(s,e={}){const t=s.doc.defaultView;if(!t)return()=>{};Qv(s,e);const i=fd(s,s.doc),r=Vv(s),n=zv(s),o=pd(s),a=$v(s),l=Xv(s),c=Kv(s),h=Yv(s,{win:t}),u=_d(s,s.doc),f=qv(s,{win:t}),d=s.collectFonts?Zv(s):()=>{},g=Jv(s),_=[];for(const b of s.plugins)_.push(b.observer(b.callback,t,b.options));return()=>{ci.forEach(b=>b.reset()),i.disconnect(),r(),n(),o(),a(),l(),c(),h(),u(),f(),d(),g(),_.forEach(b=>b())}}class yd{constructor(e){this.generateIdFn=e,this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap}getId(e,t,i,r){const n=i||this.getIdToRemoteIdMap(e),o=r||this.getRemoteIdToIdMap(e);let a=n.get(t);return a||(a=this.generateIdFn(),n.set(t,a),o.set(a,t)),a}getIds(e,t){const i=this.getIdToRemoteIdMap(e),r=this.getRemoteIdToIdMap(e);return t.map(n=>this.getId(e,n,i,r))}getRemoteId(e,t,i){const r=i||this.getRemoteIdToIdMap(e);if(typeof t!="number")return t;const n=r.get(t);return n||-1}getRemoteIds(e,t){const i=this.getRemoteIdToIdMap(e);return t.map(r=>this.getRemoteId(e,r,i))}reset(e){if(!e){this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap;return}this.iframeIdToRemoteIdMap.delete(e),this.iframeRemoteIdToIdMap.delete(e)}getIdToRemoteIdMap(e){let t=this.iframeIdToRemoteIdMap.get(e);return t||(t=new Map,this.iframeIdToRemoteIdMap.set(e,t)),t}getRemoteIdToIdMap(e){let t=this.iframeRemoteIdToIdMap.get(e);return t||(t=new Map,this.iframeRemoteIdToIdMap.set(e,t)),t}}class t0{constructor(e){this.iframes=new WeakMap,this.crossOriginIframeMap=new WeakMap,this.crossOriginIframeMirror=new yd($u),this.mutationCb=e.mutationCb,this.wrappedEmit=e.wrappedEmit,this.stylesheetManager=e.stylesheetManager,this.recordCrossOriginIframes=e.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new yd(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=e.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}addIframe(e){this.iframes.set(e,!0),e.contentWindow&&this.crossOriginIframeMap.set(e.contentWindow,e)}addLoadListener(e){this.loadListener=e}attachIframe(e,t){var i;this.mutationCb({adds:[{parentId:this.mirror.getId(e),nextId:null,node:t}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),(i=this.loadListener)===null||i===void 0||i.call(this,e),e.contentDocument&&e.contentDocument.adoptedStyleSheets&&e.contentDocument.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(e.contentDocument.adoptedStyleSheets,this.mirror.getId(e.contentDocument))}handleMessage(e){if(e.data.type==="rrweb"){if(!e.source)return;const i=this.crossOriginIframeMap.get(e.source);if(!i)return;const r=this.transformCrossOriginEvent(i,e.data.event);r&&this.wrappedEmit(r,e.data.isCheckout)}}transformCrossOriginEvent(e,t){var i;switch(t.type){case ue.FullSnapshot:return this.crossOriginIframeMirror.reset(e),this.crossOriginIframeStyleMirror.reset(e),this.replaceIdOnNode(t.data.node,e),{timestamp:t.timestamp,type:ue.IncrementalSnapshot,data:{source:oe.Mutation,adds:[{parentId:this.mirror.getId(e),nextId:null,node:t.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}};case ue.Meta:case ue.Load:case ue.DomContentLoaded:return!1;case ue.Plugin:return t;case ue.Custom:return this.replaceIds(t.data.payload,e,["id","parentId","previousId","nextId"]),t;case ue.IncrementalSnapshot:switch(t.data.source){case oe.Mutation:return t.data.adds.forEach(r=>{this.replaceIds(r,e,["parentId","nextId","previousId"]),this.replaceIdOnNode(r.node,e)}),t.data.removes.forEach(r=>{this.replaceIds(r,e,["parentId","id"])}),t.data.attributes.forEach(r=>{this.replaceIds(r,e,["id"])}),t.data.texts.forEach(r=>{this.replaceIds(r,e,["id"])}),t;case oe.Drag:case oe.TouchMove:case oe.MouseMove:return t.data.positions.forEach(r=>{this.replaceIds(r,e,["id"])}),t;case oe.ViewportResize:return!1;case oe.MediaInteraction:case oe.MouseInteraction:case oe.Scroll:case oe.CanvasMutation:case oe.Input:return this.replaceIds(t.data,e,["id"]),t;case oe.StyleSheetRule:case oe.StyleDeclaration:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleId"]),t;case oe.Font:return t;case oe.Selection:return t.data.ranges.forEach(r=>{this.replaceIds(r,e,["start","end"])}),t;case oe.AdoptedStyleSheet:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleIds"]),(i=t.data.styles)===null||i===void 0||i.forEach(r=>{this.replaceStyleIds(r,e,["styleId"])}),t}}}replace(e,t,i,r){for(const n of r)!Array.isArray(t[n])&&typeof t[n]!="number"||(Array.isArray(t[n])?t[n]=e.getIds(i,t[n]):t[n]=e.getId(i,t[n]));return t}replaceIds(e,t,i){return this.replace(this.crossOriginIframeMirror,e,t,i)}replaceStyleIds(e,t,i){return this.replace(this.crossOriginIframeStyleMirror,e,t,i)}replaceIdOnNode(e,t){this.replaceIds(e,t,["id"]),"childNodes"in e&&e.childNodes.forEach(i=>{this.replaceIdOnNode(i,t)})}}class i0{constructor(e){this.shadowDoms=new WeakSet,this.restorePatches=[],this.mutationCb=e.mutationCb,this.scrollCb=e.scrollCb,this.bypassOptions=e.bypassOptions,this.mirror=e.mirror;const t=this;this.restorePatches.push(Wi(Element.prototype,"attachShadow",function(i){return function(r){const n=i.call(this,r);return this.shadowRoot&&t.addShadowRoot(this.shadowRoot,this.ownerDocument),n}}))}addShadowRoot(e,t){Ts(e)&&(this.shadowDoms.has(e)||(this.shadowDoms.add(e),fd(Object.assign(Object.assign({},this.bypassOptions),{doc:t,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this}),e),pd(Object.assign(Object.assign({},this.bypassOptions),{scrollCb:this.scrollCb,doc:e,mirror:this.mirror})),setTimeout(()=>{e.adoptedStyleSheets&&e.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(e.adoptedStyleSheets,this.mirror.getId(e.host)),_d({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},e)},0)))}observeAttachShadow(e){if(e.contentWindow){const t=this;this.restorePatches.push(Wi(e.contentWindow.HTMLElement.prototype,"attachShadow",function(i){return function(r){const n=i.call(this,r);return this.shadowRoot&&t.addShadowRoot(this.shadowRoot,e.contentDocument),n}}))}}reset(){this.restorePatches.forEach(e=>e()),this.shadowDoms=new WeakSet}}/*! *****************************************************************************
|
|
959
959
|
Copyright (c) Microsoft Corporation.
|
|
@@ -1056,12 +1056,12 @@ Continue the conversation naturally from this context.`,i=e.actionId;this.cleanu
|
|
|
1056
1056
|
0%, 100% { box-shadow: 0 0 0 0 var(--hs-accent-glow); }
|
|
1057
1057
|
50% { box-shadow: 0 0 14px 5px var(--hs-accent-glow); }
|
|
1058
1058
|
}
|
|
1059
|
-
`;class of{constructor(){this.el=null,this.avatarWrap=null,this.avatarImg=null,this.avatarVideo=null,this.nameEl=null,this.suggestionArea=null,this.suggestionText=null,this.currentAnim=null,this._state="hidden",this.pulseStyleInjected=!1,this.avatarUrl=null,this.videoUrl=null,this.staffName="",this.onClick=null,this.onSuggestionAccept=null,this.onSuggestionDismiss=null}init(e,t,i){if(this.el)return;if(St(),this.avatarUrl=e,this.videoUrl=t,this.staffName=i,this.el=Kt({radius:"pill",elevation:"elevated",interactive:!0,className:"hs-chat-pill"}),Object.assign(this.el.style,{position:"fixed",bottom:"var(--hs-space-5)",left:"0",right:"0",margin:"0 auto",width:"fit-content",maxWidth:"min(90vw, 600px)",display:"none",alignItems:"center",gap:"0px",padding:"5px",zIndex:W.zControls,cursor:"pointer",userSelect:"none",opacity:"0",boxShadow:"0 4px 24px rgba(0, 0, 0, 0.18)",transition:"gap 0.3s ease, padding 0.3s ease, box-shadow 0.2s ease",overflow:"hidden"}),$i(this.el),this.el.addEventListener("mouseenter",()=>{this.el&&(this.el.style.boxShadow="0 6px 32px rgba(0, 0, 0, 0.24)")}),this.el.addEventListener("mouseleave",()=>{this.el&&(this.el.style.boxShadow="0 4px 24px rgba(0, 0, 0, 0.18)")}),this.avatarWrap=document.createElement("div"),Object.assign(this.avatarWrap.style,{width:"36px",height:"36px",borderRadius:"50%",overflow:"hidden",flexShrink:"0",position:"relative",border:"1.5px solid var(--hs-glass-border)",transition:"box-shadow 0.3s ease, width 0.3s ease, height 0.3s ease"}),e)this.avatarImg=document.createElement("img"),this.avatarImg.src=e,this.avatarImg.alt=i,Object.assign(this.avatarImg.style,{width:"100%",height:"100%",objectFit:"cover",display:"block"}),this.avatarWrap.appendChild(this.avatarImg);else{const a=document.createElement("div");Object.assign(a.style,{width:"100%",height:"100%",background:"var(--hs-accent)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"var(--hs-text-sm)",fontWeight:"var(--hs-weight-semibold)",color:"var(--hs-accent-text)"}),a.textContent=i.charAt(0).toUpperCase(),this.avatarWrap.appendChild(a)}t&&(this.avatarVideo=document.createElement("video"),this.avatarVideo.src=t,this.avatarVideo.muted=!0,this.avatarVideo.loop=!0,this.avatarVideo.playsInline=!0,this.avatarVideo.setAttribute("playsinline",""),Object.assign(this.avatarVideo.style,{position:"absolute",inset:"0",width:"100%",height:"100%",objectFit:"cover",display:"none"}),this.avatarWrap.appendChild(this.avatarVideo)),this.el.appendChild(this.avatarWrap),this.nameEl=document.createElement("span"),vt(this.nameEl,"primary","base","medium"),this.nameEl.textContent=i,Object.assign(this.nameEl.style,{whiteSpace:"nowrap",overflow:"hidden",maxWidth:"0",opacity:"0",transition:"max-width 0.3s ease, opacity 0.25s ease, margin 0.3s ease",marginLeft:"0"}),this.el.appendChild(this.nameEl),this.suggestionArea=document.createElement("div"),Object.assign(this.suggestionArea.style,{display:"flex",alignItems:"center",gap:"var(--hs-space-2)",maxWidth:"0",opacity:"0",overflow:"hidden",transition:"max-width 0.35s ease, opacity 0.25s ease, margin 0.3s ease",marginLeft:"0"});const r=document.createElement("span");Object.assign(r.style,{width:"1px",height:"20px",background:"var(--hs-divider)",flexShrink:"0"}),this.suggestionArea.appendChild(r),this.suggestionText=document.createElement("span"),vt(this.suggestionText,"secondary","sm","normal"),Object.assign(this.suggestionText.style,{whiteSpace:"normal",lineHeight:"1.4",display:"-webkit-box",WebkitLineClamp:"2",WebkitBoxOrient:"vertical",overflow:"hidden"}),this.suggestionArea.appendChild(this.suggestionText);const n=Ct({label:"Let's talk",variant:"accent",size:"sm",onClick:a=>{var l;a.stopPropagation(),(l=this.onSuggestionAccept)==null||l.call(this)}});n.style.flexShrink="0",this.suggestionArea.appendChild(n);const o=document.createElement("button");o.textContent="✕",Object.assign(o.style,{background:"none",border:"none",color:"var(--hs-text-tertiary)",fontSize:"12px",cursor:"pointer",padding:"4px",flexShrink:"0",lineHeight:"1",transition:"color 0.15s ease"}),o.addEventListener("mouseenter",()=>{o.style.color="var(--hs-text-primary)"}),o.addEventListener("mouseleave",()=>{o.style.color="var(--hs-text-tertiary)"}),o.addEventListener("click",a=>{var l;a.stopPropagation(),(l=this.onSuggestionDismiss)==null||l.call(this),this.clearSuggestion()}),this.suggestionArea.appendChild(o),this.el.appendChild(this.suggestionArea),this.el.addEventListener("click",a=>{var l;a.target.closest("button")||(l=this.onClick)==null||l.call(this)}),document.body.appendChild(this.el)}showAmbient(){var e;!this.el||this._state==="ambient"||(this._state="ambient",this.collapseName(),this.collapseSuggestion(),this.stopAvatarVideo(),this.el.style.display="flex",this.el.style.gap="0px",this.el.style.padding="5px",(e=this.currentAnim)==null||e.stop(),this.currentAnim=rt(this.el,{preset:"gentle",from:{opacity:0,scale:.8,y:12}}))}showNamed(){var t;if(!this.el||this._state==="named")return;const e=this._state==="hidden";this._state="named",this.collapseSuggestion(),this.stopAvatarVideo(),this.expandName(),this.el.style.display="flex",this.el.style.gap="var(--hs-space-3)",this.el.style.padding="8px 20px 8px 8px",e&&((t=this.currentAnim)==null||t.stop(),this.el.style.opacity="0",this.currentAnim=rt(this.el,{preset:"bouncy",from:{opacity:0,scale:.85,y:16}}))}showSuggestion(e){var i;if(!this.el||!this.suggestionText)return;const t=this._state==="hidden";this._state="suggestion",this.el.style.display="flex",this.el.style.gap="var(--hs-space-3)",this.el.style.padding="10px 16px 10px 10px",this.el.style.borderRadius="var(--hs-radius-lg)",this.collapseName(),t&&((i=this.currentAnim)==null||i.stop(),this.el.style.opacity="0",this.currentAnim=rt(this.el,{preset:"bouncy",from:{opacity:0,scale:.9,y:12}})),this.startAvatarVideo(),this.startAvatarPulse(),this.suggestionText.textContent=e,this.suggestionText.title=e,requestAnimationFrame(()=>{this.suggestionArea&&(this.suggestionArea.style.maxWidth="500px",this.suggestionArea.style.opacity="1",this.suggestionArea.style.marginLeft="var(--hs-space-2)")})}clearSuggestion(){this.el&&(this._state="named",this.stopAvatarPulse(),this.stopAvatarVideo(),this.collapseSuggestion(),this.expandName(),this.el.style.padding="8px 20px 8px 8px",this.el.style.borderRadius="var(--hs-radius-pill)")}showConnecting(){var e;!this.el||!this.nameEl||(this._state="connecting",this.stopAvatarPulse(),this.stopAvatarVideo(),this.collapseSuggestion(),this.expandName(),this.nameEl.textContent="Connecting...",this.nameEl.style.opacity="0.6",this.el.style.display="flex",this.el.style.gap="var(--hs-space-3)",this.el.style.padding="8px 20px 8px 8px",this.el.style.opacity==="0"&&((e=this.currentAnim)==null||e.stop(),this.currentAnim=rt(this.el,{preset:"snappy",from:{opacity:0,scale:.9,y:8}})))}restoreName(){this.nameEl&&(this.nameEl.textContent=this.staffName,this.nameEl.style.opacity="1")}hide(){var t;if((t=this.currentAnim)==null||t.stop(),!this.el)return;this._state="hidden",this.stopAvatarPulse(),this.stopAvatarVideo();const e=this.el;this.currentAnim=Nt(e,{remove:!1,preset:"smooth",to:{opacity:0,scale:.9,y:12},onComplete:()=>{e.style.display="none"}})}destroy(){var e,t;(e=this.currentAnim)==null||e.stop(),this.stopAvatarPulse(),this.stopAvatarVideo(),(t=this.el)==null||t.remove(),this.el=null,this._state="hidden"}get state(){return this._state}get isVisible(){return this._state!=="hidden"}expandName(){this.nameEl&&(this.nameEl.textContent=this.staffName,this.nameEl.style.opacity="1",this.nameEl.style.maxWidth="150px",this.nameEl.style.marginLeft="var(--hs-space-2)")}collapseName(){this.nameEl&&(this.nameEl.style.maxWidth="0",this.nameEl.style.opacity="0",this.nameEl.style.marginLeft="0")}collapseSuggestion(){this.suggestionArea&&(this.suggestionArea.style.maxWidth="0",this.suggestionArea.style.opacity="0",this.suggestionArea.style.marginLeft="0")}startAvatarVideo(){!this.avatarVideo||!this.avatarImg||(this.avatarVideo.style.display="block",this.avatarVideo.currentTime=0,this.avatarVideo.play().catch(()=>{}),this.avatarImg.style.opacity="0")}stopAvatarVideo(){!this.avatarVideo||!this.avatarImg||(this.avatarVideo.pause(),this.avatarVideo.style.display="none",this.avatarImg.style.opacity="1")}startAvatarPulse(){this.avatarWrap&&(this.injectPulseStyle(),this.avatarWrap.style.animation="hs-pill-pulse 1.5s ease-in-out infinite")}stopAvatarPulse(){this.avatarWrap&&(this.avatarWrap.style.animation="")}injectPulseStyle(){if(this.pulseStyleInjected)return;this.pulseStyleInjected=!0;const e=document.createElement("style");e.textContent=UC,document.head.appendChild(e)}}const FC=15e3,GC=320;class LC{constructor(){this.cards=[],this.anchor=null}setAnchor(e){this.anchor=e}showTextCard(e,t){const i=this.createCard(),r=document.createElement("div");vt(r,"primary","base","semibold"),r.textContent=e,r.style.marginBottom="var(--hs-space-2)",i.el.appendChild(r);const n=document.createElement("div");vt(n,"secondary","sm","normal"),n.textContent=t,n.style.whiteSpace="pre-wrap",i.el.appendChild(n),this.mountCard(i)}showImageCard(e,t){const i=this.createCard(),r=document.createElement("img");if(r.src=e,r.alt=t||"",Object.assign(r.style,{width:"100%",borderRadius:"var(--hs-radius-sm)",display:"block",marginBottom:t?"var(--hs-space-2)":"0"}),i.el.appendChild(r),t){const n=document.createElement("div");vt(n,"secondary","sm","normal"),n.textContent=t,i.el.appendChild(n)}this.mountCard(i)}showBulletList(e,t){const i=this.createCard(),r=document.createElement("div");vt(r,"primary","base","semibold"),r.textContent=e,r.style.marginBottom="var(--hs-space-2)",i.el.appendChild(r);const n=document.createElement("ul");Object.assign(n.style,{margin:"0",paddingLeft:"var(--hs-space-5)",listStyleType:"none"}),t.forEach(o=>{const a=document.createElement("li");Object.assign(a.style,{marginBottom:"var(--hs-space-1)",position:"relative",paddingLeft:"0"});const l=document.createElement("span");Object.assign(l.style,{position:"absolute",left:"-16px",top:"6px",width:"5px",height:"5px",borderRadius:"50%",background:"var(--hs-accent)"}),a.appendChild(l);const c=document.createElement("span");vt(c,"secondary","sm","normal"),c.textContent=o,a.appendChild(c),n.appendChild(a)}),i.el.appendChild(n),this.mountCard(i)}dismissAll(){this.cards.forEach(e=>this.removeCard(e)),this.cards=[]}createCard(){St();const e=Kt({radius:"md",elevation:"elevated",className:"hs-overlay-card"});Object.assign(e.style,{position:"fixed",maxWidth:`${Math.min(GC,window.innerWidth-32)}px`,padding:"var(--hs-space-4)",zIndex:W.zOverlay,opacity:"0",pointerEvents:"auto"});const t=Ct({label:"✕",variant:"ghost",size:"sm",onClick:()=>this.dismiss(r)});Object.assign(t.style,{position:"absolute",top:"var(--hs-space-2)",right:"var(--hs-space-2)",minWidth:"0",padding:"2px 6px",fontSize:"var(--hs-text-xs)"}),e.appendChild(t);const i=setTimeout(()=>this.dismiss(r),FC),r={el:e,timer:i,anim:null};return r}mountCard(e){document.body.appendChild(e.el),this.positionCard(e.el,this.cards.length),this.cards.push(e),e.anim=rt(e.el,{preset:"snappy"})}positionCard(e,t){const i=500+t*10,r=e.offsetHeight||80;Object.assign(e.style,{bottom:`${i+t*(r+8)}px`,left:"50%",transform:"translateX(-50%)"})}dismiss(e){const t=this.cards.indexOf(e);t>=0&&this.cards.splice(t,1),this.removeCard(e)}removeCard(e){var t;clearTimeout(e.timer),(t=e.anim)==null||t.stop(),e.anim=Nt(e.el,{remove:!0,preset:"smooth"})}}class WC{constructor(){this.el=null,this.currentAnim=null,this.minimized=!1,this.onMinimize=null,this.onRestore=null,this.onClose=null}show(){St(),this.hide(),this.el=Kt({radius:"pill",elevation:"elevated",className:"hs-controls"}),Object.assign(this.el.style,{position:"fixed",bottom:"var(--hs-space-3)",left:"0",right:"0",margin:"0 auto",width:"fit-content",display:"flex",alignItems:"center",gap:"var(--hs-space-1)",padding:"4px",zIndex:W.zControls,opacity:"0"}),$i(this.el);const e=Ct({label:this.minimized?"▲":"—",variant:"ghost",size:"sm",onClick:()=>{var i,r;this.minimized?(this.minimized=!1,e.textContent="—",(i=this.onRestore)==null||i.call(this)):(this.minimized=!0,e.textContent="▲",(r=this.onMinimize)==null||r.call(this))}});Object.assign(e.style,{minWidth:"32px",height:"32px",padding:"0",fontSize:"14px",borderRadius:"50%"}),this.el.appendChild(e);const t=Ct({label:"✕",variant:"ghost",size:"sm",onClick:()=>{var i;return(i=this.onClose)==null?void 0:i.call(this)}});Object.assign(t.style,{minWidth:"32px",height:"32px",padding:"0",fontSize:"14px",borderRadius:"50%"}),this.el.appendChild(t),document.body.appendChild(this.el),this.currentAnim=rt(this.el,{preset:"snappy",from:{opacity:0,scale:.9,y:8}})}hide(){var t;if((t=this.currentAnim)==null||t.stop(),!this.el)return;const e=this.el;this.el=null,this.minimized=!1,this.currentAnim=Nt(e,{remove:!0,preset:"smooth"})}}const HC=1e4;class VC{constructor(){this.el=null,this.currentAnim=null,this.autoTimer=null,this.resolver=null}ask(e){return St(),this.dismiss(),new Promise(t=>{this.resolver=t,this.el=Kt({radius:"lg",elevation:"elevated",role:"alertdialog",className:"hs-confirm-prompt"}),Object.assign(this.el.style,{position:"fixed",bottom:"320px",left:"50%",transform:"translateX(-50%)",padding:"var(--hs-space-5)",maxWidth:"340px",minWidth:"240px",zIndex:W.zTop,opacity:"0",textAlign:"center"}),this.el.setAttribute("aria-label","Action confirmation"),$i(this.el);const i=document.createElement("p");vt(i,"primary","base","normal"),i.textContent=e,i.style.marginBottom="var(--hs-space-4)",this.el.appendChild(i);const r=document.createElement("div");Object.assign(r.style,{display:"flex",gap:"var(--hs-space-3)",justifyContent:"center"}),r.appendChild(Ct({label:"Yes",variant:"accent",size:"md",onClick:()=>this.resolve(!0)})),r.appendChild(Ct({label:"No",variant:"default",size:"md",onClick:()=>this.resolve(!1)})),this.el.appendChild(r),document.body.appendChild(this.el),this.currentAnim=rt(this.el,{preset:"snappy"}),this.autoTimer=setTimeout(()=>this.resolve(!1),HC)})}dismiss(){this.resolver&&(this.resolver(!1),this.resolver=null),this.cleanup()}resolve(e){var t;(t=this.resolver)==null||t.call(this,e),this.resolver=null,this.cleanup()}cleanup(){var e;if(this.autoTimer&&(clearTimeout(this.autoTimer),this.autoTimer=null),(e=this.currentAnim)==null||e.stop(),this.el){const t=this.el;this.el=null,this.currentAnim=Nt(t,{remove:!0,preset:"smooth"})}}}const zC=520,$C=340,ra=12;class jC{constructor(){this.currentAnim=null,St(),this.el=Kt({radius:"lg",elevation:"elevated",className:"hs-stage-backdrop"}),Object.assign(this.el.style,{position:"fixed",bottom:"0",left:"0",right:"0",margin:"0 auto",width:`${zC}px`,height:`${$C}px`,zIndex:W.zOverlay,overflow:"hidden",display:"flex",flexDirection:"column",opacity:"0",padding:`${ra}px ${ra}px 0 ${ra}px`,borderRadius:"var(--hs-radius-lg) var(--hs-radius-lg) 0 0",borderBottom:"none"}),$i(this.el),this.contentArea=document.createElement("div"),Object.assign(this.contentArea.style,{flex:"1",position:"relative",overflow:"hidden",borderRadius:"var(--hs-radius-md) var(--hs-radius-md) 0 0"}),this.el.appendChild(this.contentArea)}appendContent(e){Object.assign(e.style,{width:"100%",height:"100%",objectFit:"cover",display:"block",borderRadius:"inherit"}),this.contentArea.appendChild(e)}show(){document.body.appendChild(this.el),this.currentAnim=rt(this.el,{preset:"gentle",from:{opacity:0,scale:.95,y:24}})}hide(){var e;(e=this.currentAnim)==null||e.stop(),this.currentAnim=Nt(this.el,{remove:!0,preset:"smooth",to:{opacity:0,scale:.95,y:16}})}get contentElement(){return this.contentArea}destroy(){var e;(e=this.currentAnim)==null||e.stop(),this.el.remove()}}const XC=`
|
|
1059
|
+
`;class of{constructor(){this.el=null,this.avatarWrap=null,this.avatarImg=null,this.avatarVideo=null,this.nameEl=null,this.suggestionArea=null,this.suggestionText=null,this.currentAnim=null,this._state="hidden",this.pulseStyleInjected=!1,this.avatarUrl=null,this.videoUrl=null,this.staffName="",this.onClick=null,this.onSuggestionAccept=null,this.onSuggestionDismiss=null}init(e,t,i){if(this.el)return;if(St(),this.avatarUrl=e,this.videoUrl=t,this.staffName=i,this.el=Kt({radius:"pill",elevation:"elevated",interactive:!0,className:"hs-chat-pill"}),Object.assign(this.el.style,{position:"fixed",bottom:"var(--hs-space-5)",left:"0",right:"0",margin:"0 auto",width:"fit-content",maxWidth:"min(90vw, 600px)",display:"none",alignItems:"center",gap:"0px",padding:"5px",zIndex:W.zControls,cursor:"pointer",userSelect:"none",opacity:"0",boxShadow:"0 4px 24px rgba(0, 0, 0, 0.18)",transition:"gap 0.3s ease, padding 0.3s ease, box-shadow 0.2s ease",overflow:"hidden"}),$i(this.el),this.el.addEventListener("mouseenter",()=>{this.el&&(this.el.style.boxShadow="0 6px 32px rgba(0, 0, 0, 0.24)")}),this.el.addEventListener("mouseleave",()=>{this.el&&(this.el.style.boxShadow="0 4px 24px rgba(0, 0, 0, 0.18)")}),this.avatarWrap=document.createElement("div"),Object.assign(this.avatarWrap.style,{width:"36px",height:"36px",borderRadius:"50%",overflow:"hidden",flexShrink:"0",position:"relative",border:"1.5px solid var(--hs-glass-border)",transition:"box-shadow 0.3s ease, width 0.3s ease, height 0.3s ease"}),e)this.avatarImg=document.createElement("img"),this.avatarImg.src=e,this.avatarImg.alt=i,Object.assign(this.avatarImg.style,{width:"100%",height:"100%",objectFit:"cover",display:"block"}),this.avatarWrap.appendChild(this.avatarImg);else{const a=document.createElement("div");Object.assign(a.style,{width:"100%",height:"100%",background:"var(--hs-accent)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"var(--hs-text-sm)",fontWeight:"var(--hs-weight-semibold)",color:"var(--hs-accent-text)"}),a.textContent=i.charAt(0).toUpperCase(),this.avatarWrap.appendChild(a)}t&&(this.avatarVideo=document.createElement("video"),this.avatarVideo.src=t,this.avatarVideo.muted=!0,this.avatarVideo.loop=!0,this.avatarVideo.playsInline=!0,this.avatarVideo.setAttribute("playsinline",""),Object.assign(this.avatarVideo.style,{position:"absolute",inset:"0",width:"100%",height:"100%",objectFit:"cover",display:"none"}),this.avatarWrap.appendChild(this.avatarVideo)),this.el.appendChild(this.avatarWrap),this.nameEl=document.createElement("span"),vt(this.nameEl,"primary","base","medium"),this.nameEl.textContent=i,Object.assign(this.nameEl.style,{whiteSpace:"nowrap",overflow:"hidden",maxWidth:"0",opacity:"0",transition:"max-width 0.3s ease, opacity 0.25s ease, margin 0.3s ease",marginLeft:"0"}),this.el.appendChild(this.nameEl),this.suggestionArea=document.createElement("div"),Object.assign(this.suggestionArea.style,{display:"flex",alignItems:"center",gap:"var(--hs-space-2)",maxWidth:"0",opacity:"0",overflow:"hidden",transition:"max-width 0.35s ease, opacity 0.25s ease, margin 0.3s ease",marginLeft:"0"});const r=document.createElement("span");Object.assign(r.style,{width:"1px",height:"20px",background:"var(--hs-divider)",flexShrink:"0"}),this.suggestionArea.appendChild(r),this.suggestionText=document.createElement("span"),vt(this.suggestionText,"secondary","sm","normal"),Object.assign(this.suggestionText.style,{whiteSpace:"normal",lineHeight:"1.4",display:"-webkit-box",WebkitLineClamp:"2",WebkitBoxOrient:"vertical",overflow:"hidden"}),this.suggestionArea.appendChild(this.suggestionText);const n=Ct({label:"Let's talk",variant:"accent",size:"sm",onClick:a=>{var l;a.stopPropagation(),(l=this.onSuggestionAccept)==null||l.call(this)}});n.style.flexShrink="0",this.suggestionArea.appendChild(n);const o=document.createElement("button");o.textContent="✕",Object.assign(o.style,{background:"none",border:"none",color:"var(--hs-text-tertiary)",fontSize:"12px",cursor:"pointer",padding:"4px",flexShrink:"0",lineHeight:"1",transition:"color 0.15s ease"}),o.addEventListener("mouseenter",()=>{o.style.color="var(--hs-text-primary)"}),o.addEventListener("mouseleave",()=>{o.style.color="var(--hs-text-tertiary)"}),o.addEventListener("click",a=>{var l;a.stopPropagation(),(l=this.onSuggestionDismiss)==null||l.call(this),this.clearSuggestion()}),this.suggestionArea.appendChild(o),this.el.appendChild(this.suggestionArea),this.el.addEventListener("click",a=>{var l;a.target.closest("button")||(l=this.onClick)==null||l.call(this)}),document.documentElement.appendChild(this.el)}showAmbient(){var e;!this.el||this._state==="ambient"||(this._state="ambient",this.collapseName(),this.collapseSuggestion(),this.stopAvatarVideo(),this.el.style.display="flex",this.el.style.gap="0px",this.el.style.padding="5px",(e=this.currentAnim)==null||e.stop(),this.currentAnim=rt(this.el,{preset:"gentle",from:{opacity:0,scale:.8,y:12}}))}showNamed(){var t;if(!this.el||this._state==="named")return;const e=this._state==="hidden";this._state="named",this.collapseSuggestion(),this.stopAvatarVideo(),this.expandName(),this.el.style.display="flex",this.el.style.gap="var(--hs-space-3)",this.el.style.padding="8px 20px 8px 8px",e&&((t=this.currentAnim)==null||t.stop(),this.el.style.opacity="0",this.currentAnim=rt(this.el,{preset:"bouncy",from:{opacity:0,scale:.85,y:16}}))}showSuggestion(e){var i;if(!this.el||!this.suggestionText)return;const t=this._state==="hidden";this._state="suggestion",this.el.style.display="flex",this.el.style.gap="var(--hs-space-3)",this.el.style.padding="10px 16px 10px 10px",this.el.style.borderRadius="var(--hs-radius-lg)",this.collapseName(),t&&((i=this.currentAnim)==null||i.stop(),this.el.style.opacity="0",this.currentAnim=rt(this.el,{preset:"bouncy",from:{opacity:0,scale:.9,y:12}})),this.startAvatarVideo(),this.startAvatarPulse(),this.suggestionText.textContent=e,this.suggestionText.title=e,requestAnimationFrame(()=>{this.suggestionArea&&(this.suggestionArea.style.maxWidth="500px",this.suggestionArea.style.opacity="1",this.suggestionArea.style.marginLeft="var(--hs-space-2)")})}clearSuggestion(){this.el&&(this._state="named",this.stopAvatarPulse(),this.stopAvatarVideo(),this.collapseSuggestion(),this.expandName(),this.el.style.padding="8px 20px 8px 8px",this.el.style.borderRadius="var(--hs-radius-pill)")}showConnecting(){var e;!this.el||!this.nameEl||(this._state="connecting",this.stopAvatarPulse(),this.stopAvatarVideo(),this.collapseSuggestion(),this.expandName(),this.nameEl.textContent="Connecting...",this.nameEl.style.opacity="0.6",this.el.style.display="flex",this.el.style.gap="var(--hs-space-3)",this.el.style.padding="8px 20px 8px 8px",this.el.style.opacity==="0"&&((e=this.currentAnim)==null||e.stop(),this.currentAnim=rt(this.el,{preset:"snappy",from:{opacity:0,scale:.9,y:8}})))}restoreName(){this.nameEl&&(this.nameEl.textContent=this.staffName,this.nameEl.style.opacity="1")}hide(){var t;if((t=this.currentAnim)==null||t.stop(),!this.el)return;this._state="hidden",this.stopAvatarPulse(),this.stopAvatarVideo();const e=this.el;this.currentAnim=Nt(e,{remove:!1,preset:"smooth",to:{opacity:0,scale:.9,y:12},onComplete:()=>{e.style.display="none"}})}destroy(){var e,t;(e=this.currentAnim)==null||e.stop(),this.stopAvatarPulse(),this.stopAvatarVideo(),(t=this.el)==null||t.remove(),this.el=null,this._state="hidden"}get state(){return this._state}get isVisible(){return this._state!=="hidden"}expandName(){this.nameEl&&(this.nameEl.textContent=this.staffName,this.nameEl.style.opacity="1",this.nameEl.style.maxWidth="150px",this.nameEl.style.marginLeft="var(--hs-space-2)")}collapseName(){this.nameEl&&(this.nameEl.style.maxWidth="0",this.nameEl.style.opacity="0",this.nameEl.style.marginLeft="0")}collapseSuggestion(){this.suggestionArea&&(this.suggestionArea.style.maxWidth="0",this.suggestionArea.style.opacity="0",this.suggestionArea.style.marginLeft="0")}startAvatarVideo(){!this.avatarVideo||!this.avatarImg||(this.avatarVideo.style.display="block",this.avatarVideo.currentTime=0,this.avatarVideo.play().catch(()=>{}),this.avatarImg.style.opacity="0")}stopAvatarVideo(){!this.avatarVideo||!this.avatarImg||(this.avatarVideo.pause(),this.avatarVideo.style.display="none",this.avatarImg.style.opacity="1")}startAvatarPulse(){this.avatarWrap&&(this.injectPulseStyle(),this.avatarWrap.style.animation="hs-pill-pulse 1.5s ease-in-out infinite")}stopAvatarPulse(){this.avatarWrap&&(this.avatarWrap.style.animation="")}injectPulseStyle(){if(this.pulseStyleInjected)return;this.pulseStyleInjected=!0;const e=document.createElement("style");e.textContent=UC,document.head.appendChild(e)}}const FC=15e3,GC=320;class LC{constructor(){this.cards=[],this.anchor=null}setAnchor(e){this.anchor=e}showTextCard(e,t){const i=this.createCard(),r=document.createElement("div");vt(r,"primary","base","semibold"),r.textContent=e,r.style.marginBottom="var(--hs-space-2)",i.el.appendChild(r);const n=document.createElement("div");vt(n,"secondary","sm","normal"),n.textContent=t,n.style.whiteSpace="pre-wrap",i.el.appendChild(n),this.mountCard(i)}showImageCard(e,t){const i=this.createCard(),r=document.createElement("img");if(r.src=e,r.alt=t||"",Object.assign(r.style,{width:"100%",borderRadius:"var(--hs-radius-sm)",display:"block",marginBottom:t?"var(--hs-space-2)":"0"}),i.el.appendChild(r),t){const n=document.createElement("div");vt(n,"secondary","sm","normal"),n.textContent=t,i.el.appendChild(n)}this.mountCard(i)}showBulletList(e,t){const i=this.createCard(),r=document.createElement("div");vt(r,"primary","base","semibold"),r.textContent=e,r.style.marginBottom="var(--hs-space-2)",i.el.appendChild(r);const n=document.createElement("ul");Object.assign(n.style,{margin:"0",paddingLeft:"var(--hs-space-5)",listStyleType:"none"}),t.forEach(o=>{const a=document.createElement("li");Object.assign(a.style,{marginBottom:"var(--hs-space-1)",position:"relative",paddingLeft:"0"});const l=document.createElement("span");Object.assign(l.style,{position:"absolute",left:"-16px",top:"6px",width:"5px",height:"5px",borderRadius:"50%",background:"var(--hs-accent)"}),a.appendChild(l);const c=document.createElement("span");vt(c,"secondary","sm","normal"),c.textContent=o,a.appendChild(c),n.appendChild(a)}),i.el.appendChild(n),this.mountCard(i)}dismissAll(){this.cards.forEach(e=>this.removeCard(e)),this.cards=[]}createCard(){St();const e=Kt({radius:"md",elevation:"elevated",className:"hs-overlay-card"});Object.assign(e.style,{position:"fixed",maxWidth:`${Math.min(GC,window.innerWidth-32)}px`,padding:"var(--hs-space-4)",zIndex:W.zOverlay,opacity:"0",pointerEvents:"auto"});const t=Ct({label:"✕",variant:"ghost",size:"sm",onClick:()=>this.dismiss(r)});Object.assign(t.style,{position:"absolute",top:"var(--hs-space-2)",right:"var(--hs-space-2)",minWidth:"0",padding:"2px 6px",fontSize:"var(--hs-text-xs)"}),e.appendChild(t);const i=setTimeout(()=>this.dismiss(r),FC),r={el:e,timer:i,anim:null};return r}mountCard(e){document.body.appendChild(e.el),this.positionCard(e.el,this.cards.length),this.cards.push(e),e.anim=rt(e.el,{preset:"snappy"})}positionCard(e,t){const i=500+t*10,r=e.offsetHeight||80;Object.assign(e.style,{bottom:`${i+t*(r+8)}px`,left:"50%",transform:"translateX(-50%)"})}dismiss(e){const t=this.cards.indexOf(e);t>=0&&this.cards.splice(t,1),this.removeCard(e)}removeCard(e){var t;clearTimeout(e.timer),(t=e.anim)==null||t.stop(),e.anim=Nt(e.el,{remove:!0,preset:"smooth"})}}class WC{constructor(){this.el=null,this.currentAnim=null,this.minimized=!1,this.onMinimize=null,this.onRestore=null,this.onClose=null}show(){St(),this.hide(),this.el=Kt({radius:"pill",elevation:"elevated",className:"hs-controls"}),Object.assign(this.el.style,{position:"fixed",bottom:"var(--hs-space-3)",left:"0",right:"0",margin:"0 auto",width:"fit-content",display:"flex",alignItems:"center",gap:"var(--hs-space-1)",padding:"4px",zIndex:W.zControls,opacity:"0"}),$i(this.el);const e=Ct({label:this.minimized?"▲":"—",variant:"ghost",size:"sm",onClick:()=>{var i,r;this.minimized?(this.minimized=!1,e.textContent="—",(i=this.onRestore)==null||i.call(this)):(this.minimized=!0,e.textContent="▲",(r=this.onMinimize)==null||r.call(this))}});Object.assign(e.style,{minWidth:"32px",height:"32px",padding:"0",fontSize:"14px",borderRadius:"50%"}),this.el.appendChild(e);const t=Ct({label:"✕",variant:"ghost",size:"sm",onClick:()=>{var i;return(i=this.onClose)==null?void 0:i.call(this)}});Object.assign(t.style,{minWidth:"32px",height:"32px",padding:"0",fontSize:"14px",borderRadius:"50%"}),this.el.appendChild(t),document.body.appendChild(this.el),this.currentAnim=rt(this.el,{preset:"snappy",from:{opacity:0,scale:.9,y:8}})}hide(){var t;if((t=this.currentAnim)==null||t.stop(),!this.el)return;const e=this.el;this.el=null,this.minimized=!1,this.currentAnim=Nt(e,{remove:!0,preset:"smooth"})}}const HC=1e4;class VC{constructor(){this.el=null,this.currentAnim=null,this.autoTimer=null,this.resolver=null}ask(e){return St(),this.dismiss(),new Promise(t=>{this.resolver=t,this.el=Kt({radius:"lg",elevation:"elevated",role:"alertdialog",className:"hs-confirm-prompt"}),Object.assign(this.el.style,{position:"fixed",bottom:"320px",left:"50%",transform:"translateX(-50%)",padding:"var(--hs-space-5)",maxWidth:"340px",minWidth:"240px",zIndex:W.zTop,opacity:"0",textAlign:"center"}),this.el.setAttribute("aria-label","Action confirmation"),$i(this.el);const i=document.createElement("p");vt(i,"primary","base","normal"),i.textContent=e,i.style.marginBottom="var(--hs-space-4)",this.el.appendChild(i);const r=document.createElement("div");Object.assign(r.style,{display:"flex",gap:"var(--hs-space-3)",justifyContent:"center"}),r.appendChild(Ct({label:"Yes",variant:"accent",size:"md",onClick:()=>this.resolve(!0)})),r.appendChild(Ct({label:"No",variant:"default",size:"md",onClick:()=>this.resolve(!1)})),this.el.appendChild(r),document.body.appendChild(this.el),this.currentAnim=rt(this.el,{preset:"snappy"}),this.autoTimer=setTimeout(()=>this.resolve(!1),HC)})}dismiss(){this.resolver&&(this.resolver(!1),this.resolver=null),this.cleanup()}resolve(e){var t;(t=this.resolver)==null||t.call(this,e),this.resolver=null,this.cleanup()}cleanup(){var e;if(this.autoTimer&&(clearTimeout(this.autoTimer),this.autoTimer=null),(e=this.currentAnim)==null||e.stop(),this.el){const t=this.el;this.el=null,this.currentAnim=Nt(t,{remove:!0,preset:"smooth"})}}}const zC=520,$C=340,ra=12;class jC{constructor(){this.currentAnim=null,St(),this.el=Kt({radius:"lg",elevation:"elevated",className:"hs-stage-backdrop"}),Object.assign(this.el.style,{position:"fixed",bottom:"0",left:"0",right:"0",margin:"0 auto",width:`${zC}px`,height:`${$C}px`,zIndex:W.zOverlay,overflow:"hidden",display:"flex",flexDirection:"column",opacity:"0",padding:`${ra}px ${ra}px 0 ${ra}px`,borderRadius:"var(--hs-radius-lg) var(--hs-radius-lg) 0 0",borderBottom:"none"}),$i(this.el),this.contentArea=document.createElement("div"),Object.assign(this.contentArea.style,{flex:"1",position:"relative",overflow:"hidden",borderRadius:"var(--hs-radius-md) var(--hs-radius-md) 0 0"}),this.el.appendChild(this.contentArea)}appendContent(e){Object.assign(e.style,{width:"100%",height:"100%",objectFit:"cover",display:"block",borderRadius:"inherit"}),this.contentArea.appendChild(e)}show(){document.body.appendChild(this.el),this.currentAnim=rt(this.el,{preset:"gentle",from:{opacity:0,scale:.95,y:24}})}hide(){var e;(e=this.currentAnim)==null||e.stop(),this.currentAnim=Nt(this.el,{remove:!0,preset:"smooth",to:{opacity:0,scale:.95,y:16}})}get contentElement(){return this.contentArea}destroy(){var e;(e=this.currentAnim)==null||e.stop(),this.el.remove()}}const XC=`
|
|
1060
1060
|
@keyframes hs-highlight-glow {
|
|
1061
1061
|
0%, 100% { box-shadow: 0 0 8px var(--hs-accent-glow), inset 0 0 4px var(--hs-accent-glow); }
|
|
1062
1062
|
50% { box-shadow: 0 0 20px var(--hs-accent-glow), inset 0 0 8px var(--hs-accent-glow); }
|
|
1063
1063
|
}
|
|
1064
|
-
`;let af=!1;class YC{constructor(){this.highlights=[]}highlight(e,t=3e3){St(),this.injectPulseStyle();const i=document.createElement("div");i.className="hs-highlight-overlay",i.setAttribute("data-hs-theme","dark");const r=()=>{const l=e.getBoundingClientRect();Object.assign(i.style,{position:"fixed",top:`${l.top-3}px`,left:`${l.left-3}px`,width:`${l.width+6}px`,height:`${l.height+6}px`,border:"2px solid var(--hs-accent)",borderRadius:"var(--hs-radius-sm)",animation:"hs-highlight-glow 1.5s ease-in-out infinite",pointerEvents:"none",zIndex:W.zOverlay,boxSizing:"border-box"})};r(),document.body.appendChild(i);const n=()=>r();window.addEventListener("scroll",n,{passive:!0});const o=setTimeout(()=>this.removeHighlight(a),t),a={overlay:i,timer:o,scrollHandler:n,anim:null};this.highlights.push(a)}clearAll(){this.highlights.forEach(e=>this.removeHighlight(e)),this.highlights=[]}removeHighlight(e){clearTimeout(e.timer),window.removeEventListener("scroll",e.scrollHandler),e.anim=EC(e.overlay,1,0,"smooth",()=>{e.overlay.remove()});const t=this.highlights.indexOf(e);t>=0&&this.highlights.splice(t,1)}injectPulseStyle(){if(af)return;af=!0;const e=document.createElement("style");e.textContent=XC,document.head.appendChild(e)}}const qC=800,KC=600*1e3,ZC=540*1e3,lf=60*1e3,JC=90*1e3,QC=[{type:"function",name:"page_action",description:"Interact with the webpage the visitor is viewing. You can scroll to elements, highlight elements, click buttons/links, fill form fields, or read the page content. Describe what you want to do in natural language. Call this to understand the page, guide the visitor, or take actions on their behalf.",parameters:{type:"object",properties:{instruction:{type:"string",description:"What to do on the page, e.g. 'scroll to pricing section', 'highlight the sign-up button', 'fill the email field with test@example.com', 'read the page to understand what it contains'"}},required:["instruction"]}},{type:"function",name:"show_text_card",description:"Display a floating text card overlay near the avatar with additional information for the visitor. Use for key points, explanations, or summaries that benefit from visual display.",parameters:{type:"object",properties:{title:{type:"string",description:"Card title"},body:{type:"string",description:"Card body text"}},required:["title","body"]}},{type:"function",name:"show_image_card",description:"Display a floating image card overlay with an optional caption.",parameters:{type:"object",properties:{image_url:{type:"string",description:"URL of the image to display"},caption:{type:"string",description:"Optional caption below the image"}},required:["image_url"]}},{type:"function",name:"show_bullet_list",description:"Display a styled list of key points as a floating overlay card.",parameters:{type:"object",properties:{title:{type:"string",description:"List title"},items:{type:"array",items:{type:"string"},description:"List items"}},required:["title","items"]}},{type:"function",name:"dismiss_overlays",description:"Dismiss all currently visible overlay cards.",parameters:{type:"object",properties:{},required:[]}}];class cf{constructor(e,t){this.stage=null,this.avatar=null,this.state="idle",this.avatarState="idle",this.scrollHandler=null,this.idleVideoUrl=null,this.idleImageUrl=null,this.bubbleTimer=null,this.realtimeSession=null,this.audioForwarder=null,this.anamSession=null,this.sessionResponse=null,this.domAnalyzer=null,this.toolHandler=null,this.maxDurationTimer=null,this.maxDurationWarnTimer=null,this.inactivityTimer=null,this.inactivityCloseTimer=null,this.sessionStartTime=0,this.logger=null,this.rrwebRecorder=null,this.visionWs=null,this.externalObserver=!1,this.actionExecutor=null,this.visionContext=null,this.staffDisplayName="Assistant",this.staffAvatarUrl=null,this.hasHadConversation=!1,this.avatarFrame=null,this.bubble=null,this.chatPill=null,this.overlayRenderer=null,this.controls=null,this.confirmationPrompt=null,this.highlightRenderer=null,this.stageBackdrop=null,this.stageEl=null,this.homePlaceholder=null,this.homeObserver=null,this.homeVisible=!0,this.homeEverSeen=!1,this.pillProtected=!1,this.paused=!1,this.config=e,this.widgetPrompts=t??null,this.visitorId=this.getOrCreateVisitorId()}get isInline(){return this.config.mode==="inline"&&!!this.config.container}get activeContainer(){return this.config.container}async init(){St(),this.stage=new ux,await this.stage.init(this.config.mode,this.config.container),this.avatar=new fx(this.stage.stageWidth,this.stage.stageHeight),this.stage.app.stage.addChild(this.avatar.container),await this.loadIdleAsset(),this.avatarFrame=new OC,this.stage.rootElement&&$i(this.stage.rootElement),this.bubble=new NC(this.widgetPrompts??void 0),this.bubble.onClick=()=>this.onAvatarClick(),this.stage.rootElement&&(this.stage.rootElement.style.position="relative",this.stage.rootElement.appendChild(this.bubble.el)),this.avatar.setInteractive(()=>this.onAvatarClick()),this.isInline&&(this.chatPill=new of,this.chatPill.init(this.staffAvatarUrl,this.idleVideoUrl,this.staffDisplayName),this.chatPill.onClick=()=>this.onAvatarClick(),setTimeout(()=>{var t;(this.state==="idle"||this.state==="teasing")&&!this.homeVisible&&((t=this.chatPill)==null?void 0:t.state)==="hidden"&&this.chatPill.showNamed()},5e3),this.startHomeObserver()),this.setupTrigger(),this.startVisionLoop(),window.addEventListener("beforeunload",()=>{var e;(this.state==="active"||this.state==="connecting")&&((e=this.logger)==null||e.flush())}),console.log("[HolostaffWidget] Initialized",{staffId:this.config.staffId,trigger:this.config.trigger,visionEnabled:!!this.config.visionWsUrl})}async loadIdleAsset(){if(!(!this.avatar||!this.stage)){if(this.idleVideoUrl)try{if(this.isInline&&this.stage.inlineTarget){const e=this.stage.inlineTarget;e.style.position="relative";const t=document.createElement("div");t.className="hs-inline-card",t.setAttribute("data-hs-theme","dark"),Object.assign(t.style,{position:"absolute",inset:"0",display:"flex",flexDirection:"column",borderRadius:"var(--hs-radius-lg)",overflow:"hidden",background:"var(--hs-glass-bg)",backdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",WebkitBackdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",border:"1px solid var(--hs-glass-border)",boxShadow:"var(--hs-glass-shadow)",cursor:"pointer",padding:"var(--hs-space-3)",boxSizing:"border-box"});const i=document.createElement("div");Object.assign(i.style,{flex:"1",overflow:"hidden",position:"relative",borderRadius:"var(--hs-radius-md)",border:"1px solid var(--hs-glass-border)"});const r=document.createElement("video");r.src=this.idleVideoUrl,r.autoplay=!0,r.loop=!0,r.muted=!0,r.playsInline=!0,r.setAttribute("playsinline",""),Object.assign(r.style,{width:"100%",height:"100%",objectFit:"cover",display:"block"}),i.appendChild(r),t.appendChild(i);const n=document.createElement("div");Object.assign(n.style,{padding:"var(--hs-space-3) var(--hs-space-4)",textAlign:"center"});const o=document.createElement("div");Object.assign(o.style,{color:"var(--hs-text-primary)",fontSize:"var(--hs-text-base)",fontWeight:"var(--hs-weight-semibold)",fontFamily:"var(--hs-font)",lineHeight:"var(--hs-line-height)"}),o.textContent=`${this.staffDisplayName}, your AI copilot`,n.appendChild(o);const a=document.createElement("div");Object.assign(a.style,{color:"var(--hs-text-tertiary)",fontSize:"var(--hs-text-xs)",fontFamily:"var(--hs-font)",marginTop:"2px"}),a.textContent="Powered by Holostaff",n.appendChild(a),t.appendChild(n),t.addEventListener("click",()=>this.onAvatarClick()),e.appendChild(t),this.stage.rootElement&&(this.stage.rootElement.style.display="none")}else{const e=this.stage.rootElement;if(!e)throw new Error("Widget root not available");await this.avatar.loadIdleVideo(this.idleVideoUrl,e)}return}catch{console.warn("[HolostaffWidget] Failed to load idle video, trying image fallback")}this.idleImageUrl?await this.avatar.loadIdleImage(this.idleImageUrl):console.warn("[HolostaffWidget] No idle video or image configured")}}setIdleVideo(e){this.idleVideoUrl=e}setIdleImage(e){this.idleImageUrl=e}setObserver(e,t){this.rrwebRecorder=e,this.visionWs=t,this.externalObserver=!0}setStaffInfo(e,t){this.staffDisplayName=e,this.staffAvatarUrl=t}setupTrigger(){if(this.isInline){this.showAvatarOnly();return}if(this.config.visionWsUrl){this.showAvatarOnly();return}switch(this.config.trigger){case"scroll":this.setupScrollTrigger();break;case"delay":setTimeout(()=>this.showTeaser(),this.config.delayMs);break;case"immediate":this.showTeaser();break}}setupScrollTrigger(){this.scrollHandler=()=>{const e=window.scrollY,t=document.documentElement.scrollHeight-window.innerHeight,i=t>0?e/t:0;i>=this.config.scrollThreshold&&this.state==="idle"?this.showTeaser():i<this.config.scrollThreshold*.5&&this.state==="teasing"&&this.hideTeaser()},window.addEventListener("scroll",this.scrollHandler,{passive:!0})}showAvatarOnly(){this.state!=="idle"||!this.avatar||!this.stage||(this.state="teasing",this.avatar.slideIn(this.stage.app.ticker))}showTeaser(){this.state!=="idle"||!this.avatar||!this.stage||(this.state="teasing",this.avatar.slideIn(this.stage.app.ticker),this.bubbleTimer=setTimeout(()=>{var e;return(e=this.bubble)==null?void 0:e.start()},qC))}hideTeaser(){var e;this.state!=="teasing"||!this.avatar||!this.stage||(this.state="idle",this.bubbleTimer&&(clearTimeout(this.bubbleTimer),this.bubbleTimer=null),(e=this.bubble)==null||e.stop(),this.avatar.slideOut(this.stage.app.ticker))}async onAvatarClick(){var e,t,i,r,n,o,a,l,c,h,u,f;if(!(this.state!=="teasing"&&this.state!=="idle")){if(this.state="connecting",(e=this.bubble)==null||e.stop(),(t=this.bubble)==null||t.hideStatic(),(i=this.actionExecutor)==null||i.destroy(),this.actionExecutor=null,this.isInline){(r=this.chatPill)==null||r.showConnecting();const d=(o=(n=this.stage)==null?void 0:n.inlineTarget)==null?void 0:o.querySelector(".hs-inline-card video");d&&d.pause()}else{(a=this.stage)!=null&&a.rootElement&&(this.stage.rootElement.style.display="");const d=document.querySelector("#holostaff-widget-root video");d&&d.pause(),(l=this.bubble)==null||l.showStatic("Connecting...")}console.log("[HolostaffWidget] Starting conversation...");try{this.sessionResponse=await Bf(this.config.staffId,this.config.backendUrl),console.log("[HolostaffWidget] Session tokens received"),this.logger=new uv({staffId:this.config.staffId,staffName:this.sessionResponse.staff.name,backendUrl:this.config.backendUrl}),await this.connectAnam(),await this.connectRealtimeApi(),this.state="active",this.setAvatarState("listening"),this.sessionStartTime=Date.now(),(c=this.bubble)==null||c.hideStatic(),this.showControls(),this.startSessionTimers(),(h=this.visionWs)==null||h.sendConversationStarted(),(u=this.rrwebRecorder)==null||u.pause(),console.log("[HolostaffWidget] Conversation active")}catch(d){console.error("[HolostaffWidget] Failed to start conversation:",d),(f=this.bubble)==null||f.hideStatic(),this.endConversation()}}}moveToStage(){var t;if(!this.isInline||!((t=this.stage)!=null&&t.inlineTarget))return;const e=this.stage.inlineTarget.querySelector(".hs-inline-card");e&&(e.style.display="none"),this.stage.inlineTarget.querySelectorAll("video").forEach(i=>{i instanceof HTMLVideoElement&&i.pause()}),this.homePlaceholder=document.createElement("div"),this.homePlaceholder.setAttribute("data-hs-theme","dark"),Object.assign(this.homePlaceholder.style,{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",color:"var(--hs-text-secondary)",fontSize:"var(--hs-text-sm)",fontFamily:"var(--hs-font)",textAlign:"center",padding:"var(--hs-space-4)",boxSizing:"border-box"}),this.homePlaceholder.innerHTML="Agent is active below ↓",this.stage.inlineTarget.appendChild(this.homePlaceholder),this.stageBackdrop=new jC,this.stageEl=this.stageBackdrop.el,this.stageBackdrop.show(),console.log("[HolostaffWidget] Moved to glass stage (bottom-center)")}returnToHome(){var t,i,r;if((t=this.stageBackdrop)==null||t.destroy(),this.stageBackdrop=null,this.stageEl=null,(i=this.homePlaceholder)==null||i.remove(),this.homePlaceholder=null,!((r=this.stage)!=null&&r.inlineTarget))return;const e=this.stage.inlineTarget.querySelector(".hs-inline-card");e&&(e.style.display=""),this.stage.inlineTarget.querySelectorAll(".hs-inline-card video").forEach(n=>{n.style.display="",n instanceof HTMLVideoElement&&n.play()}),console.log("[HolostaffWidget] Returned to home (inline container)")}startHomeObserver(){var i;this.stopHomeObserver();const e=(i=this.stage)==null?void 0:i.inlineTarget;if(!e)return;const t=e.getBoundingClientRect();this.homeVisible=t.top<window.innerHeight&&t.bottom>0,this.homeObserver=new IntersectionObserver(([r])=>{const n=this.homeVisible;if(this.homeVisible=r.isIntersecting,this.homeVisible&&!this.homeEverSeen&&(this.homeEverSeen=!0),(this.state==="idle"||this.state==="teasing")&&this.chatPill)if(this.homeVisible){if(this.pillProtected){this.pillProtected=!1;return}this.chatPill.hide()}else!this.homeVisible&&n&&this.homeEverSeen?this.chatPill.showNamed():!this.homeVisible&&!this.homeEverSeen&&this.chatPill.state==="hidden"&&this.chatPill.showNamed()},{threshold:.1}),this.homeObserver.observe(e)}stopHomeObserver(){var e;(e=this.homeObserver)==null||e.disconnect(),this.homeObserver=null}async connectAnam(){this.sessionResponse&&(this.anamSession=new ev({sessionToken:this.sessionResponse.anamSessionToken,inlineMode:this.isInline&&!!this.stageBackdrop}),this.anamSession.onConnected=()=>{console.log("[HolostaffWidget] Anam connected")},this.anamSession.onVideoReady=e=>{var t,i,r;console.log("[HolostaffWidget] Anam avatar video ready"),(t=this.bubble)==null||t.hideStatic(),(i=this.chatPill)==null||i.hide(),this.isInline?(this.moveToStage(),(r=this.stageBackdrop)==null||r.appendContent(e)):this.avatar&&this.stage&&this.avatar.setLiveVideo(e,this.stage.app.ticker)},this.anamSession.onTalkStreamInterrupted=()=>{console.log("[HolostaffWidget] Anam talk stream interrupted")},this.anamSession.onDisconnected=e=>{console.log("[HolostaffWidget] Anam disconnected:",e),this.endConversation()},this.anamSession.onError=e=>{console.error("[HolostaffWidget] Anam error:",e.message)},await this.anamSession.connect(),console.log("[HolostaffWidget] Anam session ready"))}async connectRealtimeApi(){var o;if(!this.sessionResponse)return;const e=document.title||"",t=location.href,i=((o=document.querySelector('meta[name="description"]'))==null?void 0:o.getAttribute("content"))||"",r=Array.from(document.querySelectorAll("h1, h2, h3")).slice(0,10).map(a=>{var l;return(l=a.textContent)==null?void 0:l.trim()}).filter(Boolean).join(" | ");let n=(this.sessionResponse.staff.instructions??"")+`
|
|
1064
|
+
`;let af=!1;class YC{constructor(){this.highlights=[]}highlight(e,t=3e3){St(),this.injectPulseStyle();const i=document.createElement("div");i.className="hs-highlight-overlay",i.setAttribute("data-hs-theme","dark");const r=()=>{const l=e.getBoundingClientRect();Object.assign(i.style,{position:"fixed",top:`${l.top-3}px`,left:`${l.left-3}px`,width:`${l.width+6}px`,height:`${l.height+6}px`,border:"2px solid var(--hs-accent)",borderRadius:"var(--hs-radius-sm)",animation:"hs-highlight-glow 1.5s ease-in-out infinite",pointerEvents:"none",zIndex:W.zOverlay,boxSizing:"border-box"})};r(),document.body.appendChild(i);const n=()=>r();window.addEventListener("scroll",n,{passive:!0});const o=setTimeout(()=>this.removeHighlight(a),t),a={overlay:i,timer:o,scrollHandler:n,anim:null};this.highlights.push(a)}clearAll(){this.highlights.forEach(e=>this.removeHighlight(e)),this.highlights=[]}removeHighlight(e){clearTimeout(e.timer),window.removeEventListener("scroll",e.scrollHandler),e.anim=EC(e.overlay,1,0,"smooth",()=>{e.overlay.remove()});const t=this.highlights.indexOf(e);t>=0&&this.highlights.splice(t,1)}injectPulseStyle(){if(af)return;af=!0;const e=document.createElement("style");e.textContent=XC,document.head.appendChild(e)}}const qC=800,KC=600*1e3,ZC=540*1e3,lf=60*1e3,JC=90*1e3,QC=[{type:"function",name:"page_action",description:"Interact with the webpage the visitor is viewing. You can scroll to elements, highlight elements, click buttons/links, fill form fields, or read the page content. Describe what you want to do in natural language. Call this to understand the page, guide the visitor, or take actions on their behalf.",parameters:{type:"object",properties:{instruction:{type:"string",description:"What to do on the page, e.g. 'scroll to pricing section', 'highlight the sign-up button', 'fill the email field with test@example.com', 'read the page to understand what it contains'"}},required:["instruction"]}},{type:"function",name:"show_text_card",description:"Display a floating text card overlay near the avatar with additional information for the visitor. Use for key points, explanations, or summaries that benefit from visual display.",parameters:{type:"object",properties:{title:{type:"string",description:"Card title"},body:{type:"string",description:"Card body text"}},required:["title","body"]}},{type:"function",name:"show_image_card",description:"Display a floating image card overlay with an optional caption.",parameters:{type:"object",properties:{image_url:{type:"string",description:"URL of the image to display"},caption:{type:"string",description:"Optional caption below the image"}},required:["image_url"]}},{type:"function",name:"show_bullet_list",description:"Display a styled list of key points as a floating overlay card.",parameters:{type:"object",properties:{title:{type:"string",description:"List title"},items:{type:"array",items:{type:"string"},description:"List items"}},required:["title","items"]}},{type:"function",name:"dismiss_overlays",description:"Dismiss all currently visible overlay cards.",parameters:{type:"object",properties:{},required:[]}},{type:"function",name:"get_skill_instructions",description:'Retrieve the full playbook for one of your configured skills. Call this when you determine a skill is relevant to the current conversation — it returns detailed guidance on what to say, tone, and what to avoid. Use the skill name exactly as listed in the "Your Skills" section of your instructions.',parameters:{type:"object",properties:{skill_name:{type:"string",description:'The exact skill name as listed in Your Skills (e.g. "Convert Visitor", "Get Started").'}},required:["skill_name"]}}];class cf{constructor(e,t){this.stage=null,this.avatar=null,this.state="idle",this.avatarState="idle",this.scrollHandler=null,this.idleVideoUrl=null,this.idleImageUrl=null,this.bubbleTimer=null,this.realtimeSession=null,this.audioForwarder=null,this.anamSession=null,this.sessionResponse=null,this.domAnalyzer=null,this.toolHandler=null,this.maxDurationTimer=null,this.maxDurationWarnTimer=null,this.inactivityTimer=null,this.inactivityCloseTimer=null,this.sessionStartTime=0,this.logger=null,this.rrwebRecorder=null,this.visionWs=null,this.externalObserver=!1,this.actionExecutor=null,this.visionContext=null,this.staffDisplayName="Assistant",this.staffAvatarUrl=null,this.hasHadConversation=!1,this.avatarFrame=null,this.bubble=null,this.chatPill=null,this.overlayRenderer=null,this.controls=null,this.confirmationPrompt=null,this.highlightRenderer=null,this.stageBackdrop=null,this.stageEl=null,this.homePlaceholder=null,this.homeObserver=null,this.homeVisible=!0,this.homeEverSeen=!1,this.pillProtected=!1,this.paused=!1,this.config=e,this.widgetPrompts=t??null,this.visitorId=this.getOrCreateVisitorId()}get isInline(){return this.config.mode==="inline"&&!!this.config.container}get activeContainer(){return this.config.container}async init(){St(),this.stage=new ux,await this.stage.init(this.config.mode,this.config.container),this.avatar=new fx(this.stage.stageWidth,this.stage.stageHeight),this.stage.app.stage.addChild(this.avatar.container),await this.loadIdleAsset(),this.avatarFrame=new OC,this.stage.rootElement&&$i(this.stage.rootElement),this.bubble=new NC(this.widgetPrompts??void 0),this.bubble.onClick=()=>this.onAvatarClick(),this.stage.rootElement&&(this.stage.rootElement.style.position="relative",this.stage.rootElement.appendChild(this.bubble.el)),this.avatar.setInteractive(()=>this.onAvatarClick()),this.chatPill=new of,this.chatPill.init(this.staffAvatarUrl,this.idleVideoUrl,this.staffDisplayName),this.chatPill.onClick=()=>this.onAvatarClick(),this.isInline?(setTimeout(()=>{var t;(this.state==="idle"||this.state==="teasing")&&!this.homeVisible&&((t=this.chatPill)==null?void 0:t.state)==="hidden"&&this.chatPill.showNamed()},5e3),this.startHomeObserver()):this.homeVisible=!1,this.setupTrigger(),this.startVisionLoop(),window.addEventListener("beforeunload",()=>{var e;(this.state==="active"||this.state==="connecting")&&((e=this.logger)==null||e.flush())}),console.log("[HolostaffWidget] Initialized",{staffId:this.config.staffId,trigger:this.config.trigger,visionEnabled:!!this.config.visionWsUrl})}async loadIdleAsset(){if(!(!this.avatar||!this.stage)){if(this.idleVideoUrl)try{if(this.isInline&&this.stage.inlineTarget){const e=this.stage.inlineTarget;e.style.position="relative";const t=document.createElement("div");t.className="hs-inline-card",t.setAttribute("data-hs-theme","dark"),Object.assign(t.style,{position:"absolute",inset:"0",display:"flex",flexDirection:"column",borderRadius:"var(--hs-radius-lg)",overflow:"hidden",background:"var(--hs-glass-bg)",backdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",WebkitBackdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",border:"1px solid var(--hs-glass-border)",boxShadow:"var(--hs-glass-shadow)",cursor:"pointer",padding:"var(--hs-space-3)",boxSizing:"border-box"});const i=document.createElement("div");Object.assign(i.style,{flex:"1",overflow:"hidden",position:"relative",borderRadius:"var(--hs-radius-md)",border:"1px solid var(--hs-glass-border)"});const r=document.createElement("video");r.src=this.idleVideoUrl,r.autoplay=!0,r.loop=!0,r.muted=!0,r.playsInline=!0,r.setAttribute("playsinline",""),Object.assign(r.style,{width:"100%",height:"100%",objectFit:"cover",display:"block"}),i.appendChild(r),t.appendChild(i);const n=document.createElement("div");Object.assign(n.style,{padding:"var(--hs-space-3) var(--hs-space-4)",textAlign:"center"});const o=document.createElement("div");Object.assign(o.style,{color:"var(--hs-text-primary)",fontSize:"var(--hs-text-base)",fontWeight:"var(--hs-weight-semibold)",fontFamily:"var(--hs-font)",lineHeight:"var(--hs-line-height)"}),o.textContent=`${this.staffDisplayName}, your AI copilot`,n.appendChild(o);const a=document.createElement("div");Object.assign(a.style,{color:"var(--hs-text-tertiary)",fontSize:"var(--hs-text-xs)",fontFamily:"var(--hs-font)",marginTop:"2px"}),a.textContent="Powered by Holostaff",n.appendChild(a),t.appendChild(n),t.addEventListener("click",()=>this.onAvatarClick()),e.appendChild(t),this.stage.rootElement&&(this.stage.rootElement.style.display="none")}else{const e=this.stage.rootElement;if(!e)throw new Error("Widget root not available");await this.avatar.loadIdleVideo(this.idleVideoUrl,e)}return}catch{console.warn("[HolostaffWidget] Failed to load idle video, trying image fallback")}this.idleImageUrl?await this.avatar.loadIdleImage(this.idleImageUrl):console.warn("[HolostaffWidget] No idle video or image configured")}}setIdleVideo(e){this.idleVideoUrl=e}setIdleImage(e){this.idleImageUrl=e}setObserver(e,t){this.rrwebRecorder=e,this.visionWs=t,this.externalObserver=!0}setStaffInfo(e,t){this.staffDisplayName=e,this.staffAvatarUrl=t}setupTrigger(){if(this.isInline){this.showAvatarOnly();return}if(this.config.visionWsUrl){this.showAvatarOnly();return}switch(this.config.trigger){case"scroll":this.setupScrollTrigger();break;case"delay":setTimeout(()=>this.showTeaser(),this.config.delayMs);break;case"immediate":this.showTeaser();break}}setupScrollTrigger(){this.scrollHandler=()=>{const e=window.scrollY,t=document.documentElement.scrollHeight-window.innerHeight,i=t>0?e/t:0;i>=this.config.scrollThreshold&&this.state==="idle"?this.showTeaser():i<this.config.scrollThreshold*.5&&this.state==="teasing"&&this.hideTeaser()},window.addEventListener("scroll",this.scrollHandler,{passive:!0})}showAvatarOnly(){this.state!=="idle"||!this.avatar||!this.stage||(this.state="teasing",this.avatar.slideIn(this.stage.app.ticker))}showTeaser(){this.state!=="idle"||!this.avatar||!this.stage||(this.state="teasing",this.avatar.slideIn(this.stage.app.ticker),this.bubbleTimer=setTimeout(()=>{var e;return(e=this.bubble)==null?void 0:e.start()},qC))}hideTeaser(){var e;this.state!=="teasing"||!this.avatar||!this.stage||(this.state="idle",this.bubbleTimer&&(clearTimeout(this.bubbleTimer),this.bubbleTimer=null),(e=this.bubble)==null||e.stop(),this.avatar.slideOut(this.stage.app.ticker))}async onAvatarClick(){var e,t,i,r,n,o,a,l,c,h,u,f;if(!(this.state!=="teasing"&&this.state!=="idle")){if(this.state="connecting",(e=this.bubble)==null||e.stop(),(t=this.bubble)==null||t.hideStatic(),(i=this.actionExecutor)==null||i.destroy(),this.actionExecutor=null,this.isInline){(r=this.chatPill)==null||r.showConnecting();const d=(o=(n=this.stage)==null?void 0:n.inlineTarget)==null?void 0:o.querySelector(".hs-inline-card video");d&&d.pause()}else{(a=this.stage)!=null&&a.rootElement&&(this.stage.rootElement.style.display="");const d=document.querySelector("#holostaff-widget-root video");d&&d.pause(),(l=this.bubble)==null||l.showStatic("Connecting...")}console.log("[HolostaffWidget] Starting conversation...");try{this.sessionResponse=await Bf(this.config.staffId,this.config.backendUrl),console.log("[HolostaffWidget] Session tokens received"),this.logger=new uv({staffId:this.config.staffId,staffName:this.sessionResponse.staff.name,backendUrl:this.config.backendUrl}),await this.connectAnam(),await this.connectRealtimeApi(),this.state="active",this.setAvatarState("listening"),this.sessionStartTime=Date.now(),(c=this.bubble)==null||c.hideStatic(),this.showControls(),this.startSessionTimers(),(h=this.visionWs)==null||h.sendConversationStarted(),(u=this.rrwebRecorder)==null||u.pause(),console.log("[HolostaffWidget] Conversation active")}catch(d){console.error("[HolostaffWidget] Failed to start conversation:",d),(f=this.bubble)==null||f.hideStatic(),this.endConversation()}}}moveToStage(){var t;if(!this.isInline||!((t=this.stage)!=null&&t.inlineTarget))return;const e=this.stage.inlineTarget.querySelector(".hs-inline-card");e&&(e.style.display="none"),this.stage.inlineTarget.querySelectorAll("video").forEach(i=>{i instanceof HTMLVideoElement&&i.pause()}),this.homePlaceholder=document.createElement("div"),this.homePlaceholder.setAttribute("data-hs-theme","dark"),Object.assign(this.homePlaceholder.style,{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",color:"var(--hs-text-secondary)",fontSize:"var(--hs-text-sm)",fontFamily:"var(--hs-font)",textAlign:"center",padding:"var(--hs-space-4)",boxSizing:"border-box"}),this.homePlaceholder.innerHTML="Agent is active below ↓",this.stage.inlineTarget.appendChild(this.homePlaceholder),this.stageBackdrop=new jC,this.stageEl=this.stageBackdrop.el,this.stageBackdrop.show(),console.log("[HolostaffWidget] Moved to glass stage (bottom-center)")}returnToHome(){var t,i,r;if((t=this.stageBackdrop)==null||t.destroy(),this.stageBackdrop=null,this.stageEl=null,(i=this.homePlaceholder)==null||i.remove(),this.homePlaceholder=null,!((r=this.stage)!=null&&r.inlineTarget))return;const e=this.stage.inlineTarget.querySelector(".hs-inline-card");e&&(e.style.display=""),this.stage.inlineTarget.querySelectorAll(".hs-inline-card video").forEach(n=>{n.style.display="",n instanceof HTMLVideoElement&&n.play()}),console.log("[HolostaffWidget] Returned to home (inline container)")}startHomeObserver(){var i;this.stopHomeObserver();const e=(i=this.stage)==null?void 0:i.inlineTarget;if(!e)return;const t=e.getBoundingClientRect();this.homeVisible=t.top<window.innerHeight&&t.bottom>0,this.homeObserver=new IntersectionObserver(([r])=>{const n=this.homeVisible;if(this.homeVisible=r.isIntersecting,this.homeVisible&&!this.homeEverSeen&&(this.homeEverSeen=!0),(this.state==="idle"||this.state==="teasing")&&this.chatPill)if(this.homeVisible){if(this.pillProtected){this.pillProtected=!1;return}this.chatPill.hide()}else!this.homeVisible&&n&&this.homeEverSeen?this.chatPill.showNamed():!this.homeVisible&&!this.homeEverSeen&&this.chatPill.state==="hidden"&&this.chatPill.showNamed()},{threshold:.1}),this.homeObserver.observe(e)}stopHomeObserver(){var e;(e=this.homeObserver)==null||e.disconnect(),this.homeObserver=null}async connectAnam(){this.sessionResponse&&(this.anamSession=new ev({sessionToken:this.sessionResponse.anamSessionToken,inlineMode:this.isInline&&!!this.stageBackdrop}),this.anamSession.onConnected=()=>{console.log("[HolostaffWidget] Anam connected")},this.anamSession.onVideoReady=e=>{var t,i,r;console.log("[HolostaffWidget] Anam avatar video ready"),(t=this.bubble)==null||t.hideStatic(),(i=this.chatPill)==null||i.hide(),this.isInline?(this.moveToStage(),(r=this.stageBackdrop)==null||r.appendContent(e)):this.avatar&&this.stage&&this.avatar.setLiveVideo(e,this.stage.app.ticker)},this.anamSession.onTalkStreamInterrupted=()=>{console.log("[HolostaffWidget] Anam talk stream interrupted")},this.anamSession.onDisconnected=e=>{console.log("[HolostaffWidget] Anam disconnected:",e),this.endConversation()},this.anamSession.onError=e=>{console.error("[HolostaffWidget] Anam error:",e.message)},await this.anamSession.connect(),console.log("[HolostaffWidget] Anam session ready"))}async connectRealtimeApi(){var o;if(!this.sessionResponse)return;const e=document.title||"",t=location.href,i=((o=document.querySelector('meta[name="description"]'))==null?void 0:o.getAttribute("content"))||"",r=Array.from(document.querySelectorAll("h1, h2, h3")).slice(0,10).map(a=>{var l;return(l=a.textContent)==null?void 0:l.trim()}).filter(Boolean).join(" | ");let n=(this.sessionResponse.staff.instructions??"")+`
|
|
1065
1065
|
|
|
1066
1066
|
## Current Page
|
|
1067
1067
|
Title: ${e}
|
|
@@ -1076,5 +1076,5 @@ Then you can scroll to elements, highlight them, click links/buttons, or fill fo
|
|
|
1076
1076
|
All actions except form filling require the visitor to confirm before executing.`;this.visionContext&&(n+=`
|
|
1077
1077
|
|
|
1078
1078
|
## Context from observing the user's session
|
|
1079
|
-
`+this.visionContext,this.visionContext=null),this.realtimeSession=new _x({ephemeralKey:this.sessionResponse.realtimeEphemeralKey,webrtcUrl:this.sessionResponse.realtimeWebrtcUrl,voice:this.sessionResponse.staff.voiceId,instructions:n,tools:QC}),this.domAnalyzer=new nv,this.highlightRenderer=new YC,this.confirmationPrompt=new VC,this.realtimeSession.onConnected=()=>{var l,c,h,u;console.log("[HolostaffWidget] Realtime API connected");const a=(l=this.sessionResponse)==null?void 0:l.staff.openingText;a!=null&&a.trim()&&((c=this.realtimeSession)==null||c.sendJSON({type:"conversation.item.create",item:{type:"message",role:"user",content:[{type:"input_text",text:"(conversation started — greet the visitor now)"}]}}),(h=this.realtimeSession)==null||h.sendJSON({type:"conversation.item.create",item:{type:"message",role:"assistant",content:[{type:"text",text:a}]}}),(u=this.realtimeSession)==null||u.sendJSON({type:"response.create"}))},this.realtimeSession.onDisconnected=()=>{console.log("[HolostaffWidget] Realtime API disconnected"),(this.state==="active"||this.state==="connecting")&&this.endConversation()},this.realtimeSession.onRemoteTrack=async a=>{console.log("[HolostaffWidget] Remote audio track → starting audio forwarder"),this.audioForwarder=new vx,this.audioForwarder.onAudioChunk=l=>{var c;(c=this.anamSession)==null||c.sendAudioChunk(l)},await this.audioForwarder.start(a)},this.overlayRenderer=new LC,this.toolHandler=new av({realtimeSession:this.realtimeSession,domAnalyzer:this.domAnalyzer,pageActions:new lv(this.domAnalyzer,this.highlightRenderer),overlayActions:new cv(this.overlayRenderer),confirmationPrompt:this.confirmationPrompt,staffId:this.config.staffId,backendUrl:this.config.backendUrl}),this.toolHandler.onToolCall=(a,l)=>{var c;(c=this.logger)==null||c.addAction(a,l)},this.realtimeSession.onDataMessage=a=>{this.handleDataChannelMessage(a)},this.realtimeSession.onError=a=>{console.error("[HolostaffWidget] Realtime error:",a.message),this.endConversation()},await this.realtimeSession.connect()}handleDataChannelMessage(e){var i,r,n,o,a,l,c,h;if((i=this.toolHandler)!=null&&i.handleMessage(e))return;const t=e.type;switch(t){case"session.created":case"session.updated":console.log("[HolostaffWidget] Data:",t);break;case"input_audio_buffer.speech_started":console.log("[HolostaffWidget] User started speaking"),(r=this.anamSession)==null||r.interrupt(),(n=this.audioForwarder)==null||n.pause(),this.setAvatarState("listening"),this.resetInactivityTimer();break;case"input_audio_buffer.speech_stopped":console.log("[HolostaffWidget] User stopped speaking"),this.setAvatarState("thinking");break;case"response.created":console.log("[HolostaffWidget] AI response started"),(o=this.audioForwarder)==null||o.resume(),this.setAvatarState("speaking");break;case"response.done":console.log("[HolostaffWidget] AI response done"),(a=this.anamSession)==null||a.endSequence(),this.setAvatarState("listening"),this.resetInactivityTimer(),this.extractAiTranscript(e.response);break;case"conversation.item.input_audio_transcription.completed":console.log("[HolostaffWidget] User said:",e.transcript),(l=this.logger)==null||l.addUserMessage(e.transcript??"");break;case"error":console.error("[HolostaffWidget] Realtime error event:",e.error);break;case"response.cancelled":case"response.canceled":case"response.failed":console.warn("[HolostaffWidget] Response ended:",t),(c=this.anamSession)==null||c.endSequence(),(h=this.audioForwarder)==null||h.pause(),this.setAvatarState("listening");break}}extractAiTranscript(e){if(!(!(e!=null&&e.output)||!this.logger)){for(const t of e.output)if(t.type==="message"&&t.content)for(const i of t.content)i.transcript?this.logger.addStaffMessage(i.transcript):i.text&&this.logger.addStaffMessage(i.text)}}setAvatarState(e){if(this.avatarState===e)return;const t=this.avatarState;this.avatarState=e,console.log(`[HolostaffWidget] Avatar: ${t} → ${e}`)}showControls(){this.controls=new WC,this.controls.onMinimize=()=>{var e;this.state="minimized",this.avatar&&this.stage&&this.avatar.slideOut(this.stage.app.ticker),(e=this.overlayRenderer)==null||e.dismissAll(),console.log("[HolostaffWidget] Minimized")},this.controls.onRestore=()=>{this.state="active",this.avatar&&this.stage&&this.avatar.slideIn(this.stage.app.ticker),console.log("[HolostaffWidget] Restored")},this.controls.onClose=()=>{console.log("[HolostaffWidget] Close button clicked"),this.endConversation()},this.controls.show()}startSessionTimers(){this.maxDurationWarnTimer=setTimeout(()=>{var e,t;console.log("[HolostaffWidget] Session approaching max duration"),(e=this.realtimeSession)==null||e.sendJSON({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:"The session will end in about one minute. Please wrap up the conversation gracefully."}]}}),(t=this.realtimeSession)==null||t.sendJSON({type:"response.create"})},ZC),this.maxDurationTimer=setTimeout(()=>{console.log("[HolostaffWidget] Max session duration reached"),this.endConversation()},KC),this.resetInactivityTimer()}resetInactivityTimer(){this.inactivityTimer&&clearTimeout(this.inactivityTimer),this.inactivityCloseTimer&&clearTimeout(this.inactivityCloseTimer),this.inactivityTimer=setTimeout(()=>{var e,t;this.state==="active"&&(console.log("[HolostaffWidget] Inactivity — prompting user"),(e=this.realtimeSession)==null||e.sendJSON({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:'The visitor has been silent for a while. Ask them "Still there?" in a friendly way.'}]}}),(t=this.realtimeSession)==null||t.sendJSON({type:"response.create"}),this.inactivityCloseTimer=setTimeout(()=>{this.state==="active"&&(console.log("[HolostaffWidget] Inactivity — auto-closing"),this.endConversation())},JC-lf))},lf)}clearSessionTimers(){this.maxDurationTimer&&(clearTimeout(this.maxDurationTimer),this.maxDurationTimer=null),this.maxDurationWarnTimer&&(clearTimeout(this.maxDurationWarnTimer),this.maxDurationWarnTimer=null),this.inactivityTimer&&(clearTimeout(this.inactivityTimer),this.inactivityTimer=null),this.inactivityCloseTimer&&(clearTimeout(this.inactivityCloseTimer),this.inactivityCloseTimer=null)}endConversation(){var t,i,r,n,o,a,l,c,h,u,f,d,g;(t=this.logger)==null||t.flush(),this.logger=null,this.clearSessionTimers(),(i=this.controls)==null||i.hide(),this.controls=null,(r=this.audioForwarder)==null||r.stop(),this.audioForwarder=null,(n=this.anamSession)==null||n.close(),this.anamSession=null,(o=this.realtimeSession)==null||o.close(),this.realtimeSession=null,this.sessionResponse=null,this.avatarState="idle",this.toolHandler=null,this.domAnalyzer=null,(a=this.highlightRenderer)==null||a.clearAll(),this.highlightRenderer=null,(l=this.confirmationPrompt)==null||l.dismiss(),this.confirmationPrompt=null,(c=this.overlayRenderer)==null||c.dismissAll(),this.overlayRenderer=null,this.avatar&&this.stage&&this.avatar.clearLiveVideo(this.stage.app.ticker);const e=this.buildConversationSummary();(h=this.visionWs)==null||h.sendConversationEnded(e),(u=this.rrwebRecorder)==null||u.resume(),this.hasHadConversation=!0,this.state="idle",document.querySelectorAll('[id^="anam-avatar-wrapper"]').forEach(_=>_.remove()),document.querySelectorAll('video[id^="anam-avatar-video"]').forEach(_=>_.remove()),this.isInline?(this.returnToHome(),this.pillProtected=!0,(f=this.chatPill)==null||f.restoreName(),(d=this.chatPill)==null||d.showNamed(),this.attachActionExecutor()):(this.avatar&&(this.avatar.container.visible=!1),(g=this.stage)!=null&&g.rootElement&&(this.stage.rootElement.style.display="none"),this.showChatPill()),console.log("[HolostaffWidget] Conversation ended")}showChatPill(){this.chatPill||(this.chatPill=new of,this.chatPill.init(this.staffAvatarUrl,this.idleVideoUrl,this.staffDisplayName),this.chatPill.onClick=()=>this.onAvatarClick()),this.chatPill.showNamed()}hideChatPill(){var e;(e=this.chatPill)==null||e.hide()}startVisionLoop(){if(this.externalObserver&&this.visionWs){this.attachActionExecutor(),console.log("[HolostaffWidget] Action executor attached to external observer");return}const e=this.config.visionWsUrl;e&&(this.rrwebRecorder=new Ad,this.visionWs=new Id(e,{staffId:this.config.staffId,visitorId:this.visitorId,pageUrl:location.href,pageTitle:document.title}),this.rrwebRecorder.onEvent=t=>{var i;(i=this.visionWs)==null||i.sendRRWebEvent(t)},this.attachActionExecutor(),this.visionWs.connect(),this.config.visionConsent==="required"?console.log("[HolostaffWidget] Vision loop started (recording deferred — consent required)"):(this.rrwebRecorder.start(),console.log("[HolostaffWidget] Vision loop started",{visitorId:this.visitorId})))}attachActionExecutor(){var e;this.visionWs&&(this.actionExecutor=new AC({wsClient:this.visionWs,getWidgetState:()=>this.state,getHomeVisible:()=>this.homeVisible,inlineTarget:((e=this.stage)==null?void 0:e.inlineTarget)??null,pill:this.chatPill}),this.actionExecutor.onAccept=t=>{console.log("[HolostaffWidget] Suggestion accepted — starting conversation with vision context"),this.visionContext=t,this.onAvatarClick()})}stopVisionLoop(){var e,t,i;(e=this.actionExecutor)==null||e.destroy(),this.actionExecutor=null,this.externalObserver||((t=this.rrwebRecorder)==null||t.stop(),this.rrwebRecorder=null,(i=this.visionWs)==null||i.close(),this.visionWs=null)}buildConversationSummary(){var e;return((e=this.logger)==null?void 0:e.getSummary())??"Conversation ended (no transcript available)."}getOrCreateVisitorId(){var r;const e="hs_visitor_id",t=(r=document.cookie.split("; ").find(n=>n.startsWith(`${e}=`)))==null?void 0:r.split("=")[1];if(t)return t;const i=`v_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`;return document.cookie=`${e}=${i}; max-age=${365*24*60*60}; path=/; SameSite=Lax`,i}pause(){var e,t,i;this.paused||(this.paused=!0,console.log("[HolostaffWidget] Presenter paused (page not targeted — observer continues)"),(this.state==="active"||this.state==="connecting")&&this.endConversation(),(e=this.stage)!=null&&e.rootElement&&(this.stage.rootElement.style.display="none"),this.hideChatPill(),(t=this.bubble)==null||t.stop(),(i=this.actionExecutor)==null||i.destroy(),this.actionExecutor=null)}resume(){var e;this.paused&&(this.paused=!1,console.log("[HolostaffWidget] Presenter resumed (page targeted)"),(e=this.stage)!=null&&e.rootElement&&(this.stage.rootElement.style.display=""),this.attachActionExecutor(),(this.state==="idle"||this.state==="teasing")&&(this.state="idle",this.setupTrigger()))}updateContainer(e){var r,n;const t=e?"inline":"floating";(this.config.container!==e||this.config.mode!==t)&&(console.log("[HolostaffWidget] Updating container:",e??"(floating)"),this.config={...this.config,mode:t,container:e},this.stage&&((this.state==="active"||this.state==="connecting")&&this.endConversation(),(r=this.bubble)==null||r.destroy(),(n=this.avatar)==null||n.destroy(),this.stage.destroy(),this.stage=null,this.avatar=null,this.bubble=null,this.state="idle",this.init()))}destroy(){var e,t,i;this.state="destroyed",this.endConversation(),this.hideChatPill(),this.stopHomeObserver(),this.stopVisionLoop(),this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler),this.bubbleTimer&&clearTimeout(this.bubbleTimer),(e=this.bubble)==null||e.destroy(),(t=this.avatar)==null||t.destroy(),(i=this.stage)==null||i.destroy(),this.bubble=null,this.avatar=null,this.stage=null}}function eS(s){return!s||s.length===0?[{pattern:"*"}]:s.map(e=>typeof e=="string"?{pattern:e}:e)}function tS(s,e){if(e==="*")return!0;if(!e.endsWith("/*")){const n=s.replace(/\/+$/,"")||"/",o=e.replace(/\/+$/,"")||"/";return n===o}const t=e.slice(0,-2),i=s.replace(/\/+$/,"")||"/",r=t.replace(/\/+$/,"")||"/";return i===r||i.startsWith(r+"/")}function hf(s,e){for(const t of e)if(tS(s,t.pattern))return t;return null}class iS{constructor(e){this.currentPath=location.pathname,this.onChange=e,this.origPushState=history.pushState.bind(history),this.origReplaceState=history.replaceState.bind(history),history.pushState=(...t)=>{this.origPushState(...t),this.check()},history.replaceState=(...t)=>{this.origReplaceState(...t),this.check()},window.addEventListener("popstate",()=>this.check())}check(){const e=location.pathname;e!==this.currentPath&&(this.currentPath=e,this.onChange(e))}destroy(){history.pushState=this.origPushState,history.replaceState=this.origReplaceState}}function sS(){var i;const s="hs_visitor_id",e=(i=document.cookie.split("; ").find(r=>r.startsWith(`${s}=`)))==null?void 0:i.split("=")[1];if(e)return e;const t=`v_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`;return document.cookie=`${s}=${t}; max-age=${365*24*60*60}; path=/; SameSite=Lax`,t}function rS(){const s=document.currentScript??document.querySelector("script[data-staff-id]");if(!s){console.error("[HolostaffWidget] Could not find script tag with data-staff-id");return}try{let e=function(r,n,o,a,l){const c=new cf(r,o);return a&&l&&c.setObserver(a,l),n!=null&&n.idleVideoUrl?c.setIdleVideo(n.idleVideoUrl):n!=null&&n.avatarImageUrl&&c.setIdleImage(n.avatarImageUrl),n&&c.setStaffInfo(n.name,n.avatarImageUrl),c};const t=Rf(s);async function i(){let r=t,n=null,o=null;try{o=await Nf(t.staffId,t.backendUrl),r=Of(t,s,o),n=o.widgetPrompts}catch(g){if(g.name==="WidgetDisabledError"){console.log("[HolostaffWidget] Agent is not active — widget suppressed");return}console.warn("[HolostaffWidget] Failed to fetch server config, using embed defaults:",g)}const a=eS(o==null?void 0:o.pagePatterns),l=sS();let c=null,h=null;r.visionWsUrl&&(c=new Ad,h=new Id(r.visionWsUrl,{staffId:r.staffId,visitorId:l,pageUrl:location.href,pageTitle:document.title,pagePatterns:a.map(g=>{const _={pattern:g.pattern};return g.container&&(_.container=g.container),_})}),c.onEvent=g=>{h==null||h.sendRRWebEvent(g)},h.connect(),r.visionConsent==="required"?console.log("[HolostaffWidget] Observer started (recording deferred — consent required)"):(c.start(),console.log("[HolostaffWidget] Observer started on all pages",{visitorId:l})));let u=hf(location.pathname,a),f=null;if(u){let g=r;u.container&&(g={...r,mode:"inline",container:u.container}),f=e(g,o,n,c,h),window.holostaffWidget=f,f.init()}else console.log("[HolostaffWidget] No matching page pattern for",location.pathname,"— presenter not loaded (observer active)");const d=new iS(g=>{h==null||h.sendPageChanged(location.href,g,document.title);const _=hf(g,a);if(_&&!f){console.log("[HolostaffWidget] SPA navigated to matching page:",g);let b=r;_.container&&(b={...r,mode:"inline",container:_.container}),f=e(b,o,n,c,h),window.holostaffWidget=f,f.init()}else if(_&&f){const b=_.container??null;b!==f.activeContainer&&f.updateContainer(b),f.resume()}else!_&&f&&f.pause()});window.__holostaffSPARouter=d}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>i()):i()}catch(e){console.error("[HolostaffWidget]",e)}}rS(),Q.add(Qm),Q.mixin(Ve,eg),Q.add(sh),Q.add(rh),Q.mixin(Ve,sy),Q.add(lh),Q.add(oh);const nS=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),oS=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));fi.HolostaffWidget=cf,Object.defineProperty(fi,Symbol.toStringTag,{value:"Module"})}));
|
|
1079
|
+
`+this.visionContext,this.visionContext=null),this.realtimeSession=new _x({ephemeralKey:this.sessionResponse.realtimeEphemeralKey,webrtcUrl:this.sessionResponse.realtimeWebrtcUrl,voice:this.sessionResponse.staff.voiceId,instructions:n,tools:QC}),this.domAnalyzer=new nv,this.highlightRenderer=new YC,this.confirmationPrompt=new VC,this.realtimeSession.onConnected=()=>{var l,c,h,u;console.log("[HolostaffWidget] Realtime API connected");const a=(l=this.sessionResponse)==null?void 0:l.staff.openingText;a!=null&&a.trim()&&((c=this.realtimeSession)==null||c.sendJSON({type:"conversation.item.create",item:{type:"message",role:"user",content:[{type:"input_text",text:"(conversation started — greet the visitor now)"}]}}),(h=this.realtimeSession)==null||h.sendJSON({type:"conversation.item.create",item:{type:"message",role:"assistant",content:[{type:"text",text:a}]}}),(u=this.realtimeSession)==null||u.sendJSON({type:"response.create"}))},this.realtimeSession.onDisconnected=()=>{console.log("[HolostaffWidget] Realtime API disconnected"),(this.state==="active"||this.state==="connecting")&&this.endConversation()},this.realtimeSession.onRemoteTrack=async a=>{console.log("[HolostaffWidget] Remote audio track → starting audio forwarder"),this.audioForwarder=new vx,this.audioForwarder.onAudioChunk=l=>{var c;(c=this.anamSession)==null||c.sendAudioChunk(l)},await this.audioForwarder.start(a)},this.overlayRenderer=new LC,this.toolHandler=new av({realtimeSession:this.realtimeSession,domAnalyzer:this.domAnalyzer,pageActions:new lv(this.domAnalyzer,this.highlightRenderer),overlayActions:new cv(this.overlayRenderer),confirmationPrompt:this.confirmationPrompt,staffId:this.config.staffId,backendUrl:this.config.backendUrl,skills:this.sessionResponse.skills??{}}),this.toolHandler.onToolCall=(a,l)=>{var c;(c=this.logger)==null||c.addAction(a,l)},this.realtimeSession.onDataMessage=a=>{this.handleDataChannelMessage(a)},this.realtimeSession.onError=a=>{console.error("[HolostaffWidget] Realtime error:",a.message),this.endConversation()},await this.realtimeSession.connect()}handleDataChannelMessage(e){var i,r,n,o,a,l,c,h;if((i=this.toolHandler)!=null&&i.handleMessage(e))return;const t=e.type;switch(t){case"session.created":case"session.updated":console.log("[HolostaffWidget] Data:",t);break;case"input_audio_buffer.speech_started":console.log("[HolostaffWidget] User started speaking"),(r=this.anamSession)==null||r.interrupt(),(n=this.audioForwarder)==null||n.pause(),this.setAvatarState("listening"),this.resetInactivityTimer();break;case"input_audio_buffer.speech_stopped":console.log("[HolostaffWidget] User stopped speaking"),this.setAvatarState("thinking");break;case"response.created":console.log("[HolostaffWidget] AI response started"),(o=this.audioForwarder)==null||o.resume(),this.setAvatarState("speaking");break;case"response.done":console.log("[HolostaffWidget] AI response done"),(a=this.anamSession)==null||a.endSequence(),this.setAvatarState("listening"),this.resetInactivityTimer(),this.extractAiTranscript(e.response);break;case"conversation.item.input_audio_transcription.completed":console.log("[HolostaffWidget] User said:",e.transcript),(l=this.logger)==null||l.addUserMessage(e.transcript??"");break;case"error":console.error("[HolostaffWidget] Realtime error event:",e.error);break;case"response.cancelled":case"response.canceled":case"response.failed":console.warn("[HolostaffWidget] Response ended:",t),(c=this.anamSession)==null||c.endSequence(),(h=this.audioForwarder)==null||h.pause(),this.setAvatarState("listening");break}}extractAiTranscript(e){if(!(!(e!=null&&e.output)||!this.logger)){for(const t of e.output)if(t.type==="message"&&t.content)for(const i of t.content)i.transcript?this.logger.addStaffMessage(i.transcript):i.text&&this.logger.addStaffMessage(i.text)}}setAvatarState(e){if(this.avatarState===e)return;const t=this.avatarState;this.avatarState=e,console.log(`[HolostaffWidget] Avatar: ${t} → ${e}`)}showControls(){this.controls=new WC,this.controls.onMinimize=()=>{var e;this.state="minimized",this.avatar&&this.stage&&this.avatar.slideOut(this.stage.app.ticker),(e=this.overlayRenderer)==null||e.dismissAll(),console.log("[HolostaffWidget] Minimized")},this.controls.onRestore=()=>{this.state="active",this.avatar&&this.stage&&this.avatar.slideIn(this.stage.app.ticker),console.log("[HolostaffWidget] Restored")},this.controls.onClose=()=>{console.log("[HolostaffWidget] Close button clicked"),this.endConversation()},this.controls.show()}startSessionTimers(){this.maxDurationWarnTimer=setTimeout(()=>{var e,t;console.log("[HolostaffWidget] Session approaching max duration"),(e=this.realtimeSession)==null||e.sendJSON({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:"The session will end in about one minute. Please wrap up the conversation gracefully."}]}}),(t=this.realtimeSession)==null||t.sendJSON({type:"response.create"})},ZC),this.maxDurationTimer=setTimeout(()=>{console.log("[HolostaffWidget] Max session duration reached"),this.endConversation()},KC),this.resetInactivityTimer()}resetInactivityTimer(){this.inactivityTimer&&clearTimeout(this.inactivityTimer),this.inactivityCloseTimer&&clearTimeout(this.inactivityCloseTimer),this.inactivityTimer=setTimeout(()=>{var e,t;this.state==="active"&&(console.log("[HolostaffWidget] Inactivity — prompting user"),(e=this.realtimeSession)==null||e.sendJSON({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:'The visitor has been silent for a while. Ask them "Still there?" in a friendly way.'}]}}),(t=this.realtimeSession)==null||t.sendJSON({type:"response.create"}),this.inactivityCloseTimer=setTimeout(()=>{this.state==="active"&&(console.log("[HolostaffWidget] Inactivity — auto-closing"),this.endConversation())},JC-lf))},lf)}clearSessionTimers(){this.maxDurationTimer&&(clearTimeout(this.maxDurationTimer),this.maxDurationTimer=null),this.maxDurationWarnTimer&&(clearTimeout(this.maxDurationWarnTimer),this.maxDurationWarnTimer=null),this.inactivityTimer&&(clearTimeout(this.inactivityTimer),this.inactivityTimer=null),this.inactivityCloseTimer&&(clearTimeout(this.inactivityCloseTimer),this.inactivityCloseTimer=null)}endConversation(){var t,i,r,n,o,a,l,c,h,u,f,d,g;(t=this.logger)==null||t.flush(),this.logger=null,this.clearSessionTimers(),(i=this.controls)==null||i.hide(),this.controls=null,(r=this.audioForwarder)==null||r.stop(),this.audioForwarder=null,(n=this.anamSession)==null||n.close(),this.anamSession=null,(o=this.realtimeSession)==null||o.close(),this.realtimeSession=null,this.sessionResponse=null,this.avatarState="idle",this.toolHandler=null,this.domAnalyzer=null,(a=this.highlightRenderer)==null||a.clearAll(),this.highlightRenderer=null,(l=this.confirmationPrompt)==null||l.dismiss(),this.confirmationPrompt=null,(c=this.overlayRenderer)==null||c.dismissAll(),this.overlayRenderer=null,this.avatar&&this.stage&&this.avatar.clearLiveVideo(this.stage.app.ticker);const e=this.buildConversationSummary();(h=this.visionWs)==null||h.sendConversationEnded(e),(u=this.rrwebRecorder)==null||u.resume(),this.hasHadConversation=!0,this.state="idle",document.querySelectorAll('[id^="anam-avatar-wrapper"]').forEach(_=>_.remove()),document.querySelectorAll('video[id^="anam-avatar-video"]').forEach(_=>_.remove()),this.isInline?(this.returnToHome(),this.pillProtected=!0,(f=this.chatPill)==null||f.restoreName(),(d=this.chatPill)==null||d.showNamed(),this.attachActionExecutor()):(this.avatar&&(this.avatar.container.visible=!1),(g=this.stage)!=null&&g.rootElement&&(this.stage.rootElement.style.display="none"),this.showChatPill()),console.log("[HolostaffWidget] Conversation ended")}showChatPill(){this.chatPill||(this.chatPill=new of,this.chatPill.init(this.staffAvatarUrl,this.idleVideoUrl,this.staffDisplayName),this.chatPill.onClick=()=>this.onAvatarClick()),this.chatPill.showNamed()}hideChatPill(){var e;(e=this.chatPill)==null||e.hide()}startVisionLoop(){if(this.externalObserver&&this.visionWs){this.attachActionExecutor(),console.log("[HolostaffWidget] Action executor attached to external observer");return}const e=this.config.visionWsUrl;e&&(this.rrwebRecorder=new Ad,this.visionWs=new Id(e,{staffId:this.config.staffId,visitorId:this.visitorId,pageUrl:location.href,pageTitle:document.title}),this.rrwebRecorder.onEvent=t=>{var i;(i=this.visionWs)==null||i.sendRRWebEvent(t)},this.attachActionExecutor(),this.visionWs.connect(),this.config.visionConsent==="required"?console.log("[HolostaffWidget] Vision loop started (recording deferred — consent required)"):(this.rrwebRecorder.start(),console.log("[HolostaffWidget] Vision loop started",{visitorId:this.visitorId})))}attachActionExecutor(){var e;this.visionWs&&(this.actionExecutor=new AC({wsClient:this.visionWs,getWidgetState:()=>this.state,getHomeVisible:()=>this.homeVisible,inlineTarget:((e=this.stage)==null?void 0:e.inlineTarget)??null,pill:this.chatPill}),this.actionExecutor.onAccept=t=>{console.log("[HolostaffWidget] Suggestion accepted — starting conversation with vision context"),this.visionContext=t,this.onAvatarClick()})}stopVisionLoop(){var e,t,i;(e=this.actionExecutor)==null||e.destroy(),this.actionExecutor=null,this.externalObserver||((t=this.rrwebRecorder)==null||t.stop(),this.rrwebRecorder=null,(i=this.visionWs)==null||i.close(),this.visionWs=null)}buildConversationSummary(){var e;return((e=this.logger)==null?void 0:e.getSummary())??"Conversation ended (no transcript available)."}getOrCreateVisitorId(){var r;const e="hs_visitor_id",t=(r=document.cookie.split("; ").find(n=>n.startsWith(`${e}=`)))==null?void 0:r.split("=")[1];if(t)return t;const i=`v_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`;return document.cookie=`${e}=${i}; max-age=${365*24*60*60}; path=/; SameSite=Lax`,i}pause(){var e,t,i;this.paused||(this.paused=!0,console.log("[HolostaffWidget] Presenter paused (page not targeted — observer continues)"),(this.state==="active"||this.state==="connecting")&&this.endConversation(),(e=this.stage)!=null&&e.rootElement&&(this.stage.rootElement.style.display="none"),this.hideChatPill(),(t=this.bubble)==null||t.stop(),(i=this.actionExecutor)==null||i.destroy(),this.actionExecutor=null)}resume(){var e;this.paused&&(this.paused=!1,console.log("[HolostaffWidget] Presenter resumed (page targeted)"),(e=this.stage)!=null&&e.rootElement&&(this.stage.rootElement.style.display=""),this.attachActionExecutor(),(this.state==="idle"||this.state==="teasing")&&(this.state="idle",this.setupTrigger()))}updateContainer(e){var r,n;const t=e?"inline":"floating";(this.config.container!==e||this.config.mode!==t)&&(console.log("[HolostaffWidget] Updating container:",e??"(floating)"),this.config={...this.config,mode:t,container:e},this.stage&&((this.state==="active"||this.state==="connecting")&&this.endConversation(),(r=this.bubble)==null||r.destroy(),(n=this.avatar)==null||n.destroy(),this.stage.destroy(),this.stage=null,this.avatar=null,this.bubble=null,this.state="idle",this.init()))}destroy(){var e,t,i;this.state="destroyed",this.endConversation(),this.hideChatPill(),this.stopHomeObserver(),this.stopVisionLoop(),this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler),this.bubbleTimer&&clearTimeout(this.bubbleTimer),(e=this.bubble)==null||e.destroy(),(t=this.avatar)==null||t.destroy(),(i=this.stage)==null||i.destroy(),this.bubble=null,this.avatar=null,this.stage=null}}function eS(s){return!s||s.length===0?[{pattern:"*"}]:s.map(e=>typeof e=="string"?{pattern:e}:e)}function tS(s,e){if(e==="*")return!0;if(!e.endsWith("/*")){const n=s.replace(/\/+$/,"")||"/",o=e.replace(/\/+$/,"")||"/";return n===o}const t=e.slice(0,-2),i=s.replace(/\/+$/,"")||"/",r=t.replace(/\/+$/,"")||"/";return i===r||i.startsWith(r+"/")}function hf(s,e){for(const t of e)if(tS(s,t.pattern))return t;return null}class iS{constructor(e){this.currentPath=location.pathname,this.onChange=e,this.origPushState=history.pushState.bind(history),this.origReplaceState=history.replaceState.bind(history),history.pushState=(...t)=>{this.origPushState(...t),this.check()},history.replaceState=(...t)=>{this.origReplaceState(...t),this.check()},window.addEventListener("popstate",()=>this.check())}check(){const e=location.pathname;e!==this.currentPath&&(this.currentPath=e,this.onChange(e))}destroy(){history.pushState=this.origPushState,history.replaceState=this.origReplaceState}}function sS(){var i;const s="hs_visitor_id",e=(i=document.cookie.split("; ").find(r=>r.startsWith(`${s}=`)))==null?void 0:i.split("=")[1];if(e)return e;const t=`v_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`;return document.cookie=`${s}=${t}; max-age=${365*24*60*60}; path=/; SameSite=Lax`,t}function rS(){const s=document.currentScript??document.querySelector("script[data-staff-id]");if(!s){console.error("[HolostaffWidget] Could not find script tag with data-staff-id");return}try{let e=function(r,n,o,a,l){const c=new cf(r,o);return a&&l&&c.setObserver(a,l),n!=null&&n.idleVideoUrl?c.setIdleVideo(n.idleVideoUrl):n!=null&&n.avatarImageUrl&&c.setIdleImage(n.avatarImageUrl),n&&c.setStaffInfo(n.name,n.avatarImageUrl),c};const t=Rf(s);async function i(){let r=t,n=null,o=null;try{o=await Nf(t.staffId,t.backendUrl),r=Of(t,s,o),n=o.widgetPrompts}catch(g){if(g.name==="WidgetDisabledError"){console.log("[HolostaffWidget] Agent is not active — widget suppressed");return}console.warn("[HolostaffWidget] Failed to fetch server config, using embed defaults:",g)}const a=eS(o==null?void 0:o.pagePatterns),l=sS();let c=null,h=null;r.visionWsUrl&&(c=new Ad,h=new Id(r.visionWsUrl,{staffId:r.staffId,visitorId:l,pageUrl:location.href,pageTitle:document.title,pagePatterns:a.map(g=>{const _={pattern:g.pattern};return g.container&&(_.container=g.container),_})}),c.onEvent=g=>{h==null||h.sendRRWebEvent(g)},h.connect(),r.visionConsent==="required"?console.log("[HolostaffWidget] Observer started (recording deferred — consent required)"):(c.start(),console.log("[HolostaffWidget] Observer started on all pages",{visitorId:l})));let u=hf(location.pathname,a),f=null;if(u){let g=r;u.container&&(g={...r,mode:"inline",container:u.container}),f=e(g,o,n,c,h),window.holostaffWidget=f,f.init()}else console.log("[HolostaffWidget] No matching page pattern for",location.pathname,"— presenter not loaded (observer active)");const d=new iS(g=>{h==null||h.sendPageChanged(location.href,g,document.title);const _=hf(g,a);if(_&&!f){console.log("[HolostaffWidget] SPA navigated to matching page:",g);let b=r;_.container&&(b={...r,mode:"inline",container:_.container}),f=e(b,o,n,c,h),window.holostaffWidget=f,f.init()}else if(_&&f){const b=_.container??null;b!==f.activeContainer&&f.updateContainer(b),f.resume()}else!_&&f&&f.pause()});window.__holostaffSPARouter=d}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>i()):i()}catch(e){console.error("[HolostaffWidget]",e)}}rS(),Q.add(Qm),Q.mixin(Ve,eg),Q.add(sh),Q.add(rh),Q.mixin(Ve,sy),Q.add(lh),Q.add(oh);const nS=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),oS=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));fi.HolostaffWidget=cf,Object.defineProperty(fi,Symbol.toStringTag,{value:"Module"})}));
|
|
1080
1080
|
//# sourceMappingURL=hs-widget.umd.js.map
|