holostaff-widget 3.0.0 → 3.0.2
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/{BufferResource-DeLlYxf8.js → BufferResource-6mO-PO_c.js} +4 -4
- package/dist/{BufferResource-DeLlYxf8.js.map → BufferResource-6mO-PO_c.js.map} +1 -1
- package/dist/{CanvasRenderer-BgLtSh22.js → CanvasRenderer-BL1L0Zug.js} +5 -5
- package/dist/{CanvasRenderer-BgLtSh22.js.map → CanvasRenderer-BL1L0Zug.js.map} +1 -1
- package/dist/{Geometry-Bdq2tsB3.js → Geometry-B-K9I6MO.js} +2 -2
- package/dist/{Geometry-Bdq2tsB3.js.map → Geometry-B-K9I6MO.js.map} +1 -1
- package/dist/{RenderTargetSystem-BCBByEgg.js → RenderTargetSystem-CahYKOD4.js} +3 -3
- package/dist/{RenderTargetSystem-BCBByEgg.js.map → RenderTargetSystem-CahYKOD4.js.map} +1 -1
- package/dist/{WebGLRenderer-3x7mgYt9.js → WebGLRenderer-Ci14rIHw.js} +5 -5
- package/dist/{WebGLRenderer-3x7mgYt9.js.map → WebGLRenderer-Ci14rIHw.js.map} +1 -1
- package/dist/{WebGPURenderer-CdbjQMqs.js → WebGPURenderer-SF1OSYpo.js} +6 -6
- package/dist/{WebGPURenderer-CdbjQMqs.js.map → WebGPURenderer-SF1OSYpo.js.map} +1 -1
- package/dist/{browserAll-DejMU3y7.js → browserAll-B97ymwYI.js} +3 -3
- package/dist/{browserAll-DejMU3y7.js.map → browserAll-B97ymwYI.js.map} +1 -1
- package/dist/{getTextureBatchBindGroup-CHJWR-eE.js → getTextureBatchBindGroup-BPB_9pp9.js} +3 -3
- package/dist/{getTextureBatchBindGroup-CHJWR-eE.js.map → getTextureBatchBindGroup-BPB_9pp9.js.map} +1 -1
- package/dist/hs-widget.es.js +1 -1
- package/dist/hs-widget.umd.js +60 -60
- package/dist/hs-widget.umd.js.map +1 -1
- package/dist/{index-C1ZbqCjI.js → index-qJyFW51-.js} +511 -502
- package/dist/index-qJyFW51-.js.map +1 -0
- package/dist/{webworkerAll-D5g5Ds7S.js → webworkerAll-DYG_wBG4.js} +3 -3
- package/dist/{webworkerAll-D5g5Ds7S.js.map → webworkerAll-DYG_wBG4.js.map} +1 -1
- package/package.json +1 -1
- package/dist/index-C1ZbqCjI.js.map +0 -1
package/dist/hs-widget.umd.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
(function(ds,$e){typeof exports=="object"&&typeof module<"u"?$e(exports):typeof define=="function"&&define.amd?define(["exports"],$e):(ds=typeof globalThis<"u"?globalThis:ds||self,$e(ds.HolostaffWidget={}))})(this,(function(ds){"use strict";const $e={mode:"floating",container:null,position:"bottom-center",trigger:"scroll",scrollThreshold:.3,delayMs:3e3,theme:"light",accentColor:null,language:"en",backendUrl:"https://us-central1-holostaff-ai.cloudfunctions.net",visionWsUrl:null,visionConsent:"auto"};function Tf(i){const e=i.dataset.staffId;if(!e)throw new Error("[HolostaffWidget] data-staff-id attribute is required");return{staffId:e,mode:i.dataset.mode??$e.mode,container:i.dataset.container??$e.container,position:i.dataset.position??$e.position,trigger:i.dataset.trigger??$e.trigger,scrollThreshold:parseFloat(i.dataset.scrollThreshold??"")||$e.scrollThreshold,delayMs:parseInt(i.dataset.delayMs??"",10)||$e.delayMs,theme:i.dataset.theme??$e.theme,accentColor:i.dataset.accentColor??$e.accentColor,language:i.dataset.language??$e.language,backendUrl:i.dataset.backendUrl??$e.backendUrl,visionWsUrl:i.dataset.visionWsUrl??$e.visionWsUrl,visionConsent:i.dataset.hsConsent??$e.visionConsent}}const Af=["bottom-center","bottom-left","bottom-right"],wf=["scroll","delay","immediate"],If=["light","dark","auto"];function Rf(i,e,t){const s={...i};return!e.dataset.trigger&&t.trigger&&wf.includes(t.trigger)&&(s.trigger=t.trigger),!e.dataset.position&&t.position&&Af.includes(t.position)&&(s.position=t.position),!e.dataset.theme&&t.theme&&If.includes(t.theme)&&(s.theme=t.theme),!e.dataset.scrollThreshold&&t.scrollThreshold!=null&&(s.scrollThreshold=t.scrollThreshold),!e.dataset.delayMs&&t.delayMs!=null&&(s.delayMs=t.delayMs),!e.dataset.visionWsUrl&&t.visionWsUrl&&(s.visionWsUrl=t.visionWsUrl),s}const Or="https://us-central1-holostaff-ai.cloudfunctions.net";async function Mf(i,e=Or){const t=await fetch(`${e}/widgetSession`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({staffId:i})});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||`Session request failed: ${t.status}`)}return t.json()}async function Pf(i,e=Or){const t=await fetch(`${e}/widgetConfig?staffId=${encodeURIComponent(i)}`);if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||`Config request failed: ${t.status}`)}return t.json()}async function kf(i,e,t,s=Or){const r=await fetch(`${s}/widgetPageAction`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({staffId:i,domSnapshot:e,instruction:t})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||`Page action request failed: ${r.status}`)}return r.json()}var A=(i=>(i.Application="application",i.WebGLPipes="webgl-pipes",i.WebGLPipesAdaptor="webgl-pipes-adaptor",i.WebGLSystem="webgl-system",i.WebGPUPipes="webgpu-pipes",i.WebGPUPipesAdaptor="webgpu-pipes-adaptor",i.WebGPUSystem="webgpu-system",i.CanvasSystem="canvas-system",i.CanvasPipesAdaptor="canvas-pipes-adaptor",i.CanvasPipes="canvas-pipes",i.Asset="asset",i.LoadParser="load-parser",i.ResolveParser="resolve-parser",i.CacheParser="cache-parser",i.DetectionParser="detection-parser",i.MaskEffect="mask-effect",i.BlendMode="blend-mode",i.TextureSource="texture-source",i.Environment="environment",i.ShapeBuilder="shape-builder",i.Batcher="batcher",i))(A||{});const Br=i=>{if(typeof i=="function"||typeof i=="object"&&i.extension){if(!i.extension)throw new Error("Extension class must have an extension object");i={...typeof i.extension!="object"?{type:i.extension}:i.extension,ref:i}}if(typeof i=="object")i={...i};else throw new Error("Invalid extension type");return typeof i.type=="string"&&(i.type=[i.type]),i},Di=(i,e)=>Br(i).priority??e,Q={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...i){return i.map(Br).forEach(e=>{e.type.forEach(t=>{var s,r;return(r=(s=this._removeHandlers)[t])==null?void 0:r.call(s,e)})}),this},add(...i){return i.map(Br).forEach(e=>{e.type.forEach(t=>{var n,o;const s=this._addHandlers,r=this._queue;s[t]?(o=s[t])==null||o.call(s,e):(r[t]=r[t]||[],(n=r[t])==null||n.push(e))})}),this},handle(i,e,t){var o;const s=this._addHandlers,r=this._removeHandlers;if(s[i]||r[i])throw new Error(`Extension type ${i} already has a handler`);s[i]=e,r[i]=t;const n=this._queue;return n[i]&&((o=n[i])==null||o.forEach(a=>e(a)),delete n[i]),this},handleByMap(i,e){return this.handle(i,t=>{t.name&&(e[t.name]=t.ref)},t=>{t.name&&delete e[t.name]})},handleByNamedList(i,e,t=-1){return this.handle(i,s=>{e.findIndex(n=>n.name===s.name)>=0||(e.push({name:s.name,value:s.ref}),e.sort((n,o)=>Di(o.value,t)-Di(n.value,t)))},s=>{const r=e.findIndex(n=>n.name===s.name);r!==-1&&e.splice(r,1)})},handleByList(i,e,t=-1){return this.handle(i,s=>{e.includes(s.ref)||(e.push(s.ref),e.sort((r,n)=>Di(n,t)-Di(r,t)))},s=>{const r=e.indexOf(s.ref);r!==-1&&e.splice(r,1)})},mixin(i,...e){for(const t of e)Object.defineProperties(i.prototype,Object.getOwnPropertyDescriptors(t))}},Of={extension:{type:A.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await Promise.resolve().then(()=>UC)}},Bf={extension:{type:A.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await Promise.resolve().then(()=>GC)}};class je{constructor(e,t,s){this._x=t||0,this._y=s||0,this._observer=e}clone(e){return new je(e??this._observer,this._x,this._y)}set(e=0,t=e){return(this._x!==e||this._y!==t)&&(this._x=e,this._y=t,this._observer._onUpdate(this)),this}copyFrom(e){return(this._x!==e.x||this._y!==e.y)&&(this._x=e.x,this._y=e.y,this._observer._onUpdate(this)),this}copyTo(e){return e.set(this._x,this._y),e}equals(e){return e.x===this._x&&e.y===this._y}toString(){return`[pixi.js/math:ObservablePoint x=${this._x} y=${this._y} scope=${this._observer}]`}get x(){return this._x}set x(e){this._x!==e&&(this._x=e,this._observer._onUpdate(this))}get y(){return this._y}set y(e){this._y!==e&&(this._y=e,this._observer._onUpdate(this))}}function oa(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Dr={exports:{}},aa;function Df(){return aa||(aa=1,(function(i){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function r(l,c,h){this.fn=l,this.context=c,this.once=h||!1}function n(l,c,h,u,p){if(typeof h!="function")throw new TypeError("The listener must be a function");var d=new r(h,u||l,p),g=t?t+c:c;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],d]:l._events[g].push(d):(l._events[g]=d,l._eventsCount++),l}function o(l,c){--l._eventsCount===0?l._events=new s:delete l._events[c]}function a(){this._events=new s,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],h,u;if(this._eventsCount===0)return c;for(u in h=this._events)e.call(h,u)&&c.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(h)):c},a.prototype.listeners=function(c){var h=t?t+c:c,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var p=0,d=u.length,g=new Array(d);p<d;p++)g[p]=u[p].fn;return g},a.prototype.listenerCount=function(c){var h=t?t+c:c,u=this._events[h];return u?u.fn?1:u.length:0},a.prototype.emit=function(c,h,u,p,d,g){var _=t?t+c:c;if(!this._events[_])return!1;var b=this._events[_],v=arguments.length,C,E;if(b.fn){switch(b.once&&this.removeListener(c,b.fn,void 0,!0),v){case 1:return b.fn.call(b.context),!0;case 2:return b.fn.call(b.context,h),!0;case 3:return b.fn.call(b.context,h,u),!0;case 4:return b.fn.call(b.context,h,u,p),!0;case 5:return b.fn.call(b.context,h,u,p,d),!0;case 6:return b.fn.call(b.context,h,u,p,d,g),!0}for(E=1,C=new Array(v-1);E<v;E++)C[E-1]=arguments[E];b.fn.apply(b.context,C)}else{var S=b.length,w;for(E=0;E<S;E++)switch(b[E].once&&this.removeListener(c,b[E].fn,void 0,!0),v){case 1:b[E].fn.call(b[E].context);break;case 2:b[E].fn.call(b[E].context,h);break;case 3:b[E].fn.call(b[E].context,h,u);break;case 4:b[E].fn.call(b[E].context,h,u,p);break;default:if(!C)for(w=1,C=new Array(v-1);w<v;w++)C[w-1]=arguments[w];b[E].fn.apply(b[E].context,C)}}return!0},a.prototype.on=function(c,h,u){return n(this,c,h,u,!1)},a.prototype.once=function(c,h,u){return n(this,c,h,u,!0)},a.prototype.removeListener=function(c,h,u,p){var d=t?t+c:c;if(!this._events[d])return this;if(!h)return o(this,d),this;var g=this._events[d];if(g.fn)g.fn===h&&(!p||g.once)&&(!u||g.context===u)&&o(this,d);else{for(var _=0,b=[],v=g.length;_<v;_++)(g[_].fn!==h||p&&!g[_].once||u&&g[_].context!==u)&&b.push(g[_]);b.length?this._events[d]=b.length===1?b[0]:b:o(this,d)}return this},a.prototype.removeAllListeners=function(c){var h;return c?(h=t?t+c:c,this._events[h]&&o(this,h)):(this._events=new s,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,i.exports=a})(Dr)),Dr.exports}var Nf=Df();const lt=oa(Nf),Uf=Math.PI*2,Gf=180/Math.PI,Ff=Math.PI/180;class ye{constructor(e=0,t=0){this.x=0,this.y=0,this.x=e,this.y=t}clone(){return new ye(this.x,this.y)}copyFrom(e){return this.set(e.x,e.y),this}copyTo(e){return e.set(this.x,this.y),e}equals(e){return e.x===this.x&&e.y===this.y}set(e=0,t=e){return this.x=e,this.y=t,this}toString(){return`[pixi.js/math:Point x=${this.x} y=${this.y}]`}static get shared(){return Nr.x=0,Nr.y=0,Nr}}const Nr=new ye;class H{constructor(e=1,t=0,s=0,r=1,n=0,o=0){this.array=null,this.a=e,this.b=t,this.c=s,this.d=r,this.tx=n,this.ty=o}fromArray(e){this.a=e[0],this.b=e[1],this.c=e[3],this.d=e[4],this.tx=e[2],this.ty=e[5]}set(e,t,s,r,n,o){return this.a=e,this.b=t,this.c=s,this.d=r,this.tx=n,this.ty=o,this}toArray(e,t){this.array||(this.array=new Float32Array(9));const s=t||this.array;return e?(s[0]=this.a,s[1]=this.b,s[2]=0,s[3]=this.c,s[4]=this.d,s[5]=0,s[6]=this.tx,s[7]=this.ty,s[8]=1):(s[0]=this.a,s[1]=this.c,s[2]=this.tx,s[3]=this.b,s[4]=this.d,s[5]=this.ty,s[6]=0,s[7]=0,s[8]=1),s}apply(e,t){t=t||new ye;const s=e.x,r=e.y;return t.x=this.a*s+this.c*r+this.tx,t.y=this.b*s+this.d*r+this.ty,t}applyInverse(e,t){t=t||new ye;const s=this.a,r=this.b,n=this.c,o=this.d,a=this.tx,l=this.ty,c=1/(s*o+n*-r),h=e.x,u=e.y;return t.x=o*c*h+-n*c*u+(l*n-a*o)*c,t.y=s*c*u+-r*c*h+(-l*s+a*r)*c,t}translate(e,t){return this.tx+=e,this.ty+=t,this}scale(e,t){return this.a*=e,this.d*=t,this.c*=e,this.b*=t,this.tx*=e,this.ty*=t,this}rotate(e){const t=Math.cos(e),s=Math.sin(e),r=this.a,n=this.c,o=this.tx;return this.a=r*t-this.b*s,this.b=r*s+this.b*t,this.c=n*t-this.d*s,this.d=n*s+this.d*t,this.tx=o*t-this.ty*s,this.ty=o*s+this.ty*t,this}append(e){const t=this.a,s=this.b,r=this.c,n=this.d;return this.a=e.a*t+e.b*r,this.b=e.a*s+e.b*n,this.c=e.c*t+e.d*r,this.d=e.c*s+e.d*n,this.tx=e.tx*t+e.ty*r+this.tx,this.ty=e.tx*s+e.ty*n+this.ty,this}appendFrom(e,t){const s=e.a,r=e.b,n=e.c,o=e.d,a=e.tx,l=e.ty,c=t.a,h=t.b,u=t.c,p=t.d;return this.a=s*c+r*u,this.b=s*h+r*p,this.c=n*c+o*u,this.d=n*h+o*p,this.tx=a*c+l*u+t.tx,this.ty=a*h+l*p+t.ty,this}setTransform(e,t,s,r,n,o,a,l,c){return this.a=Math.cos(a+c)*n,this.b=Math.sin(a+c)*n,this.c=-Math.sin(a-l)*o,this.d=Math.cos(a-l)*o,this.tx=e-(s*this.a+r*this.c),this.ty=t-(s*this.b+r*this.d),this}prepend(e){const t=this.tx;if(e.a!==1||e.b!==0||e.c!==0||e.d!==1){const s=this.a,r=this.c;this.a=s*e.a+this.b*e.c,this.b=s*e.b+this.b*e.d,this.c=r*e.a+this.d*e.c,this.d=r*e.b+this.d*e.d}return this.tx=t*e.a+this.ty*e.c+e.tx,this.ty=t*e.b+this.ty*e.d+e.ty,this}decompose(e){const t=this.a,s=this.b,r=this.c,n=this.d,o=e.pivot,a=-Math.atan2(-r,n),l=Math.atan2(s,t),c=Math.abs(a+l);return c<1e-5||Math.abs(Uf-c)<1e-5?(e.rotation=l,e.skew.x=e.skew.y=0):(e.rotation=0,e.skew.x=a,e.skew.y=l),e.scale.x=Math.sqrt(t*t+s*s),e.scale.y=Math.sqrt(r*r+n*n),e.position.x=this.tx+(o.x*t+o.y*r),e.position.y=this.ty+(o.x*s+o.y*n),e}invert(){const e=this.a,t=this.b,s=this.c,r=this.d,n=this.tx,o=e*r-t*s;return this.a=r/o,this.b=-t/o,this.c=-s/o,this.d=e/o,this.tx=(s*this.ty-r*n)/o,this.ty=-(e*this.ty-t*n)/o,this}isIdentity(){return this.a===1&&this.b===0&&this.c===0&&this.d===1&&this.tx===0&&this.ty===0}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){const e=new H;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyTo(e){return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyFrom(e){return this.a=e.a,this.b=e.b,this.c=e.c,this.d=e.d,this.tx=e.tx,this.ty=e.ty,this}equals(e){return e.a===this.a&&e.b===this.b&&e.c===this.c&&e.d===this.d&&e.tx===this.tx&&e.ty===this.ty}toString(){return`[pixi.js:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`}static get IDENTITY(){return Wf.identity()}static get shared(){return Lf.identity()}}const Lf=new H,Wf=new H,Jt=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],Qt=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],es=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],ts=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],Ur=[],la=[],Ni=Math.sign;function Hf(){for(let i=0;i<16;i++){const e=[];Ur.push(e);for(let t=0;t<16;t++){const s=Ni(Jt[i]*Jt[t]+es[i]*Qt[t]),r=Ni(Qt[i]*Jt[t]+ts[i]*Qt[t]),n=Ni(Jt[i]*es[t]+es[i]*ts[t]),o=Ni(Qt[i]*es[t]+ts[i]*ts[t]);for(let a=0;a<16;a++)if(Jt[a]===s&&Qt[a]===r&&es[a]===n&&ts[a]===o){e.push(a);break}}}for(let i=0;i<16;i++){const e=new H;e.set(Jt[i],Qt[i],es[i],ts[i],0,0),la.push(e)}}Hf();const re={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MAIN_DIAGONAL:10,MIRROR_HORIZONTAL:12,REVERSE_DIAGONAL:14,uX:i=>Jt[i],uY:i=>Qt[i],vX:i=>es[i],vY:i=>ts[i],inv:i=>i&8?i&15:-i&7,add:(i,e)=>Ur[i][e],sub:(i,e)=>Ur[i][re.inv(e)],rotate180:i=>i^4,isVertical:i=>(i&3)===2,byDirection:(i,e)=>Math.abs(i)*2<=Math.abs(e)?e>=0?re.S:re.N:Math.abs(e)*2<=Math.abs(i)?i>0?re.E:re.W:e>0?i>0?re.SE:re.SW:i>0?re.NE:re.NW,matrixAppendRotationInv:(i,e,t=0,s=0,r=0,n=0)=>{const o=la[re.inv(e)],a=o.a,l=o.b,c=o.c,h=o.d,u=t-Math.min(0,a*r,c*n,a*r+c*n),p=s-Math.min(0,l*r,h*n,l*r+h*n),d=i.a,g=i.b,_=i.c,b=i.d;i.a=a*d+l*_,i.b=a*g+l*b,i.c=c*d+h*_,i.d=c*g+h*b,i.tx=u*d+p*_+i.tx,i.ty=u*g+p*b+i.ty},transformRectCoords:(i,e,t,s)=>{const{x:r,y:n,width:o,height:a}=i,{x:l,y:c,width:h,height:u}=e;return t===re.E?(s.set(r+l,n+c,o,a),s):t===re.S?s.set(h-n-a+l,r+c,a,o):t===re.W?s.set(h-r-o+l,u-n-a+c,o,a):t===re.N?s.set(n+l,u-r-o+c,a,o):s.set(r+l,n+c,o,a)}},Ui=[new ye,new ye,new ye,new ye];class Ce{constructor(e=0,t=0,s=0,r=0){this.type="rectangle",this.x=Number(e),this.y=Number(t),this.width=Number(s),this.height=Number(r)}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}isEmpty(){return this.left===this.right||this.top===this.bottom}static get EMPTY(){return new Ce(0,0,0,0)}clone(){return new Ce(this.x,this.y,this.width,this.height)}copyFromBounds(e){return this.x=e.minX,this.y=e.minY,this.width=e.maxX-e.minX,this.height=e.maxY-e.minY,this}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){return this.width<=0||this.height<=0?!1:e>=this.x&&e<this.x+this.width&&t>=this.y&&t<this.y+this.height}strokeContains(e,t,s,r=.5){const{width:n,height:o}=this;if(n<=0||o<=0)return!1;const a=this.x,l=this.y,c=s*(1-r),h=s-c,u=a-c,p=a+n+c,d=l-c,g=l+o+c,_=a+h,b=a+n-h,v=l+h,C=l+o-h;return e>=u&&e<=p&&t>=d&&t<=g&&!(e>_&&e<b&&t>v&&t<C)}intersects(e,t){if(!t){const D=this.x<e.x?e.x:this.x;if((this.right>e.right?e.right:this.right)<=D)return!1;const k=this.y<e.y?e.y:this.y;return(this.bottom>e.bottom?e.bottom:this.bottom)>k}const s=this.left,r=this.right,n=this.top,o=this.bottom;if(r<=s||o<=n)return!1;const a=Ui[0].set(e.left,e.top),l=Ui[1].set(e.left,e.bottom),c=Ui[2].set(e.right,e.top),h=Ui[3].set(e.right,e.bottom);if(c.x<=a.x||l.y<=a.y)return!1;const u=Math.sign(t.a*t.d-t.b*t.c);if(u===0||(t.apply(a,a),t.apply(l,l),t.apply(c,c),t.apply(h,h),Math.max(a.x,l.x,c.x,h.x)<=s||Math.min(a.x,l.x,c.x,h.x)>=r||Math.max(a.y,l.y,c.y,h.y)<=n||Math.min(a.y,l.y,c.y,h.y)>=o))return!1;const p=u*(l.y-a.y),d=u*(a.x-l.x),g=p*s+d*n,_=p*r+d*n,b=p*s+d*o,v=p*r+d*o;if(Math.max(g,_,b,v)<=p*a.x+d*a.y||Math.min(g,_,b,v)>=p*h.x+d*h.y)return!1;const C=u*(a.y-c.y),E=u*(c.x-a.x),S=C*s+E*n,w=C*r+E*n,R=C*s+E*o,M=C*r+E*o;return!(Math.max(S,w,R,M)<=C*a.x+E*a.y||Math.min(S,w,R,M)>=C*h.x+E*h.y)}pad(e=0,t=e){return this.x-=e,this.y-=t,this.width+=e*2,this.height+=t*2,this}fit(e){const t=Math.max(this.x,e.x),s=Math.min(this.x+this.width,e.x+e.width),r=Math.max(this.y,e.y),n=Math.min(this.y+this.height,e.y+e.height);return this.x=t,this.width=Math.max(s-t,0),this.y=r,this.height=Math.max(n-r,0),this}ceil(e=1,t=.001){const s=Math.ceil((this.x+this.width-t)*e)/e,r=Math.ceil((this.y+this.height-t)*e)/e;return this.x=Math.floor((this.x+t)*e)/e,this.y=Math.floor((this.y+t)*e)/e,this.width=s-this.x,this.height=r-this.y,this}scale(e,t=e){return this.x*=e,this.y*=t,this.width*=e,this.height*=t,this}enlarge(e){const t=Math.min(this.x,e.x),s=Math.max(this.x+this.width,e.x+e.width),r=Math.min(this.y,e.y),n=Math.max(this.y+this.height,e.y+e.height);return this.x=t,this.width=s-t,this.y=r,this.height=n-r,this}getBounds(e){return e||(e=new Ce),e.copyFrom(this),e}containsRect(e){if(this.width<=0||this.height<=0)return!1;const t=e.x,s=e.y,r=e.x+e.width,n=e.y+e.height;return t>=this.x&&t<this.x+this.width&&s>=this.y&&s<this.y+this.height&&r>=this.x&&r<this.x+this.width&&n>=this.y&&n<this.y+this.height}set(e,t,s,r){return this.x=e,this.y=t,this.width=s,this.height=r,this}toString(){return`[pixi.js/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`}}const Gr={default:-1};function be(i="default"){return Gr[i]===void 0&&(Gr[i]=-1),++Gr[i]}const ca=new Set,Be="8.0.0",Vf="8.3.4",fs={quiet:!1,noColor:!1},ee=((i,e,t=3)=>{if(fs.quiet||ca.has(e))return;let s=new Error().stack;const r=`${e}
|
|
1
|
+
(function(ds,$e){typeof exports=="object"&&typeof module<"u"?$e(exports):typeof define=="function"&&define.amd?define(["exports"],$e):(ds=typeof globalThis<"u"?globalThis:ds||self,$e(ds.HolostaffWidget={}))})(this,(function(ds){"use strict";const $e={mode:"floating",container:null,position:"bottom-center",trigger:"scroll",scrollThreshold:.3,delayMs:3e3,theme:"light",accentColor:null,language:"en",backendUrl:"https://us-central1-holostaff-ai.cloudfunctions.net",visionWsUrl:null,visionConsent:"auto"};function Tf(i){const e=i.dataset.staffId;if(!e)throw new Error("[HolostaffWidget] data-staff-id attribute is required");return{staffId:e,mode:i.dataset.mode??$e.mode,container:i.dataset.container??$e.container,position:i.dataset.position??$e.position,trigger:i.dataset.trigger??$e.trigger,scrollThreshold:parseFloat(i.dataset.scrollThreshold??"")||$e.scrollThreshold,delayMs:parseInt(i.dataset.delayMs??"",10)||$e.delayMs,theme:i.dataset.theme??$e.theme,accentColor:i.dataset.accentColor??$e.accentColor,language:i.dataset.language??$e.language,backendUrl:i.dataset.backendUrl??$e.backendUrl,visionWsUrl:i.dataset.visionWsUrl??$e.visionWsUrl,visionConsent:i.dataset.hsConsent??$e.visionConsent}}const Af=["bottom-center","bottom-left","bottom-right"],wf=["scroll","delay","immediate"],If=["light","dark","auto"];function Rf(i,e,t){const s={...i};return!e.dataset.trigger&&t.trigger&&wf.includes(t.trigger)&&(s.trigger=t.trigger),!e.dataset.position&&t.position&&Af.includes(t.position)&&(s.position=t.position),!e.dataset.theme&&t.theme&&If.includes(t.theme)&&(s.theme=t.theme),!e.dataset.scrollThreshold&&t.scrollThreshold!=null&&(s.scrollThreshold=t.scrollThreshold),!e.dataset.delayMs&&t.delayMs!=null&&(s.delayMs=t.delayMs),!e.dataset.visionWsUrl&&t.visionWsUrl&&(s.visionWsUrl=t.visionWsUrl),s}const Or="https://us-central1-holostaff-ai.cloudfunctions.net";async function Mf(i,e=Or){const t=await fetch(`${e}/widgetSession`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({staffId:i})});if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw new Error(s.error||`Session request failed: ${t.status}`)}return t.json()}class Pf extends Error{constructor(e){super(e),this.name="WidgetDisabledError"}}async function kf(i,e=Or){const t=await fetch(`${e}/widgetConfig?staffId=${encodeURIComponent(i)}`);if(!t.ok){const s=await t.json().catch(()=>({error:t.statusText}));throw s.disabled===!0||t.status===404?new Pf(s.error||"Agent not available"):new Error(s.error||`Config request failed: ${t.status}`)}return t.json()}async function Of(i,e,t,s=Or){const r=await fetch(`${s}/widgetPageAction`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({staffId:i,domSnapshot:e,instruction:t})});if(!r.ok){const n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error||`Page action request failed: ${r.status}`)}return r.json()}var A=(i=>(i.Application="application",i.WebGLPipes="webgl-pipes",i.WebGLPipesAdaptor="webgl-pipes-adaptor",i.WebGLSystem="webgl-system",i.WebGPUPipes="webgpu-pipes",i.WebGPUPipesAdaptor="webgpu-pipes-adaptor",i.WebGPUSystem="webgpu-system",i.CanvasSystem="canvas-system",i.CanvasPipesAdaptor="canvas-pipes-adaptor",i.CanvasPipes="canvas-pipes",i.Asset="asset",i.LoadParser="load-parser",i.ResolveParser="resolve-parser",i.CacheParser="cache-parser",i.DetectionParser="detection-parser",i.MaskEffect="mask-effect",i.BlendMode="blend-mode",i.TextureSource="texture-source",i.Environment="environment",i.ShapeBuilder="shape-builder",i.Batcher="batcher",i))(A||{});const Br=i=>{if(typeof i=="function"||typeof i=="object"&&i.extension){if(!i.extension)throw new Error("Extension class must have an extension object");i={...typeof i.extension!="object"?{type:i.extension}:i.extension,ref:i}}if(typeof i=="object")i={...i};else throw new Error("Invalid extension type");return typeof i.type=="string"&&(i.type=[i.type]),i},Di=(i,e)=>Br(i).priority??e,Q={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...i){return i.map(Br).forEach(e=>{e.type.forEach(t=>{var s,r;return(r=(s=this._removeHandlers)[t])==null?void 0:r.call(s,e)})}),this},add(...i){return i.map(Br).forEach(e=>{e.type.forEach(t=>{var n,o;const s=this._addHandlers,r=this._queue;s[t]?(o=s[t])==null||o.call(s,e):(r[t]=r[t]||[],(n=r[t])==null||n.push(e))})}),this},handle(i,e,t){var o;const s=this._addHandlers,r=this._removeHandlers;if(s[i]||r[i])throw new Error(`Extension type ${i} already has a handler`);s[i]=e,r[i]=t;const n=this._queue;return n[i]&&((o=n[i])==null||o.forEach(a=>e(a)),delete n[i]),this},handleByMap(i,e){return this.handle(i,t=>{t.name&&(e[t.name]=t.ref)},t=>{t.name&&delete e[t.name]})},handleByNamedList(i,e,t=-1){return this.handle(i,s=>{e.findIndex(n=>n.name===s.name)>=0||(e.push({name:s.name,value:s.ref}),e.sort((n,o)=>Di(o.value,t)-Di(n.value,t)))},s=>{const r=e.findIndex(n=>n.name===s.name);r!==-1&&e.splice(r,1)})},handleByList(i,e,t=-1){return this.handle(i,s=>{e.includes(s.ref)||(e.push(s.ref),e.sort((r,n)=>Di(n,t)-Di(r,t)))},s=>{const r=e.indexOf(s.ref);r!==-1&&e.splice(r,1)})},mixin(i,...e){for(const t of e)Object.defineProperties(i.prototype,Object.getOwnPropertyDescriptors(t))}},Bf={extension:{type:A.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await Promise.resolve().then(()=>GC)}},Df={extension:{type:A.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await Promise.resolve().then(()=>FC)}};class je{constructor(e,t,s){this._x=t||0,this._y=s||0,this._observer=e}clone(e){return new je(e??this._observer,this._x,this._y)}set(e=0,t=e){return(this._x!==e||this._y!==t)&&(this._x=e,this._y=t,this._observer._onUpdate(this)),this}copyFrom(e){return(this._x!==e.x||this._y!==e.y)&&(this._x=e.x,this._y=e.y,this._observer._onUpdate(this)),this}copyTo(e){return e.set(this._x,this._y),e}equals(e){return e.x===this._x&&e.y===this._y}toString(){return`[pixi.js/math:ObservablePoint x=${this._x} y=${this._y} scope=${this._observer}]`}get x(){return this._x}set x(e){this._x!==e&&(this._x=e,this._observer._onUpdate(this))}get y(){return this._y}set y(e){this._y!==e&&(this._y=e,this._observer._onUpdate(this))}}function oa(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Dr={exports:{}},aa;function Nf(){return aa||(aa=1,(function(i){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function r(l,c,h){this.fn=l,this.context=c,this.once=h||!1}function n(l,c,h,u,p){if(typeof h!="function")throw new TypeError("The listener must be a function");var d=new r(h,u||l,p),g=t?t+c:c;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],d]:l._events[g].push(d):(l._events[g]=d,l._eventsCount++),l}function o(l,c){--l._eventsCount===0?l._events=new s:delete l._events[c]}function a(){this._events=new s,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],h,u;if(this._eventsCount===0)return c;for(u in h=this._events)e.call(h,u)&&c.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(h)):c},a.prototype.listeners=function(c){var h=t?t+c:c,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var p=0,d=u.length,g=new Array(d);p<d;p++)g[p]=u[p].fn;return g},a.prototype.listenerCount=function(c){var h=t?t+c:c,u=this._events[h];return u?u.fn?1:u.length:0},a.prototype.emit=function(c,h,u,p,d,g){var _=t?t+c:c;if(!this._events[_])return!1;var b=this._events[_],v=arguments.length,C,E;if(b.fn){switch(b.once&&this.removeListener(c,b.fn,void 0,!0),v){case 1:return b.fn.call(b.context),!0;case 2:return b.fn.call(b.context,h),!0;case 3:return b.fn.call(b.context,h,u),!0;case 4:return b.fn.call(b.context,h,u,p),!0;case 5:return b.fn.call(b.context,h,u,p,d),!0;case 6:return b.fn.call(b.context,h,u,p,d,g),!0}for(E=1,C=new Array(v-1);E<v;E++)C[E-1]=arguments[E];b.fn.apply(b.context,C)}else{var S=b.length,w;for(E=0;E<S;E++)switch(b[E].once&&this.removeListener(c,b[E].fn,void 0,!0),v){case 1:b[E].fn.call(b[E].context);break;case 2:b[E].fn.call(b[E].context,h);break;case 3:b[E].fn.call(b[E].context,h,u);break;case 4:b[E].fn.call(b[E].context,h,u,p);break;default:if(!C)for(w=1,C=new Array(v-1);w<v;w++)C[w-1]=arguments[w];b[E].fn.apply(b[E].context,C)}}return!0},a.prototype.on=function(c,h,u){return n(this,c,h,u,!1)},a.prototype.once=function(c,h,u){return n(this,c,h,u,!0)},a.prototype.removeListener=function(c,h,u,p){var d=t?t+c:c;if(!this._events[d])return this;if(!h)return o(this,d),this;var g=this._events[d];if(g.fn)g.fn===h&&(!p||g.once)&&(!u||g.context===u)&&o(this,d);else{for(var _=0,b=[],v=g.length;_<v;_++)(g[_].fn!==h||p&&!g[_].once||u&&g[_].context!==u)&&b.push(g[_]);b.length?this._events[d]=b.length===1?b[0]:b:o(this,d)}return this},a.prototype.removeAllListeners=function(c){var h;return c?(h=t?t+c:c,this._events[h]&&o(this,h)):(this._events=new s,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,i.exports=a})(Dr)),Dr.exports}var Uf=Nf();const lt=oa(Uf),Gf=Math.PI*2,Ff=180/Math.PI,Lf=Math.PI/180;class ye{constructor(e=0,t=0){this.x=0,this.y=0,this.x=e,this.y=t}clone(){return new ye(this.x,this.y)}copyFrom(e){return this.set(e.x,e.y),this}copyTo(e){return e.set(this.x,this.y),e}equals(e){return e.x===this.x&&e.y===this.y}set(e=0,t=e){return this.x=e,this.y=t,this}toString(){return`[pixi.js/math:Point x=${this.x} y=${this.y}]`}static get shared(){return Nr.x=0,Nr.y=0,Nr}}const Nr=new ye;class H{constructor(e=1,t=0,s=0,r=1,n=0,o=0){this.array=null,this.a=e,this.b=t,this.c=s,this.d=r,this.tx=n,this.ty=o}fromArray(e){this.a=e[0],this.b=e[1],this.c=e[3],this.d=e[4],this.tx=e[2],this.ty=e[5]}set(e,t,s,r,n,o){return this.a=e,this.b=t,this.c=s,this.d=r,this.tx=n,this.ty=o,this}toArray(e,t){this.array||(this.array=new Float32Array(9));const s=t||this.array;return e?(s[0]=this.a,s[1]=this.b,s[2]=0,s[3]=this.c,s[4]=this.d,s[5]=0,s[6]=this.tx,s[7]=this.ty,s[8]=1):(s[0]=this.a,s[1]=this.c,s[2]=this.tx,s[3]=this.b,s[4]=this.d,s[5]=this.ty,s[6]=0,s[7]=0,s[8]=1),s}apply(e,t){t=t||new ye;const s=e.x,r=e.y;return t.x=this.a*s+this.c*r+this.tx,t.y=this.b*s+this.d*r+this.ty,t}applyInverse(e,t){t=t||new ye;const s=this.a,r=this.b,n=this.c,o=this.d,a=this.tx,l=this.ty,c=1/(s*o+n*-r),h=e.x,u=e.y;return t.x=o*c*h+-n*c*u+(l*n-a*o)*c,t.y=s*c*u+-r*c*h+(-l*s+a*r)*c,t}translate(e,t){return this.tx+=e,this.ty+=t,this}scale(e,t){return this.a*=e,this.d*=t,this.c*=e,this.b*=t,this.tx*=e,this.ty*=t,this}rotate(e){const t=Math.cos(e),s=Math.sin(e),r=this.a,n=this.c,o=this.tx;return this.a=r*t-this.b*s,this.b=r*s+this.b*t,this.c=n*t-this.d*s,this.d=n*s+this.d*t,this.tx=o*t-this.ty*s,this.ty=o*s+this.ty*t,this}append(e){const t=this.a,s=this.b,r=this.c,n=this.d;return this.a=e.a*t+e.b*r,this.b=e.a*s+e.b*n,this.c=e.c*t+e.d*r,this.d=e.c*s+e.d*n,this.tx=e.tx*t+e.ty*r+this.tx,this.ty=e.tx*s+e.ty*n+this.ty,this}appendFrom(e,t){const s=e.a,r=e.b,n=e.c,o=e.d,a=e.tx,l=e.ty,c=t.a,h=t.b,u=t.c,p=t.d;return this.a=s*c+r*u,this.b=s*h+r*p,this.c=n*c+o*u,this.d=n*h+o*p,this.tx=a*c+l*u+t.tx,this.ty=a*h+l*p+t.ty,this}setTransform(e,t,s,r,n,o,a,l,c){return this.a=Math.cos(a+c)*n,this.b=Math.sin(a+c)*n,this.c=-Math.sin(a-l)*o,this.d=Math.cos(a-l)*o,this.tx=e-(s*this.a+r*this.c),this.ty=t-(s*this.b+r*this.d),this}prepend(e){const t=this.tx;if(e.a!==1||e.b!==0||e.c!==0||e.d!==1){const s=this.a,r=this.c;this.a=s*e.a+this.b*e.c,this.b=s*e.b+this.b*e.d,this.c=r*e.a+this.d*e.c,this.d=r*e.b+this.d*e.d}return this.tx=t*e.a+this.ty*e.c+e.tx,this.ty=t*e.b+this.ty*e.d+e.ty,this}decompose(e){const t=this.a,s=this.b,r=this.c,n=this.d,o=e.pivot,a=-Math.atan2(-r,n),l=Math.atan2(s,t),c=Math.abs(a+l);return c<1e-5||Math.abs(Gf-c)<1e-5?(e.rotation=l,e.skew.x=e.skew.y=0):(e.rotation=0,e.skew.x=a,e.skew.y=l),e.scale.x=Math.sqrt(t*t+s*s),e.scale.y=Math.sqrt(r*r+n*n),e.position.x=this.tx+(o.x*t+o.y*r),e.position.y=this.ty+(o.x*s+o.y*n),e}invert(){const e=this.a,t=this.b,s=this.c,r=this.d,n=this.tx,o=e*r-t*s;return this.a=r/o,this.b=-t/o,this.c=-s/o,this.d=e/o,this.tx=(s*this.ty-r*n)/o,this.ty=-(e*this.ty-t*n)/o,this}isIdentity(){return this.a===1&&this.b===0&&this.c===0&&this.d===1&&this.tx===0&&this.ty===0}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){const e=new H;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyTo(e){return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyFrom(e){return this.a=e.a,this.b=e.b,this.c=e.c,this.d=e.d,this.tx=e.tx,this.ty=e.ty,this}equals(e){return e.a===this.a&&e.b===this.b&&e.c===this.c&&e.d===this.d&&e.tx===this.tx&&e.ty===this.ty}toString(){return`[pixi.js:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`}static get IDENTITY(){return Hf.identity()}static get shared(){return Wf.identity()}}const Wf=new H,Hf=new H,Jt=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],Qt=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],es=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],ts=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],Ur=[],la=[],Ni=Math.sign;function Vf(){for(let i=0;i<16;i++){const e=[];Ur.push(e);for(let t=0;t<16;t++){const s=Ni(Jt[i]*Jt[t]+es[i]*Qt[t]),r=Ni(Qt[i]*Jt[t]+ts[i]*Qt[t]),n=Ni(Jt[i]*es[t]+es[i]*ts[t]),o=Ni(Qt[i]*es[t]+ts[i]*ts[t]);for(let a=0;a<16;a++)if(Jt[a]===s&&Qt[a]===r&&es[a]===n&&ts[a]===o){e.push(a);break}}}for(let i=0;i<16;i++){const e=new H;e.set(Jt[i],Qt[i],es[i],ts[i],0,0),la.push(e)}}Vf();const re={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MAIN_DIAGONAL:10,MIRROR_HORIZONTAL:12,REVERSE_DIAGONAL:14,uX:i=>Jt[i],uY:i=>Qt[i],vX:i=>es[i],vY:i=>ts[i],inv:i=>i&8?i&15:-i&7,add:(i,e)=>Ur[i][e],sub:(i,e)=>Ur[i][re.inv(e)],rotate180:i=>i^4,isVertical:i=>(i&3)===2,byDirection:(i,e)=>Math.abs(i)*2<=Math.abs(e)?e>=0?re.S:re.N:Math.abs(e)*2<=Math.abs(i)?i>0?re.E:re.W:e>0?i>0?re.SE:re.SW:i>0?re.NE:re.NW,matrixAppendRotationInv:(i,e,t=0,s=0,r=0,n=0)=>{const o=la[re.inv(e)],a=o.a,l=o.b,c=o.c,h=o.d,u=t-Math.min(0,a*r,c*n,a*r+c*n),p=s-Math.min(0,l*r,h*n,l*r+h*n),d=i.a,g=i.b,_=i.c,b=i.d;i.a=a*d+l*_,i.b=a*g+l*b,i.c=c*d+h*_,i.d=c*g+h*b,i.tx=u*d+p*_+i.tx,i.ty=u*g+p*b+i.ty},transformRectCoords:(i,e,t,s)=>{const{x:r,y:n,width:o,height:a}=i,{x:l,y:c,width:h,height:u}=e;return t===re.E?(s.set(r+l,n+c,o,a),s):t===re.S?s.set(h-n-a+l,r+c,a,o):t===re.W?s.set(h-r-o+l,u-n-a+c,o,a):t===re.N?s.set(n+l,u-r-o+c,a,o):s.set(r+l,n+c,o,a)}},Ui=[new ye,new ye,new ye,new ye];class Ce{constructor(e=0,t=0,s=0,r=0){this.type="rectangle",this.x=Number(e),this.y=Number(t),this.width=Number(s),this.height=Number(r)}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}isEmpty(){return this.left===this.right||this.top===this.bottom}static get EMPTY(){return new Ce(0,0,0,0)}clone(){return new Ce(this.x,this.y,this.width,this.height)}copyFromBounds(e){return this.x=e.minX,this.y=e.minY,this.width=e.maxX-e.minX,this.height=e.maxY-e.minY,this}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){return this.width<=0||this.height<=0?!1:e>=this.x&&e<this.x+this.width&&t>=this.y&&t<this.y+this.height}strokeContains(e,t,s,r=.5){const{width:n,height:o}=this;if(n<=0||o<=0)return!1;const a=this.x,l=this.y,c=s*(1-r),h=s-c,u=a-c,p=a+n+c,d=l-c,g=l+o+c,_=a+h,b=a+n-h,v=l+h,C=l+o-h;return e>=u&&e<=p&&t>=d&&t<=g&&!(e>_&&e<b&&t>v&&t<C)}intersects(e,t){if(!t){const D=this.x<e.x?e.x:this.x;if((this.right>e.right?e.right:this.right)<=D)return!1;const k=this.y<e.y?e.y:this.y;return(this.bottom>e.bottom?e.bottom:this.bottom)>k}const s=this.left,r=this.right,n=this.top,o=this.bottom;if(r<=s||o<=n)return!1;const a=Ui[0].set(e.left,e.top),l=Ui[1].set(e.left,e.bottom),c=Ui[2].set(e.right,e.top),h=Ui[3].set(e.right,e.bottom);if(c.x<=a.x||l.y<=a.y)return!1;const u=Math.sign(t.a*t.d-t.b*t.c);if(u===0||(t.apply(a,a),t.apply(l,l),t.apply(c,c),t.apply(h,h),Math.max(a.x,l.x,c.x,h.x)<=s||Math.min(a.x,l.x,c.x,h.x)>=r||Math.max(a.y,l.y,c.y,h.y)<=n||Math.min(a.y,l.y,c.y,h.y)>=o))return!1;const p=u*(l.y-a.y),d=u*(a.x-l.x),g=p*s+d*n,_=p*r+d*n,b=p*s+d*o,v=p*r+d*o;if(Math.max(g,_,b,v)<=p*a.x+d*a.y||Math.min(g,_,b,v)>=p*h.x+d*h.y)return!1;const C=u*(a.y-c.y),E=u*(c.x-a.x),S=C*s+E*n,w=C*r+E*n,R=C*s+E*o,M=C*r+E*o;return!(Math.max(S,w,R,M)<=C*a.x+E*a.y||Math.min(S,w,R,M)>=C*h.x+E*h.y)}pad(e=0,t=e){return this.x-=e,this.y-=t,this.width+=e*2,this.height+=t*2,this}fit(e){const t=Math.max(this.x,e.x),s=Math.min(this.x+this.width,e.x+e.width),r=Math.max(this.y,e.y),n=Math.min(this.y+this.height,e.y+e.height);return this.x=t,this.width=Math.max(s-t,0),this.y=r,this.height=Math.max(n-r,0),this}ceil(e=1,t=.001){const s=Math.ceil((this.x+this.width-t)*e)/e,r=Math.ceil((this.y+this.height-t)*e)/e;return this.x=Math.floor((this.x+t)*e)/e,this.y=Math.floor((this.y+t)*e)/e,this.width=s-this.x,this.height=r-this.y,this}scale(e,t=e){return this.x*=e,this.y*=t,this.width*=e,this.height*=t,this}enlarge(e){const t=Math.min(this.x,e.x),s=Math.max(this.x+this.width,e.x+e.width),r=Math.min(this.y,e.y),n=Math.max(this.y+this.height,e.y+e.height);return this.x=t,this.width=s-t,this.y=r,this.height=n-r,this}getBounds(e){return e||(e=new Ce),e.copyFrom(this),e}containsRect(e){if(this.width<=0||this.height<=0)return!1;const t=e.x,s=e.y,r=e.x+e.width,n=e.y+e.height;return t>=this.x&&t<this.x+this.width&&s>=this.y&&s<this.y+this.height&&r>=this.x&&r<this.x+this.width&&n>=this.y&&n<this.y+this.height}set(e,t,s,r){return this.x=e,this.y=t,this.width=s,this.height=r,this}toString(){return`[pixi.js/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`}}const Gr={default:-1};function be(i="default"){return Gr[i]===void 0&&(Gr[i]=-1),++Gr[i]}const ca=new Set,Be="8.0.0",zf="8.3.4",fs={quiet:!1,noColor:!1},ee=((i,e,t=3)=>{if(fs.quiet||ca.has(e))return;let s=new Error().stack;const r=`${e}
|
|
2
2
|
Deprecated since v${i}`,n=typeof console.groupCollapsed=="function"&&!fs.noColor;typeof s>"u"?console.warn("PixiJS Deprecation Warning: ",r):(s=s.split(`
|
|
3
3
|
`).splice(t).join(`
|
|
4
|
-
`),n?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",r),console.warn(s),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",r),console.warn(s))),ca.add(e)});Object.defineProperties(ee,{quiet:{get:()=>fs.quiet,set:i=>{fs.quiet=i},enumerable:!0,configurable:!1},noColor:{get:()=>fs.noColor,set:i=>{fs.noColor=i},enumerable:!0,configurable:!1}});const ha=()=>{};function Gi(i){return i+=i===0?1:0,--i,i|=i>>>1,i|=i>>>2,i|=i>>>4,i|=i>>>8,i|=i>>>16,i+1}function ua(i){return!(i&i-1)&&!!i}function da(i){const e={};for(const t in i)i[t]!==void 0&&(e[t]=i[t]);return e}const fa=Object.create(null);function zf(i){const e=fa[i];return e===void 0&&(fa[i]=be("resource")),e}const pa=class af extends lt{constructor(e={}){super(),this._resourceType="textureSampler",this._touched=0,this._maxAnisotropy=1,this.destroyed=!1,e={...af.defaultOptions,...e},this.addressMode=e.addressMode,this.addressModeU=e.addressModeU??this.addressModeU,this.addressModeV=e.addressModeV??this.addressModeV,this.addressModeW=e.addressModeW??this.addressModeW,this.scaleMode=e.scaleMode,this.magFilter=e.magFilter??this.magFilter,this.minFilter=e.minFilter??this.minFilter,this.mipmapFilter=e.mipmapFilter??this.mipmapFilter,this.lodMinClamp=e.lodMinClamp,this.lodMaxClamp=e.lodMaxClamp,this.compare=e.compare,this.maxAnisotropy=e.maxAnisotropy??1}set addressMode(e){this.addressModeU=e,this.addressModeV=e,this.addressModeW=e}get addressMode(){return this.addressModeU}set wrapMode(e){ee(Be,"TextureStyle.wrapMode is now TextureStyle.addressMode"),this.addressMode=e}get wrapMode(){return this.addressMode}set scaleMode(e){this.magFilter=e,this.minFilter=e,this.mipmapFilter=e}get scaleMode(){return this.magFilter}set maxAnisotropy(e){this._maxAnisotropy=Math.min(e,16),this._maxAnisotropy>1&&(this.scaleMode="linear")}get maxAnisotropy(){return this._maxAnisotropy}get _resourceId(){return this._sharedResourceId||this._generateResourceId()}update(){this._sharedResourceId=null,this.emit("change",this)}_generateResourceId(){const e=`${this.addressModeU}-${this.addressModeV}-${this.addressModeW}-${this.magFilter}-${this.minFilter}-${this.mipmapFilter}-${this.lodMinClamp}-${this.lodMaxClamp}-${this.compare}-${this._maxAnisotropy}`;return this._sharedResourceId=zf(e),this._resourceId}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this.removeAllListeners()}};pa.defaultOptions={addressMode:"clamp-to-edge",scaleMode:"linear"};let Fr=pa;const ma=class lf extends lt{constructor(e={}){super(),this.options=e,this._gpuData=Object.create(null),this._gcLastUsed=-1,this.uid=be("textureSource"),this._resourceType="textureSource",this._resourceId=be("resource"),this.uploadMethodId="unknown",this._resolution=1,this.pixelWidth=1,this.pixelHeight=1,this.width=1,this.height=1,this.sampleCount=1,this.mipLevelCount=1,this.autoGenerateMipmaps=!1,this.format="rgba8unorm",this.dimension="2d",this.viewDimension="2d",this.arrayLayerCount=1,this.antialias=!1,this._touched=0,this._batchTick=-1,this._textureBindLocation=-1,e={...lf.defaultOptions,...e},this.label=e.label??"",this.resource=e.resource,this.autoGarbageCollect=e.autoGarbageCollect,this._resolution=e.resolution,e.width?this.pixelWidth=e.width*this._resolution:this.pixelWidth=this.resource?this.resourceWidth??1:1,e.height?this.pixelHeight=e.height*this._resolution:this.pixelHeight=this.resource?this.resourceHeight??1:1,this.width=this.pixelWidth/this._resolution,this.height=this.pixelHeight/this._resolution,this.format=e.format,this.dimension=e.dimensions,this.viewDimension=e.viewDimension??e.dimensions,this.arrayLayerCount=e.arrayLayerCount,this.mipLevelCount=e.mipLevelCount,this.autoGenerateMipmaps=e.autoGenerateMipmaps,this.sampleCount=e.sampleCount,this.antialias=e.antialias,this.alphaMode=e.alphaMode,this.style=new Fr(da(e)),this.destroyed=!1,this._refreshPOT()}get source(){return this}get style(){return this._style}set style(e){var t,s;this.style!==e&&((t=this._style)==null||t.off("change",this._onStyleChange,this),this._style=e,(s=this._style)==null||s.on("change",this._onStyleChange,this),this._onStyleChange())}set maxAnisotropy(e){this._style.maxAnisotropy=e}get maxAnisotropy(){return this._style.maxAnisotropy}get addressMode(){return this._style.addressMode}set addressMode(e){this._style.addressMode=e}get repeatMode(){return this._style.addressMode}set repeatMode(e){this._style.addressMode=e}get magFilter(){return this._style.magFilter}set magFilter(e){this._style.magFilter=e}get minFilter(){return this._style.minFilter}set minFilter(e){this._style.minFilter=e}get mipmapFilter(){return this._style.mipmapFilter}set mipmapFilter(e){this._style.mipmapFilter=e}get lodMinClamp(){return this._style.lodMinClamp}set lodMinClamp(e){this._style.lodMinClamp=e}get lodMaxClamp(){return this._style.lodMaxClamp}set lodMaxClamp(e){this._style.lodMaxClamp=e}_onStyleChange(){this.emit("styleChange",this)}update(){if(this.resource){const e=this._resolution;if(this.resize(this.resourceWidth/e,this.resourceHeight/e))return}this.emit("update",this)}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this._style&&(this._style.destroy(),this._style=null),this.uploadMethodId=null,this.resource=null,this.removeAllListeners()}unload(){var e,t;this._resourceId=be("resource"),this.emit("change",this),this.emit("unload",this);for(const s in this._gpuData)(t=(e=this._gpuData[s])==null?void 0:e.destroy)==null||t.call(e);this._gpuData=Object.create(null)}get resourceWidth(){const{resource:e}=this;return e.naturalWidth||e.videoWidth||e.displayWidth||e.width}get resourceHeight(){const{resource:e}=this;return e.naturalHeight||e.videoHeight||e.displayHeight||e.height}get resolution(){return this._resolution}set resolution(e){this._resolution!==e&&(this._resolution=e,this.width=this.pixelWidth/e,this.height=this.pixelHeight/e)}resize(e,t,s){s||(s=this._resolution),e||(e=this.width),t||(t=this.height);const r=Math.round(e*s),n=Math.round(t*s);return this.width=r/s,this.height=n/s,this._resolution=s,this.pixelWidth===r&&this.pixelHeight===n?!1:(this._refreshPOT(),this.pixelWidth=r,this.pixelHeight=n,this.emit("resize",this),this._resourceId=be("resource"),this.emit("change",this),!0)}updateMipmaps(){this.autoGenerateMipmaps&&this.mipLevelCount>1&&this.emit("updateMipmaps",this)}set wrapMode(e){this._style.wrapMode=e}get wrapMode(){return this._style.wrapMode}set scaleMode(e){this._style.scaleMode=e}get scaleMode(){return this._style.scaleMode}_refreshPOT(){this.isPowerOfTwo=ua(this.pixelWidth)&&ua(this.pixelHeight)}static test(e){throw new Error("Unimplemented")}};ma.defaultOptions={resolution:1,format:"bgra8unorm",alphaMode:"premultiply-alpha-on-upload",dimensions:"2d",viewDimension:"2d",arrayLayerCount:1,mipLevelCount:1,autoGenerateMipmaps:!1,sampleCount:1,antialias:!1,autoGarbageCollect:!1};let De=ma;class Lr extends De{constructor(e){const t=e.resource||new Float32Array(e.width*e.height*4);let s=e.format;s||(t instanceof Float32Array?s="rgba32float":t instanceof Int32Array||t instanceof Uint32Array?s="rgba32uint":t instanceof Int16Array||t instanceof Uint16Array?s="rgba16uint":(t instanceof Int8Array,s="bgra8unorm")),super({...e,resource:t,format:s}),this.uploadMethodId="buffer"}static test(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array}}Lr.extension=A.TextureSource;const ga=new H;class _a{constructor(e,t){this.mapCoord=new H,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._textureID=-1,this._updateID=0,this.clampOffset=0,typeof t>"u"?this.clampMargin=e.width<10?0:.5:this.clampMargin=t,this.isSimple=!1,this.texture=e}get texture(){return this._texture}set texture(e){var t;this.texture!==e&&((t=this._texture)==null||t.removeListener("update",this.update,this),this._texture=e,this._texture.addListener("update",this.update,this),this.update())}multiplyUvs(e,t){t===void 0&&(t=e);const s=this.mapCoord;for(let r=0;r<e.length;r+=2){const n=e[r],o=e[r+1];t[r]=n*s.a+o*s.c+s.tx,t[r+1]=n*s.b+o*s.d+s.ty}return t}update(){const e=this._texture;this._updateID++;const t=e.uvs;this.mapCoord.set(t.x1-t.x0,t.y1-t.y0,t.x3-t.x0,t.y3-t.y0,t.x0,t.y0);const s=e.orig,r=e.trim;r&&(ga.set(s.width/r.width,0,0,s.height/r.height,-r.x/r.width,-r.y/r.height),this.mapCoord.append(ga));const n=e.source,o=this.uClampFrame,a=this.clampMargin/n._resolution,l=this.clampOffset/n._resolution;return o[0]=(e.frame.x+a+l)/n.width,o[1]=(e.frame.y+a+l)/n.height,o[2]=(e.frame.x+e.frame.width-a+l)/n.width,o[3]=(e.frame.y+e.frame.height-a+l)/n.height,this.uClampOffset[0]=this.clampOffset/n.pixelWidth,this.uClampOffset[1]=this.clampOffset/n.pixelHeight,this.isSimple=e.frame.width===n.width&&e.frame.height===n.height&&e.rotate===0,!0}}class j extends lt{constructor({source:e,label:t,frame:s,orig:r,trim:n,defaultAnchor:o,defaultBorders:a,rotate:l,dynamic:c}={}){if(super(),this.uid=be("texture"),this.uvs={x0:0,y0:0,x1:0,y1:0,x2:0,y2:0,x3:0,y3:0},this.frame=new Ce,this.noFrame=!1,this.dynamic=!1,this.isTexture=!0,this.label=t,this.source=(e==null?void 0:e.source)??new De,this.noFrame=!s,s)this.frame.copyFrom(s);else{const{width:h,height:u}=this._source;this.frame.width=h,this.frame.height=u}this.orig=r||this.frame,this.trim=n,this.rotate=l??0,this.defaultAnchor=o,this.defaultBorders=a,this.destroyed=!1,this.dynamic=c||!1,this.updateUvs()}set source(e){this._source&&this._source.off("resize",this.update,this),this._source=e,e.on("resize",this.update,this),this.emit("update",this)}get source(){return this._source}get textureMatrix(){return this._textureMatrix||(this._textureMatrix=new _a(this)),this._textureMatrix}get width(){return this.orig.width}get height(){return this.orig.height}updateUvs(){const{uvs:e,frame:t}=this,{width:s,height:r}=this._source,n=t.x/s,o=t.y/r,a=t.width/s,l=t.height/r;let c=this.rotate;if(c){const h=a/2,u=l/2,p=n+h,d=o+u;c=re.add(c,re.NW),e.x0=p+h*re.uX(c),e.y0=d+u*re.uY(c),c=re.add(c,2),e.x1=p+h*re.uX(c),e.y1=d+u*re.uY(c),c=re.add(c,2),e.x2=p+h*re.uX(c),e.y2=d+u*re.uY(c),c=re.add(c,2),e.x3=p+h*re.uX(c),e.y3=d+u*re.uY(c)}else e.x0=n,e.y0=o,e.x1=n+a,e.y1=o,e.x2=n+a,e.y2=o+l,e.x3=n,e.y3=o+l}destroy(e=!1){this._source&&(this._source.off("resize",this.update,this),e&&(this._source.destroy(),this._source=null)),this._textureMatrix=null,this.destroyed=!0,this.emit("destroy",this),this.removeAllListeners()}update(){this.noFrame&&(this.frame.width=this._source.width,this.frame.height=this._source.height),this.updateUvs(),this.emit("update",this)}get baseTexture(){return ee(Be,"Texture.baseTexture is now Texture.source"),this._source}}j.EMPTY=new j({label:"EMPTY",source:new De({label:"EMPTY"})}),j.EMPTY.destroy=ha,j.WHITE=new j({source:new Lr({resource:new Uint8Array([255,255,255,255]),width:1,height:1,alphaMode:"premultiply-alpha-on-upload",label:"WHITE"}),label:"WHITE"}),j.WHITE.destroy=ha;function $f(i,e,t){const{width:s,height:r}=t.orig,n=t.trim;if(n){const o=n.width,a=n.height;i.minX=n.x-e._x*s,i.maxX=i.minX+o,i.minY=n.y-e._y*r,i.maxY=i.minY+a}else i.minX=-e._x*s,i.maxX=i.minX+s,i.minY=-e._y*r,i.maxY=i.minY+r}const ya=new H;class Ye{constructor(e=1/0,t=1/0,s=-1/0,r=-1/0){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=ya,this.minX=e,this.minY=t,this.maxX=s,this.maxY=r}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}get rectangle(){this._rectangle||(this._rectangle=new Ce);const e=this._rectangle;return this.minX>this.maxX||this.minY>this.maxY?(e.x=0,e.y=0,e.width=0,e.height=0):e.copyFromBounds(this),e}clear(){return this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=ya,this}set(e,t,s,r){this.minX=e,this.minY=t,this.maxX=s,this.maxY=r}addFrame(e,t,s,r,n){n||(n=this.matrix);const o=n.a,a=n.b,l=n.c,c=n.d,h=n.tx,u=n.ty;let p=this.minX,d=this.minY,g=this.maxX,_=this.maxY,b=o*e+l*t+h,v=a*e+c*t+u;b<p&&(p=b),v<d&&(d=v),b>g&&(g=b),v>_&&(_=v),b=o*s+l*t+h,v=a*s+c*t+u,b<p&&(p=b),v<d&&(d=v),b>g&&(g=b),v>_&&(_=v),b=o*e+l*r+h,v=a*e+c*r+u,b<p&&(p=b),v<d&&(d=v),b>g&&(g=b),v>_&&(_=v),b=o*s+l*r+h,v=a*s+c*r+u,b<p&&(p=b),v<d&&(d=v),b>g&&(g=b),v>_&&(_=v),this.minX=p,this.minY=d,this.maxX=g,this.maxY=_}addRect(e,t){this.addFrame(e.x,e.y,e.x+e.width,e.y+e.height,t)}addBounds(e,t){this.addFrame(e.minX,e.minY,e.maxX,e.maxY,t)}addBoundsMask(e){this.minX=this.minX>e.minX?this.minX:e.minX,this.minY=this.minY>e.minY?this.minY:e.minY,this.maxX=this.maxX<e.maxX?this.maxX:e.maxX,this.maxY=this.maxY<e.maxY?this.maxY:e.maxY}applyMatrix(e){const t=this.minX,s=this.minY,r=this.maxX,n=this.maxY,{a:o,b:a,c:l,d:c,tx:h,ty:u}=e;let p=o*t+l*s+h,d=a*t+c*s+u;this.minX=p,this.minY=d,this.maxX=p,this.maxY=d,p=o*r+l*s+h,d=a*r+c*s+u,this.minX=p<this.minX?p:this.minX,this.minY=d<this.minY?d:this.minY,this.maxX=p>this.maxX?p:this.maxX,this.maxY=d>this.maxY?d:this.maxY,p=o*t+l*n+h,d=a*t+c*n+u,this.minX=p<this.minX?p:this.minX,this.minY=d<this.minY?d:this.minY,this.maxX=p>this.maxX?p:this.maxX,this.maxY=d>this.maxY?d:this.maxY,p=o*r+l*n+h,d=a*r+c*n+u,this.minX=p<this.minX?p:this.minX,this.minY=d<this.minY?d:this.minY,this.maxX=p>this.maxX?p:this.maxX,this.maxY=d>this.maxY?d:this.maxY}fit(e){return this.minX<e.left&&(this.minX=e.left),this.maxX>e.right&&(this.maxX=e.right),this.minY<e.top&&(this.minY=e.top),this.maxY>e.bottom&&(this.maxY=e.bottom),this}fitBounds(e,t,s,r){return this.minX<e&&(this.minX=e),this.maxX>t&&(this.maxX=t),this.minY<s&&(this.minY=s),this.maxY>r&&(this.maxY=r),this}pad(e,t=e){return this.minX-=e,this.maxX+=e,this.minY-=t,this.maxY+=t,this}ceil(){return this.minX=Math.floor(this.minX),this.minY=Math.floor(this.minY),this.maxX=Math.ceil(this.maxX),this.maxY=Math.ceil(this.maxY),this}clone(){return new Ye(this.minX,this.minY,this.maxX,this.maxY)}scale(e,t=e){return this.minX*=e,this.minY*=t,this.maxX*=e,this.maxY*=t,this}get x(){return this.minX}set x(e){const t=this.maxX-this.minX;this.minX=e,this.maxX=e+t}get y(){return this.minY}set y(e){const t=this.maxY-this.minY;this.minY=e,this.maxY=e+t}get width(){return this.maxX-this.minX}set width(e){this.maxX=this.minX+e}get height(){return this.maxY-this.minY}set height(e){this.maxY=this.minY+e}get left(){return this.minX}get right(){return this.maxX}get top(){return this.minY}get bottom(){return this.maxY}get isPositive(){return this.maxX-this.minX>0&&this.maxY-this.minY>0}get isValid(){return this.minX+this.minY!==1/0}addVertexData(e,t,s,r){let n=this.minX,o=this.minY,a=this.maxX,l=this.maxY;r||(r=this.matrix);const c=r.a,h=r.b,u=r.c,p=r.d,d=r.tx,g=r.ty;for(let _=t;_<s;_+=2){const b=e[_],v=e[_+1],C=c*b+u*v+d,E=h*b+p*v+g;n=C<n?C:n,o=E<o?E:o,a=C>a?C:a,l=E>l?E:l}this.minX=n,this.minY=o,this.maxX=a,this.maxY=l}containsPoint(e,t){return this.minX<=e&&this.minY<=t&&this.maxX>=e&&this.maxY>=t}toString(){return`[pixi.js:Bounds minX=${this.minX} minY=${this.minY} maxX=${this.maxX} maxY=${this.maxY} width=${this.width} height=${this.height}]`}copyFrom(e){return this.minX=e.minX,this.minY=e.minY,this.maxX=e.maxX,this.maxY=e.maxY,this}}var jf={grad:.9,turn:360,rad:360/(2*Math.PI)},St=function(i){return typeof i=="string"?i.length>0:typeof i=="number"},Fe=function(i,e,t){return e===void 0&&(e=0),t===void 0&&(t=Math.pow(10,e)),Math.round(t*i)/t+0},ot=function(i,e,t){return e===void 0&&(e=0),t===void 0&&(t=1),i>t?t:i>e?i:e},ba=function(i){return(i=isFinite(i)?i%360:0)>0?i:i+360},va=function(i){return{r:ot(i.r,0,255),g:ot(i.g,0,255),b:ot(i.b,0,255),a:ot(i.a)}},Wr=function(i){return{r:Fe(i.r),g:Fe(i.g),b:Fe(i.b),a:Fe(i.a,3)}},Xf=/^#([0-9a-f]{3,8})$/i,Fi=function(i){var e=i.toString(16);return e.length<2?"0"+e:e},xa=function(i){var e=i.r,t=i.g,s=i.b,r=i.a,n=Math.max(e,t,s),o=n-Math.min(e,t,s),a=o?n===e?(t-s)/o:n===t?2+(s-e)/o:4+(e-t)/o:0;return{h:60*(a<0?a+6:a),s:n?o/n*100:0,v:n/255*100,a:r}},Ca=function(i){var e=i.h,t=i.s,s=i.v,r=i.a;e=e/360*6,t/=100,s/=100;var n=Math.floor(e),o=s*(1-t),a=s*(1-(e-n)*t),l=s*(1-(1-e+n)*t),c=n%6;return{r:255*[s,a,o,o,l,s][c],g:255*[l,s,s,a,o,o][c],b:255*[o,o,l,s,s,a][c],a:r}},Ea=function(i){return{h:ba(i.h),s:ot(i.s,0,100),l:ot(i.l,0,100),a:ot(i.a)}},Sa=function(i){return{h:Fe(i.h),s:Fe(i.s),l:Fe(i.l),a:Fe(i.a,3)}},Ta=function(i){return Ca((t=(e=i).s,{h:e.h,s:(t*=((s=e.l)<50?s:100-s)/100)>0?2*t/(s+t)*100:0,v:s+t,a:e.a}));var e,t,s},$s=function(i){return{h:(e=xa(i)).h,s:(r=(200-(t=e.s))*(s=e.v)/100)>0&&r<200?t*s/100/(r<=100?r:200-r)*100:0,l:r/2,a:e.a};var e,t,s,r},Yf=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,qf=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Kf=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Zf=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Hr={string:[[function(i){var e=Xf.exec(i);return e?(i=e[1]).length<=4?{r:parseInt(i[0]+i[0],16),g:parseInt(i[1]+i[1],16),b:parseInt(i[2]+i[2],16),a:i.length===4?Fe(parseInt(i[3]+i[3],16)/255,2):1}:i.length===6||i.length===8?{r:parseInt(i.substr(0,2),16),g:parseInt(i.substr(2,2),16),b:parseInt(i.substr(4,2),16),a:i.length===8?Fe(parseInt(i.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(i){var e=Kf.exec(i)||Zf.exec(i);return e?e[2]!==e[4]||e[4]!==e[6]?null:va({r:Number(e[1])/(e[2]?100/255:1),g:Number(e[3])/(e[4]?100/255:1),b:Number(e[5])/(e[6]?100/255:1),a:e[7]===void 0?1:Number(e[7])/(e[8]?100:1)}):null},"rgb"],[function(i){var e=Yf.exec(i)||qf.exec(i);if(!e)return null;var t,s,r=Ea({h:(t=e[1],s=e[2],s===void 0&&(s="deg"),Number(t)*(jf[s]||1)),s:Number(e[3]),l:Number(e[4]),a:e[5]===void 0?1:Number(e[5])/(e[6]?100:1)});return Ta(r)},"hsl"]],object:[[function(i){var e=i.r,t=i.g,s=i.b,r=i.a,n=r===void 0?1:r;return St(e)&&St(t)&&St(s)?va({r:Number(e),g:Number(t),b:Number(s),a:Number(n)}):null},"rgb"],[function(i){var e=i.h,t=i.s,s=i.l,r=i.a,n=r===void 0?1:r;if(!St(e)||!St(t)||!St(s))return null;var o=Ea({h:Number(e),s:Number(t),l:Number(s),a:Number(n)});return Ta(o)},"hsl"],[function(i){var e=i.h,t=i.s,s=i.v,r=i.a,n=r===void 0?1:r;if(!St(e)||!St(t)||!St(s))return null;var o=(function(a){return{h:ba(a.h),s:ot(a.s,0,100),v:ot(a.v,0,100),a:ot(a.a)}})({h:Number(e),s:Number(t),v:Number(s),a:Number(n)});return Ca(o)},"hsv"]]},Aa=function(i,e){for(var t=0;t<e.length;t++){var s=e[t][0](i);if(s)return[s,e[t][1]]}return[null,void 0]},Jf=function(i){return typeof i=="string"?Aa(i.trim(),Hr.string):typeof i=="object"&&i!==null?Aa(i,Hr.object):[null,void 0]},Vr=function(i,e){var t=$s(i);return{h:t.h,s:ot(t.s+100*e,0,100),l:t.l,a:t.a}},zr=function(i){return(299*i.r+587*i.g+114*i.b)/1e3/255},wa=function(i,e){var t=$s(i);return{h:t.h,s:t.s,l:ot(t.l+100*e,0,100),a:t.a}},$r=(function(){function i(e){this.parsed=Jf(e)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return i.prototype.isValid=function(){return this.parsed!==null},i.prototype.brightness=function(){return Fe(zr(this.rgba),2)},i.prototype.isDark=function(){return zr(this.rgba)<.5},i.prototype.isLight=function(){return zr(this.rgba)>=.5},i.prototype.toHex=function(){return e=Wr(this.rgba),t=e.r,s=e.g,r=e.b,o=(n=e.a)<1?Fi(Fe(255*n)):"","#"+Fi(t)+Fi(s)+Fi(r)+o;var e,t,s,r,n,o},i.prototype.toRgb=function(){return Wr(this.rgba)},i.prototype.toRgbString=function(){return e=Wr(this.rgba),t=e.r,s=e.g,r=e.b,(n=e.a)<1?"rgba("+t+", "+s+", "+r+", "+n+")":"rgb("+t+", "+s+", "+r+")";var e,t,s,r,n},i.prototype.toHsl=function(){return Sa($s(this.rgba))},i.prototype.toHslString=function(){return e=Sa($s(this.rgba)),t=e.h,s=e.s,r=e.l,(n=e.a)<1?"hsla("+t+", "+s+"%, "+r+"%, "+n+")":"hsl("+t+", "+s+"%, "+r+"%)";var e,t,s,r,n},i.prototype.toHsv=function(){return e=xa(this.rgba),{h:Fe(e.h),s:Fe(e.s),v:Fe(e.v),a:Fe(e.a,3)};var e},i.prototype.invert=function(){return pt({r:255-(e=this.rgba).r,g:255-e.g,b:255-e.b,a:e.a});var e},i.prototype.saturate=function(e){return e===void 0&&(e=.1),pt(Vr(this.rgba,e))},i.prototype.desaturate=function(e){return e===void 0&&(e=.1),pt(Vr(this.rgba,-e))},i.prototype.grayscale=function(){return pt(Vr(this.rgba,-1))},i.prototype.lighten=function(e){return e===void 0&&(e=.1),pt(wa(this.rgba,e))},i.prototype.darken=function(e){return e===void 0&&(e=.1),pt(wa(this.rgba,-e))},i.prototype.rotate=function(e){return e===void 0&&(e=15),this.hue(this.hue()+e)},i.prototype.alpha=function(e){return typeof e=="number"?pt({r:(t=this.rgba).r,g:t.g,b:t.b,a:e}):Fe(this.rgba.a,3);var t},i.prototype.hue=function(e){var t=$s(this.rgba);return typeof e=="number"?pt({h:e,s:t.s,l:t.l,a:t.a}):Fe(t.h)},i.prototype.isEqual=function(e){return this.toHex()===pt(e).toHex()},i})(),pt=function(i){return i instanceof $r?i:new $r(i)},Ia=[],Qf=function(i){i.forEach(function(e){Ia.indexOf(e)<0&&(e($r,Hr),Ia.push(e))})};function ep(i,e){var t={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},s={};for(var r in t)s[t[r]]=r;var n={};i.prototype.toName=function(o){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var a,l,c=s[this.toHex()];if(c)return c;if(o!=null&&o.closest){var h=this.toRgb(),u=1/0,p="black";if(!n.length)for(var d in t)n[d]=new i(t[d]).toRgb();for(var g in t){var _=(a=h,l=n[g],Math.pow(a.r-l.r,2)+Math.pow(a.g-l.g,2)+Math.pow(a.b-l.b,2));_<u&&(u=_,p=g)}return p}},e.string.push([function(o){var a=o.toLowerCase(),l=a==="transparent"?"#0000":t[a];return l?new i(l).toRgb():null},"name"])}Qf([ep]);const ps=class Oi{constructor(e=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=e}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(e){return this.value=e,this}set value(e){if(e instanceof Oi)this._value=this._cloneSource(e._value),this._int=e._int,this._components.set(e._components);else{if(e===null)throw new Error("Cannot set Color#value to null");(this._value===null||!this._isSourceEqual(this._value,e))&&(this._value=this._cloneSource(e),this._normalize(this._value))}}get value(){return this._value}_cloneSource(e){return typeof e=="string"||typeof e=="number"||e instanceof Number||e===null?e:Array.isArray(e)||ArrayBuffer.isView(e)?e.slice(0):typeof e=="object"&&e!==null?{...e}:e}_isSourceEqual(e,t){const s=typeof e;if(s!==typeof t)return!1;if(s==="number"||s==="string"||e instanceof Number)return e===t;if(Array.isArray(e)&&Array.isArray(t)||ArrayBuffer.isView(e)&&ArrayBuffer.isView(t))return e.length!==t.length?!1:e.every((n,o)=>n===t[o]);if(e!==null&&t!==null){const n=Object.keys(e),o=Object.keys(t);return n.length!==o.length?!1:n.every(a=>e[a]===t[a])}return e===t}toRgba(){const[e,t,s,r]=this._components;return{r:e,g:t,b:s,a:r}}toRgb(){const[e,t,s]=this._components;return{r:e,g:t,b:s}}toRgbaString(){const[e,t,s]=this.toUint8RgbArray();return`rgba(${e},${t},${s},${this.alpha})`}toUint8RgbArray(e){const[t,s,r]=this._components;return this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb),e[0]=Math.round(t*255),e[1]=Math.round(s*255),e[2]=Math.round(r*255),e}toArray(e){this._arrayRgba||(this._arrayRgba=[]),e||(e=this._arrayRgba);const[t,s,r,n]=this._components;return e[0]=t,e[1]=s,e[2]=r,e[3]=n,e}toRgbArray(e){this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb);const[t,s,r]=this._components;return e[0]=t,e[1]=s,e[2]=r,e}toNumber(){return this._int}toBgrNumber(){const[e,t,s]=this.toUint8RgbArray();return(s<<16)+(t<<8)+e}toLittleEndianNumber(){const e=this._int;return(e>>16)+(e&65280)+((e&255)<<16)}multiply(e){const[t,s,r,n]=Oi._temp.setValue(e)._components;return this._components[0]*=t,this._components[1]*=s,this._components[2]*=r,this._components[3]*=n,this._refreshInt(),this._value=null,this}premultiply(e,t=!0){return t&&(this._components[0]*=e,this._components[1]*=e,this._components[2]*=e),this._components[3]=e,this._refreshInt(),this._value=null,this}toPremultiplied(e,t=!0){if(e===1)return(255<<24)+this._int;if(e===0)return t?0:this._int;let s=this._int>>16&255,r=this._int>>8&255,n=this._int&255;return t&&(s=s*e+.5|0,r=r*e+.5|0,n=n*e+.5|0),(e*255<<24)+(s<<16)+(r<<8)+n}toHex(){const e=this._int.toString(16);return`#${"000000".substring(0,6-e.length)+e}`}toHexa(){const t=Math.round(this._components[3]*255).toString(16);return this.toHex()+"00".substring(0,2-t.length)+t}setAlpha(e){return this._components[3]=this._clamp(e),this._value=null,this}_normalize(e){let t,s,r,n;if((typeof e=="number"||e instanceof Number)&&e>=0&&e<=16777215){const o=e;t=(o>>16&255)/255,s=(o>>8&255)/255,r=(o&255)/255,n=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[t,s,r,n=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[t,s,r,n=255]=e,t/=255,s/=255,r/=255,n/=255;else if(typeof e=="string"||typeof e=="object"){if(typeof e=="string"){const a=Oi.HEX_PATTERN.exec(e);a&&(e=`#${a[2]}`)}const o=pt(e);o.isValid()&&({r:t,g:s,b:r,a:n}=o.rgba,t/=255,s/=255,r/=255)}if(t!==void 0)this._components[0]=t,this._components[1]=s,this._components[2]=r,this._components[3]=n,this._refreshInt();else throw new Error(`Unable to convert color ${e}`)}_refreshInt(){this._clamp(this._components);const[e,t,s]=this._components;this._int=(e*255<<16)+(t*255<<8)+(s*255|0)}_clamp(e,t=0,s=1){return typeof e=="number"?Math.min(Math.max(e,t),s):(e.forEach((r,n)=>{e[n]=Math.min(Math.max(r,t),s)}),e)}static isColorLike(e){return typeof e=="number"||typeof e=="string"||e instanceof Number||e instanceof Oi||Array.isArray(e)||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Float32Array||e.r!==void 0&&e.g!==void 0&&e.b!==void 0||e.r!==void 0&&e.g!==void 0&&e.b!==void 0&&e.a!==void 0||e.h!==void 0&&e.s!==void 0&&e.l!==void 0||e.h!==void 0&&e.s!==void 0&&e.l!==void 0&&e.a!==void 0||e.h!==void 0&&e.s!==void 0&&e.v!==void 0||e.h!==void 0&&e.s!==void 0&&e.v!==void 0&&e.a!==void 0}};ps.shared=new ps,ps._temp=new ps,ps.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let Pe=ps;const tp={cullArea:null,cullable:!1,cullableChildren:!0};let jr=0;const Ra=500;function ie(...i){jr!==Ra&&(jr++,jr===Ra?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...i))}const ms={_registeredResources:new Set,register(i){this._registeredResources.add(i)},unregister(i){this._registeredResources.delete(i)},release(){this._registeredResources.forEach(i=>i.clear())},get registeredCount(){return this._registeredResources.size},isRegistered(i){return this._registeredResources.has(i)},reset(){this._registeredResources.clear()}};class sp{constructor(e,t){this._pool=[],this._count=0,this._index=0,this._classType=e,t&&this.prepopulate(t)}prepopulate(e){for(let t=0;t<e;t++)this._pool[this._index++]=new this._classType;this._count+=e}get(e){var s;let t;return this._index>0?t=this._pool[--this._index]:(t=new this._classType,this._count++),(s=t.init)==null||s.call(t,e),t}return(e){var t;(t=e.reset)==null||t.call(e),this._pool[this._index++]=e}get totalSize(){return this._count}get totalFree(){return this._index}get totalUsed(){return this._count-this._index}clear(){if(this._pool.length>0&&this._pool[0].destroy)for(let e=0;e<this._index;e++)this._pool[e].destroy();this._pool.length=0,this._count=0,this._index=0}}class ip{constructor(){this._poolsByClass=new Map}prepopulate(e,t){this.getPool(e).prepopulate(t)}get(e,t){return this.getPool(e).get(t)}return(e){this.getPool(e.constructor).return(e)}getPool(e){return this._poolsByClass.has(e)||this._poolsByClass.set(e,new sp(e)),this._poolsByClass.get(e)}stats(){const e={};return this._poolsByClass.forEach(t=>{const s=e[t._classType.name]?t._classType.name+t._classType.ID:t._classType.name;e[s]={free:t.totalFree,used:t.totalUsed,size:t.totalSize}}),e}clear(){this._poolsByClass.forEach(e=>e.clear()),this._poolsByClass.clear()}}const Le=new ip;ms.register(Le);const rp={get isCachedAsTexture(){var i;return!!((i=this.renderGroup)!=null&&i.isCachedAsTexture)},cacheAsTexture(i){typeof i=="boolean"&&i===!1?this.disableRenderGroup():(this.enableRenderGroup(),this.renderGroup.enableCacheAsTexture(i===!0?{}:i))},updateCacheTexture(){var i;(i=this.renderGroup)==null||i.updateCacheTexture()},get cacheAsBitmap(){return this.isCachedAsTexture},set cacheAsBitmap(i){ee("v8.6.0","cacheAsBitmap is deprecated, use cacheAsTexture instead."),this.cacheAsTexture(i)}};function Ma(i,e,t){const s=i.length;let r;if(e>=s||t===0)return;t=e+t>s?s-e:t;const n=s-t;for(r=e;r<n;++r)i[r]=i[r+t];i.length=n}const np={allowChildren:!0,removeChildren(i=0,e){var n;const t=e??this.children.length,s=t-i,r=[];if(s>0&&s<=t){for(let a=t-1;a>=i;a--){const l=this.children[a];l&&(r.push(l),l.parent=null)}Ma(this.children,i,t);const o=this.renderGroup||this.parentRenderGroup;o&&o.removeChildren(r);for(let a=0;a<r.length;++a){const l=r[a];(n=l.parentRenderLayer)==null||n.detach(l),this.emit("childRemoved",l,this,a),r[a].emit("removed",this)}return r.length>0&&this._didViewChangeTick++,r}else if(s===0&&this.children.length===0)return r;throw new RangeError("removeChildren: numeric values are outside the acceptable range.")},removeChildAt(i){const e=this.getChildAt(i);return this.removeChild(e)},getChildAt(i){if(i<0||i>=this.children.length)throw new Error(`getChildAt: Index (${i}) does not exist.`);return this.children[i]},setChildIndex(i,e){if(e<0||e>=this.children.length)throw new Error(`The index ${e} supplied is out of bounds ${this.children.length}`);this.getChildIndex(i),this.addChildAt(i,e)},getChildIndex(i){const e=this.children.indexOf(i);if(e===-1)throw new Error("The supplied Container must be a child of the caller");return e},addChildAt(i,e){this.allowChildren||ee(Be,"addChildAt: Only Containers will be allowed to add children in v8.0.0");const{children:t}=this;if(e<0||e>t.length)throw new Error(`${i}addChildAt: The index ${e} supplied is out of bounds ${t.length}`);const s=i.parent===this;if(i.parent){const n=i.parent.children.indexOf(i);if(s){if(n===e)return i;i.parent.children.splice(n,1)}else i.removeFromParent()}e===t.length?t.push(i):t.splice(e,0,i),i.parent=this,i.didChange=!0,i._updateFlags=15;const r=this.renderGroup||this.parentRenderGroup;return r&&r.addChild(i),this.sortableChildren&&(this.sortDirty=!0),s||(this.emit("childAdded",i,this,e),i.emit("added",this)),i},swapChildren(i,e){if(i===e)return;const t=this.getChildIndex(i),s=this.getChildIndex(e);this.children[t]=e,this.children[s]=i;const r=this.renderGroup||this.parentRenderGroup;r&&(r.structureDidChange=!0),this._didContainerChangeTick++},removeFromParent(){var i;(i=this.parent)==null||i.removeChild(this)},reparentChild(...i){return i.length===1?this.reparentChildAt(i[0],this.children.length):(i.forEach(e=>this.reparentChildAt(e,this.children.length)),i[0])},reparentChildAt(i,e){if(i.parent===this)return this.setChildIndex(i,e),i;const t=i.worldTransform.clone();i.removeFromParent(),this.addChildAt(i,e);const s=this.worldTransform.clone();return s.invert(),t.prepend(s),i.setFromMatrix(t),i},replaceChild(i,e){i.updateLocalTransform(),this.addChildAt(e,this.getChildIndex(i)),e.setFromMatrix(i.localTransform),e.updateLocalTransform(),this.removeChild(i)}},op={collectRenderables(i,e,t){this.parentRenderLayer&&this.parentRenderLayer!==t||this.globalDisplayStatus<7||!this.includeInBuild||(this.sortableChildren&&this.sortChildren(),this.isSimple?this.collectRenderablesSimple(i,e,t):this.renderGroup?e.renderPipes.renderGroup.addRenderGroup(this.renderGroup,i):this.collectRenderablesWithEffects(i,e,t))},collectRenderablesSimple(i,e,t){const s=this.children,r=s.length;for(let n=0;n<r;n++)s[n].collectRenderables(i,e,t)},collectRenderablesWithEffects(i,e,t){const{renderPipes:s}=e;for(let r=0;r<this.effects.length;r++){const n=this.effects[r];s[n.pipe].push(n,this,i)}this.collectRenderablesSimple(i,e,t);for(let r=this.effects.length-1;r>=0;r--){const n=this.effects[r];s[n.pipe].pop(n,this,i)}}};class Li{constructor(){this.pipe="filter",this.priority=1}destroy(){for(let e=0;e<this.filters.length;e++)this.filters[e].destroy();this.filters=null,this.filterArea=null}}class ap{constructor(){this._effectClasses=[],this._tests=[],this._initialized=!1}init(){this._initialized||(this._initialized=!0,this._effectClasses.forEach(e=>{this.add({test:e.test,maskClass:e})}))}add(e){this._tests.push(e)}getMaskEffect(e){this._initialized||this.init();for(let t=0;t<this._tests.length;t++){const s=this._tests[t];if(s.test(e))return Le.get(s.maskClass,e)}return e}returnMaskEffect(e){Le.return(e)}}const Xr=new ap;Q.handleByList(A.MaskEffect,Xr._effectClasses);const lp={_maskEffect:null,_maskOptions:{inverse:!1},_filterEffect:null,effects:[],_markStructureAsChanged(){const i=this.renderGroup||this.parentRenderGroup;i&&(i.structureDidChange=!0)},addEffect(i){this.effects.indexOf(i)===-1&&(this.effects.push(i),this.effects.sort((t,s)=>t.priority-s.priority),this._markStructureAsChanged(),this._updateIsSimple())},removeEffect(i){const e=this.effects.indexOf(i);e!==-1&&(this.effects.splice(e,1),this._markStructureAsChanged(),this._updateIsSimple())},set mask(i){const e=this._maskEffect;(e==null?void 0:e.mask)!==i&&(e&&(this.removeEffect(e),Xr.returnMaskEffect(e),this._maskEffect=null),i!=null&&(this._maskEffect=Xr.getMaskEffect(i),this.addEffect(this._maskEffect)))},get mask(){var i;return(i=this._maskEffect)==null?void 0:i.mask},setMask(i){this._maskOptions={...this._maskOptions,...i},i.mask&&(this.mask=i.mask),this._markStructureAsChanged()},set filters(i){var n;!Array.isArray(i)&&i&&(i=[i]);const e=this._filterEffect||(this._filterEffect=new Li);i=i;const t=(i==null?void 0:i.length)>0,s=((n=e.filters)==null?void 0:n.length)>0,r=t!==s;i=Array.isArray(i)?i.slice(0):i,e.filters=Object.freeze(i),r&&(t?this.addEffect(e):(this.removeEffect(e),e.filters=i??null))},get filters(){var i;return(i=this._filterEffect)==null?void 0:i.filters},set filterArea(i){this._filterEffect||(this._filterEffect=new Li),this._filterEffect.filterArea=i},get filterArea(){var i;return(i=this._filterEffect)==null?void 0:i.filterArea}},cp={label:null,get name(){return ee(Be,"Container.name property has been removed, use Container.label instead"),this.label},set name(i){ee(Be,"Container.name property has been removed, use Container.label instead"),this.label=i},getChildByName(i,e=!1){return this.getChildByLabel(i,e)},getChildByLabel(i,e=!1){const t=this.children;for(let s=0;s<t.length;s++){const r=t[s];if(r.label===i||i instanceof RegExp&&i.test(r.label))return r}if(e)for(let s=0;s<t.length;s++){const n=t[s].getChildByLabel(i,!0);if(n)return n}return null},getChildrenByLabel(i,e=!1,t=[]){const s=this.children;for(let r=0;r<s.length;r++){const n=s[r];(n.label===i||i instanceof RegExp&&i.test(n.label))&&t.push(n)}if(e)for(let r=0;r<s.length;r++)s[r].getChildrenByLabel(i,!0,t);return t}},qe=Le.getPool(H),Tt=Le.getPool(Ye),hp=new H,up={getFastGlobalBounds(i,e){e||(e=new Ye),e.clear(),this._getGlobalBoundsRecursive(!!i,e,this.parentRenderLayer),e.isValid||e.set(0,0,0,0);const t=this.renderGroup||this.parentRenderGroup;return e.applyMatrix(t.worldTransform),e},_getGlobalBoundsRecursive(i,e,t){let s=e;if(i&&this.parentRenderLayer&&this.parentRenderLayer!==t||this.localDisplayStatus!==7||!this.measurable)return;const r=!!this.effects.length;if((this.renderGroup||r)&&(s=Tt.get().clear()),this.boundsArea)e.addRect(this.boundsArea,this.worldTransform);else{if(this.renderPipeId){const o=this.bounds;s.addFrame(o.minX,o.minY,o.maxX,o.maxY,this.groupTransform)}const n=this.children;for(let o=0;o<n.length;o++)n[o]._getGlobalBoundsRecursive(i,s,t)}if(r){let n=!1;const o=this.renderGroup||this.parentRenderGroup;for(let a=0;a<this.effects.length;a++)this.effects[a].addBounds&&(n||(n=!0,s.applyMatrix(o.worldTransform)),this.effects[a].addBounds(s,!0));n&&s.applyMatrix(o.worldTransform.copyTo(hp).invert()),e.addBounds(s),Tt.return(s)}else this.renderGroup&&(e.addBounds(s,this.relativeGroupTransform),Tt.return(s))}};function Yr(i,e,t){t.clear();let s,r;return i.parent?e?s=i.parent.worldTransform:(r=qe.get().identity(),s=qr(i,r)):s=H.IDENTITY,Pa(i,t,s,e),r&&qe.return(r),t.isValid||t.set(0,0,0,0),t}function Pa(i,e,t,s){var a,l;if(!i.visible||!i.measurable)return;let r;s?r=i.worldTransform:(i.updateLocalTransform(),r=qe.get(),r.appendFrom(i.localTransform,t));const n=e,o=!!i.effects.length;if(o&&(e=Tt.get().clear()),i.boundsArea)e.addRect(i.boundsArea,r);else{const c=i.bounds;c&&!c.isEmpty()&&(e.matrix=r,e.addBounds(c));for(let h=0;h<i.children.length;h++)Pa(i.children[h],e,r,s)}if(o){for(let c=0;c<i.effects.length;c++)(l=(a=i.effects[c]).addBounds)==null||l.call(a,e);n.addBounds(e,H.IDENTITY),Tt.return(e)}s||qe.return(r)}function qr(i,e){const t=i.parent;return t&&(qr(t,e),t.updateLocalTransform(),e.append(t.localTransform)),e}function gs(i,e){if(i===16777215||!e)return e;if(e===16777215||!i)return i;const t=i>>16&255,s=i>>8&255,r=i&255,n=e>>16&255,o=e>>8&255,a=e&255,l=t*n/255|0,c=s*o/255|0,h=r*a/255|0;return(l<<16)+(c<<8)+h}const ka=16777215;function Wi(i,e){return i===ka?e:e===ka?i:gs(i,e)}function _s(i){return((i&255)<<16)+(i&65280)+(i>>16&255)}const dp={getGlobalAlpha(i){if(i)return this.renderGroup?this.renderGroup.worldAlpha:this.parentRenderGroup?this.parentRenderGroup.worldAlpha*this.alpha:this.alpha;let e=this.alpha,t=this.parent;for(;t;)e*=t.alpha,t=t.parent;return e},getGlobalTransform(i=new H,e){if(e)return i.copyFrom(this.worldTransform);this.updateLocalTransform();const t=qr(this,qe.get().identity());return i.appendFrom(this.localTransform,t),qe.return(t),i},getGlobalTint(i){if(i)return this.renderGroup?_s(this.renderGroup.worldColor):this.parentRenderGroup?_s(Wi(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let e=this.localColor,t=this.parent;for(;t;)e=Wi(e,t.localColor),t=t.parent;return _s(e)}};function Kr(i,e,t){return e.clear(),t||(t=H.IDENTITY),Oa(i,e,t,i,!0),e.isValid||e.set(0,0,0,0),e}function Oa(i,e,t,s,r){var l,c;let n;if(r)n=qe.get(),n=t.copyTo(n);else{if(!i.visible||!i.measurable)return;i.updateLocalTransform();const h=i.localTransform;n=qe.get(),n.appendFrom(h,t)}const o=e,a=!!i.effects.length;if(a&&(e=Tt.get().clear()),i.boundsArea)e.addRect(i.boundsArea,n);else{i.renderPipeId&&(e.matrix=n,e.addBounds(i.bounds));const h=i.children;for(let u=0;u<h.length;u++)Oa(h[u],e,n,s,!1)}if(a){for(let h=0;h<i.effects.length;h++)(c=(l=i.effects[h]).addLocalBounds)==null||c.call(l,e,s);o.addBounds(e,H.IDENTITY),Tt.return(e)}qe.return(n)}function Ba(i,e){const t=i.children;for(let s=0;s<t.length;s++){const r=t[s],n=r.uid,o=(r._didViewChangeTick&65535)<<16|r._didContainerChangeTick&65535,a=e.index;(e.data[a]!==n||e.data[a+1]!==o)&&(e.data[e.index]=n,e.data[e.index+1]=o,e.didChange=!0),e.index=a+2,r.children.length&&Ba(r,e)}return e.didChange}const fp=new H,pp={_localBoundsCacheId:-1,_localBoundsCacheData:null,_setWidth(i,e){const t=Math.sign(this.scale.x)||1;e!==0?this.scale.x=i/e*t:this.scale.x=t},_setHeight(i,e){const t=Math.sign(this.scale.y)||1;e!==0?this.scale.y=i/e*t:this.scale.y=t},getLocalBounds(){this._localBoundsCacheData||(this._localBoundsCacheData={data:[],index:1,didChange:!1,localBounds:new Ye});const i=this._localBoundsCacheData;return i.index=1,i.didChange=!1,i.data[0]!==this._didViewChangeTick&&(i.didChange=!0,i.data[0]=this._didViewChangeTick),Ba(this,i),i.didChange&&Kr(this,i.localBounds,fp),i.localBounds},getBounds(i,e){return Yr(this,i,e||new Ye)}},mp={_onRender:null,set onRender(i){const e=this.renderGroup||this.parentRenderGroup;if(!i){this._onRender&&(e==null||e.removeOnRender(this)),this._onRender=null;return}this._onRender||e==null||e.addOnRender(this),this._onRender=i},get onRender(){return this._onRender}},gp={_zIndex:0,sortDirty:!1,sortableChildren:!1,get zIndex(){return this._zIndex},set zIndex(i){this._zIndex!==i&&(this._zIndex=i,this.depthOfChildModified())},depthOfChildModified(){this.parent&&(this.parent.sortableChildren=!0,this.parent.sortDirty=!0),this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0)},sortChildren(){this.sortDirty&&(this.sortDirty=!1,this.children.sort(_p))}};function _p(i,e){return i._zIndex-e._zIndex}const yp={getGlobalPosition(i=new ye,e=!1){return this.parent?this.parent.toGlobal(this._position,i,e):(i.x=this._position.x,i.y=this._position.y),i},toGlobal(i,e,t=!1){const s=this.getGlobalTransform(qe.get(),t);return e=s.apply(i,e),qe.return(s),e},toLocal(i,e,t,s){e&&(i=e.toGlobal(i,t,s));const r=this.getGlobalTransform(qe.get(),s);return t=r.applyInverse(i,t),qe.return(r),t}};class Zr{constructor(){this.uid=be("instructionSet"),this.instructions=[],this.instructionSize=0,this.renderables=[],this.gcTick=0}reset(){this.instructionSize=0}destroy(){this.instructions.length=0,this.renderables.length=0,this.renderPipes=null,this.gcTick=0}add(e){this.instructions[this.instructionSize++]=e}log(){this.instructions.length=this.instructionSize,console.table(this.instructions,["type","action"])}}let bp=0;class vp{constructor(e){this._poolKeyHash=Object.create(null),this._texturePool={},this.textureOptions=e||{},this.enableFullScreen=!1,this.textureStyle=new Fr(this.textureOptions)}createTexture(e,t,s,r){const n=new De({...this.textureOptions,width:e,height:t,resolution:1,antialias:s,autoGarbageCollect:!1,autoGenerateMipmaps:r});return new j({source:n,label:`texturePool_${bp++}`})}getOptimalTexture(e,t,s=1,r,n=!1){let o=Math.ceil(e*s-1e-6),a=Math.ceil(t*s-1e-6);o=Gi(o),a=Gi(a);const l=r?1:0,c=n?1:0,h=(o<<17)+(a<<2)+(c<<1)+l;this._texturePool[h]||(this._texturePool[h]=[]);let u=this._texturePool[h].pop();return u||(u=this.createTexture(o,a,r,n)),u.source._resolution=s,u.source.width=o/s,u.source.height=a/s,u.source.pixelWidth=o,u.source.pixelHeight=a,u.frame.x=0,u.frame.y=0,u.frame.width=e,u.frame.height=t,u.updateUvs(),this._poolKeyHash[u.uid]=h,u}getSameSizeTexture(e,t=!1){const s=e.source;return this.getOptimalTexture(e.width,e.height,s._resolution,t)}returnTexture(e,t=!1){const s=this._poolKeyHash[e.uid];t&&(e.source.style=this.textureStyle),this._texturePool[s].push(e)}clear(e){if(e=e!==!1,e)for(const t in this._texturePool){const s=this._texturePool[t];if(s)for(let r=0;r<s.length;r++)s[r].destroy(!0)}this._texturePool={}}}const Qe=new vp;ms.register(Qe);class Jr{constructor(){this.renderPipeId="renderGroup",this.root=null,this.canBundle=!1,this.renderGroupParent=null,this.renderGroupChildren=[],this.worldTransform=new H,this.worldColorAlpha=4294967295,this.worldColor=16777215,this.worldAlpha=1,this.childrenToUpdate=Object.create(null),this.updateTick=0,this.gcTick=0,this.childrenRenderablesToUpdate={list:[],index:0},this.structureDidChange=!0,this.instructionSet=new Zr,this._onRenderContainers=[],this.textureNeedsUpdate=!0,this.isCachedAsTexture=!1,this._matrixDirty=7}init(e){this.root=e,e._onRender&&this.addOnRender(e),e.didChange=!0;const t=e.children;for(let s=0;s<t.length;s++){const r=t[s];r._updateFlags=15,this.addChild(r)}}enableCacheAsTexture(e={}){this.textureOptions=e,this.isCachedAsTexture=!0,this.textureNeedsUpdate=!0}disableCacheAsTexture(){this.isCachedAsTexture=!1,this.texture&&(Qe.returnTexture(this.texture,!0),this.texture=null)}updateCacheTexture(){this.textureNeedsUpdate=!0;const e=this._parentCacheAsTextureRenderGroup;e&&!e.textureNeedsUpdate&&e.updateCacheTexture()}reset(){this.renderGroupChildren.length=0;for(const e in this.childrenToUpdate){const t=this.childrenToUpdate[e];t.list.fill(null),t.index=0}this.childrenRenderablesToUpdate.index=0,this.childrenRenderablesToUpdate.list.fill(null),this.root=null,this.updateTick=0,this.structureDidChange=!0,this._onRenderContainers.length=0,this.renderGroupParent=null,this.disableCacheAsTexture()}get localTransform(){return this.root.localTransform}addRenderGroupChild(e){e.renderGroupParent&&e.renderGroupParent._removeRenderGroupChild(e),e.renderGroupParent=this,this.renderGroupChildren.push(e)}_removeRenderGroupChild(e){const t=this.renderGroupChildren.indexOf(e);t>-1&&this.renderGroupChildren.splice(t,1),e.renderGroupParent=null}addChild(e){if(this.structureDidChange=!0,e.parentRenderGroup=this,e.updateTick=-1,e.parent===this.root?e.relativeRenderGroupDepth=1:e.relativeRenderGroupDepth=e.parent.relativeRenderGroupDepth+1,e.didChange=!0,this.onChildUpdate(e),e.renderGroup){this.addRenderGroupChild(e.renderGroup);return}e._onRender&&this.addOnRender(e);const t=e.children;for(let s=0;s<t.length;s++)this.addChild(t[s])}removeChild(e){if(this.structureDidChange=!0,e._onRender&&(e.renderGroup||this.removeOnRender(e)),e.parentRenderGroup=null,e.renderGroup){this._removeRenderGroupChild(e.renderGroup);return}const t=e.children;for(let s=0;s<t.length;s++)this.removeChild(t[s])}removeChildren(e){for(let t=0;t<e.length;t++)this.removeChild(e[t])}onChildUpdate(e){let t=this.childrenToUpdate[e.relativeRenderGroupDepth];t||(t=this.childrenToUpdate[e.relativeRenderGroupDepth]={index:0,list:[]}),t.list[t.index++]=e}updateRenderable(e){e.globalDisplayStatus<7||(this.instructionSet.renderPipes[e.renderPipeId].updateRenderable(e),e.didViewUpdate=!1)}onChildViewUpdate(e){this.childrenRenderablesToUpdate.list[this.childrenRenderablesToUpdate.index++]=e}get isRenderable(){return this.root.localDisplayStatus===7&&this.worldAlpha>0}addOnRender(e){this._onRenderContainers.push(e)}removeOnRender(e){this._onRenderContainers.splice(this._onRenderContainers.indexOf(e),1)}runOnRender(e){for(let t=0;t<this._onRenderContainers.length;t++)this._onRenderContainers[t]._onRender(e)}destroy(){this.disableCacheAsTexture(),this.renderGroupParent=null,this.root=null,this.childrenRenderablesToUpdate=null,this.childrenToUpdate=null,this.renderGroupChildren=null,this._onRenderContainers=null,this.instructionSet=null}getChildren(e=[]){const t=this.root.children;for(let s=0;s<t.length;s++)this._getChildren(t[s],e);return e}_getChildren(e,t=[]){if(t.push(e),e.renderGroup)return t;const s=e.children;for(let r=0;r<s.length;r++)this._getChildren(s[r],t);return t}invalidateMatrices(){this._matrixDirty=7}get inverseWorldTransform(){return(this._matrixDirty&1)===0?this._inverseWorldTransform:(this._matrixDirty&=-2,this._inverseWorldTransform||(this._inverseWorldTransform=new H),this._inverseWorldTransform.copyFrom(this.worldTransform).invert())}get textureOffsetInverseTransform(){return(this._matrixDirty&2)===0?this._textureOffsetInverseTransform:(this._matrixDirty&=-3,this._textureOffsetInverseTransform||(this._textureOffsetInverseTransform=new H),this._textureOffsetInverseTransform.copyFrom(this.inverseWorldTransform).translate(-this._textureBounds.x,-this._textureBounds.y))}get inverseParentTextureTransform(){if((this._matrixDirty&4)===0)return this._inverseParentTextureTransform;this._matrixDirty&=-5;const e=this._parentCacheAsTextureRenderGroup;return e?(this._inverseParentTextureTransform||(this._inverseParentTextureTransform=new H),this._inverseParentTextureTransform.copyFrom(this.worldTransform).prepend(e.inverseWorldTransform).translate(-e._textureBounds.x,-e._textureBounds.y)):this.worldTransform}get cacheToLocalTransform(){return this.isCachedAsTexture?this.textureOffsetInverseTransform:this._parentCacheAsTextureRenderGroup?this._parentCacheAsTextureRenderGroup.textureOffsetInverseTransform:null}}function xp(i,e,t={}){for(const s in e)!t[s]&&e[s]!==void 0&&(i[s]=e[s])}const Qr=new je(null),Hi=new je(null),en=new je(null,1,1),Vi=new je(null),zi=1,tn=2,js=4;class Ve extends lt{constructor(e={}){var t,s;super(),this.uid=be("renderable"),this._updateFlags=15,this.renderGroup=null,this.parentRenderGroup=null,this.parentRenderGroupIndex=0,this.didChange=!1,this.didViewUpdate=!1,this.relativeRenderGroupDepth=0,this.children=[],this.parent=null,this.includeInBuild=!0,this.measurable=!0,this.isSimple=!0,this.parentRenderLayer=null,this.updateTick=-1,this.localTransform=new H,this.relativeGroupTransform=new H,this.groupTransform=this.relativeGroupTransform,this.destroyed=!1,this._position=new je(this,0,0),this._scale=en,this._pivot=Hi,this._origin=Vi,this._skew=Qr,this._cx=1,this._sx=0,this._cy=0,this._sy=1,this._rotation=0,this.localColor=16777215,this.localAlpha=1,this.groupAlpha=1,this.groupColor=16777215,this.groupColorAlpha=4294967295,this.localBlendMode="inherit",this.groupBlendMode="normal",this.localDisplayStatus=7,this.globalDisplayStatus=7,this._didContainerChangeTick=0,this._didViewChangeTick=0,this._didLocalTransformChangeId=-1,this.effects=[],xp(this,e,{children:!0,parent:!0,effects:!0}),(t=e.children)==null||t.forEach(r=>this.addChild(r)),(s=e.parent)==null||s.addChild(this)}static mixin(e){ee("8.8.0","Container.mixin is deprecated, please use extensions.mixin instead."),Q.mixin(Ve,e)}set _didChangeId(e){this._didViewChangeTick=e>>12&4095,this._didContainerChangeTick=e&4095}get _didChangeId(){return this._didContainerChangeTick&4095|(this._didViewChangeTick&4095)<<12}addChild(...e){if(this.allowChildren||ee(Be,"addChild: Only Containers will be allowed to add children in v8.0.0"),e.length>1){for(let r=0;r<e.length;r++)this.addChild(e[r]);return e[0]}const t=e[0],s=this.renderGroup||this.parentRenderGroup;return t.parent===this?(this.children.splice(this.children.indexOf(t),1),this.children.push(t),s&&(s.structureDidChange=!0),t):(t.parent&&t.parent.removeChild(t),this.children.push(t),this.sortableChildren&&(this.sortDirty=!0),t.parent=this,t.didChange=!0,t._updateFlags=15,s&&s.addChild(t),this.emit("childAdded",t,this,this.children.length-1),t.emit("added",this),this._didViewChangeTick++,t._zIndex!==0&&t.depthOfChildModified(),t)}removeChild(...e){if(e.length>1){for(let r=0;r<e.length;r++)this.removeChild(e[r]);return e[0]}const t=e[0],s=this.children.indexOf(t);return s>-1&&(this._didViewChangeTick++,this.children.splice(s,1),this.renderGroup?this.renderGroup.removeChild(t):this.parentRenderGroup&&this.parentRenderGroup.removeChild(t),t.parentRenderLayer&&t.parentRenderLayer.detach(t),t.parent=null,this.emit("childRemoved",t,this,s),t.emit("removed",this)),t}_onUpdate(e){e&&e===this._skew&&this._updateSkew(),this._didContainerChangeTick++,!this.didChange&&(this.didChange=!0,this.parentRenderGroup&&this.parentRenderGroup.onChildUpdate(this))}set isRenderGroup(e){!!this.renderGroup!==e&&(e?this.enableRenderGroup():this.disableRenderGroup())}get isRenderGroup(){return!!this.renderGroup}enableRenderGroup(){if(this.renderGroup)return;const e=this.parentRenderGroup;e==null||e.removeChild(this),this.renderGroup=Le.get(Jr,this),this.groupTransform=H.IDENTITY,e==null||e.addChild(this),this._updateIsSimple()}disableRenderGroup(){if(!this.renderGroup)return;const e=this.parentRenderGroup;e==null||e.removeChild(this),Le.return(this.renderGroup),this.renderGroup=null,this.groupTransform=this.relativeGroupTransform,e==null||e.addChild(this),this._updateIsSimple()}_updateIsSimple(){this.isSimple=!this.renderGroup&&this.effects.length===0}get worldTransform(){return this._worldTransform||(this._worldTransform=new H),this.renderGroup?this._worldTransform.copyFrom(this.renderGroup.worldTransform):this.parentRenderGroup&&this._worldTransform.appendFrom(this.relativeGroupTransform,this.parentRenderGroup.worldTransform),this._worldTransform}get x(){return this._position.x}set x(e){this._position.x=e}get y(){return this._position.y}set y(e){this._position.y=e}get position(){return this._position}set position(e){this._position.copyFrom(e)}get rotation(){return this._rotation}set rotation(e){this._rotation!==e&&(this._rotation=e,this._onUpdate(this._skew))}get angle(){return this.rotation*Gf}set angle(e){this.rotation=e*Ff}get pivot(){return this._pivot===Hi&&(this._pivot=new je(this,0,0)),this._pivot}set pivot(e){this._pivot===Hi&&(this._pivot=new je(this,0,0),this._origin!==Vi&&ie("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof e=="number"?this._pivot.set(e):this._pivot.copyFrom(e)}get skew(){return this._skew===Qr&&(this._skew=new je(this,0,0)),this._skew}set skew(e){this._skew===Qr&&(this._skew=new je(this,0,0)),this._skew.copyFrom(e)}get scale(){return this._scale===en&&(this._scale=new je(this,1,1)),this._scale}set scale(e){this._scale===en&&(this._scale=new je(this,0,0)),typeof e=="string"&&(e=parseFloat(e)),typeof e=="number"?this._scale.set(e):this._scale.copyFrom(e)}get origin(){return this._origin===Vi&&(this._origin=new je(this,0,0)),this._origin}set origin(e){this._origin===Vi&&(this._origin=new je(this,0,0),this._pivot!==Hi&&ie("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof e=="number"?this._origin.set(e):this._origin.copyFrom(e)}get width(){return Math.abs(this.scale.x*this.getLocalBounds().width)}set width(e){const t=this.getLocalBounds().width;this._setWidth(e,t)}get height(){return Math.abs(this.scale.y*this.getLocalBounds().height)}set height(e){const t=this.getLocalBounds().height;this._setHeight(e,t)}getSize(e){e||(e={});const t=this.getLocalBounds();return e.width=Math.abs(this.scale.x*t.width),e.height=Math.abs(this.scale.y*t.height),e}setSize(e,t){const s=this.getLocalBounds();typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,s.width),t!==void 0&&this._setHeight(t,s.height)}_updateSkew(){const e=this._rotation,t=this._skew;this._cx=Math.cos(e+t._y),this._sx=Math.sin(e+t._y),this._cy=-Math.sin(e-t._x),this._sy=Math.cos(e-t._x)}updateTransform(e){return this.position.set(typeof e.x=="number"?e.x:this.position.x,typeof e.y=="number"?e.y:this.position.y),this.scale.set(typeof e.scaleX=="number"?e.scaleX||1:this.scale.x,typeof e.scaleY=="number"?e.scaleY||1:this.scale.y),this.rotation=typeof e.rotation=="number"?e.rotation:this.rotation,this.skew.set(typeof e.skewX=="number"?e.skewX:this.skew.x,typeof e.skewY=="number"?e.skewY:this.skew.y),this.pivot.set(typeof e.pivotX=="number"?e.pivotX:this.pivot.x,typeof e.pivotY=="number"?e.pivotY:this.pivot.y),this.origin.set(typeof e.originX=="number"?e.originX:this.origin.x,typeof e.originY=="number"?e.originY:this.origin.y),this}setFromMatrix(e){e.decompose(this)}updateLocalTransform(){const e=this._didContainerChangeTick;if(this._didLocalTransformChangeId===e)return;this._didLocalTransformChangeId=e;const t=this.localTransform,s=this._scale,r=this._pivot,n=this._origin,o=this._position,a=s._x,l=s._y,c=r._x,h=r._y,u=-n._x,p=-n._y;t.a=this._cx*a,t.b=this._sx*a,t.c=this._cy*l,t.d=this._sy*l,t.tx=o._x-(c*t.a+h*t.c)+(u*t.a+p*t.c)-u,t.ty=o._y-(c*t.b+h*t.d)+(u*t.b+p*t.d)-p}set alpha(e){e!==this.localAlpha&&(this.localAlpha=e,this._updateFlags|=zi,this._onUpdate())}get alpha(){return this.localAlpha}set tint(e){const s=Pe.shared.setValue(e??16777215).toBgrNumber();s!==this.localColor&&(this.localColor=s,this._updateFlags|=zi,this._onUpdate())}get tint(){return _s(this.localColor)}set blendMode(e){this.localBlendMode!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=tn,this.localBlendMode=e,this._onUpdate())}get blendMode(){return this.localBlendMode}get visible(){return!!(this.localDisplayStatus&2)}set visible(e){const t=e?2:0;(this.localDisplayStatus&2)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=js,this.localDisplayStatus^=2,this._onUpdate(),this.emit("visibleChanged",e))}get culled(){return!(this.localDisplayStatus&4)}set culled(e){const t=e?0:4;(this.localDisplayStatus&4)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=js,this.localDisplayStatus^=4,this._onUpdate())}get renderable(){return!!(this.localDisplayStatus&1)}set renderable(e){const t=e?1:0;(this.localDisplayStatus&1)!==t&&(this._updateFlags|=js,this.localDisplayStatus^=1,this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._onUpdate())}get isRenderable(){return this.localDisplayStatus===7&&this.groupAlpha>0}destroy(e=!1){var r;if(this.destroyed)return;this.destroyed=!0;let t;if(this.children.length&&(t=this.removeChildren(0,this.children.length)),this.removeFromParent(),this.parent=null,this._maskEffect=null,this._filterEffect=null,this.effects=null,this._position=null,this._scale=null,this._pivot=null,this._origin=null,this._skew=null,this.emit("destroyed",this),this.removeAllListeners(),(typeof e=="boolean"?e:e==null?void 0:e.children)&&t)for(let n=0;n<t.length;++n)t[n].destroy(e);(r=this.renderGroup)==null||r.destroy(),this.renderGroup=null}}Q.mixin(Ve,np,up,yp,mp,pp,lp,cp,gp,tp,rp,dp,op);class Da extends Ve{constructor(e){super(e),this.canBundle=!0,this.allowChildren=!1,this._roundPixels=0,this._lastUsed=-1,this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this._bounds=new Ye(0,1,0,0),this._boundsDirty=!0,this.autoGarbageCollect=e.autoGarbageCollect??!0}get bounds(){return this._boundsDirty?(this.updateBounds(),this._boundsDirty=!1,this._bounds):this._bounds}get roundPixels(){return!!this._roundPixels}set roundPixels(e){this._roundPixels=e?1:0}containsPoint(e){const t=this.bounds,{x:s,y:r}=e;return s>=t.minX&&s<=t.maxX&&r>=t.minY&&r<=t.maxY}onViewUpdate(){if(this._didViewChangeTick++,this._boundsDirty=!0,this.didViewUpdate)return;this.didViewUpdate=!0;const e=this.renderGroup||this.parentRenderGroup;e&&e.onChildViewUpdate(this)}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null),this.onViewUpdate()}destroy(e){this.unload(),super.destroy(e),this._bounds=null}collectRenderablesSimple(e,t,s){const{renderPipes:r}=t;r.blendMode.pushBlendMode(this,this.groupBlendMode,e);const o=r[this.renderPipeId];o!=null&&o.addRenderable&&o.addRenderable(this,e),this.didViewUpdate=!1;const a=this.children,l=a.length;for(let c=0;c<l;c++)a[c].collectRenderables(e,t,s);r.blendMode.popBlendMode(e)}}class Dt extends Da{constructor(e=j.EMPTY){e instanceof j&&(e={texture:e});const{texture:t=j.EMPTY,anchor:s,roundPixels:r,width:n,height:o,...a}=e;super({label:"Sprite",...a}),this.renderPipeId="sprite",this.batched=!0,this._visualBounds={minX:0,maxX:1,minY:0,maxY:0},this._anchor=new je({_onUpdate:()=>{this.onViewUpdate()}}),s?this.anchor=s:t.defaultAnchor&&(this.anchor=t.defaultAnchor),this.texture=t,this.allowChildren=!1,this.roundPixels=r??!1,n!==void 0&&(this.width=n),o!==void 0&&(this.height=o)}static from(e,t=!1){return e instanceof j?new Dt(e):new Dt(j.from(e,t))}set texture(e){e||(e=j.EMPTY);const t=this._texture;t!==e&&(t&&t.dynamic&&t.off("update",this.onViewUpdate,this),e.dynamic&&e.on("update",this.onViewUpdate,this),this._texture=e,this._width&&this._setWidth(this._width,this._texture.orig.width),this._height&&this._setHeight(this._height,this._texture.orig.height),this.onViewUpdate())}get texture(){return this._texture}get visualBounds(){return $f(this._visualBounds,this._anchor,this._texture),this._visualBounds}get sourceBounds(){return ee("8.6.1","Sprite.sourceBounds is deprecated, use visualBounds instead."),this.visualBounds}updateBounds(){const e=this._anchor,t=this._texture,s=this._bounds,{width:r,height:n}=t.orig;s.minX=-e._x*r,s.maxX=s.minX+r,s.minY=-e._y*n,s.maxY=s.minY+n}destroy(e=!1){if(super.destroy(e),typeof e=="boolean"?e:e==null?void 0:e.texture){const s=typeof e=="boolean"?e:e==null?void 0:e.textureSource;this._texture.destroy(s)}this._texture=null,this._visualBounds=null,this._bounds=null,this._anchor=null}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(e){this._setWidth(e,this._texture.orig.width),this._width=e}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(e){this._setHeight(e,this._texture.orig.height),this._height=e}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this._texture.orig.width,e.height=Math.abs(this.scale.y)*this._texture.orig.height,e}setSize(e,t){typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,this._texture.orig.width),t!==void 0&&this._setHeight(t,this._texture.orig.height)}}const Cp=new Ye;function Na(i,e,t){const s=Cp;i.measurable=!0,Yr(i,t,s),e.addBoundsMask(s),i.measurable=!1}function Ua(i,e,t){const s=Tt.get();i.measurable=!0;const r=qe.get().identity(),n=Ga(i,t,r);Kr(i,s,n),i.measurable=!1,e.addBoundsMask(s),qe.return(r),Tt.return(s)}function Ga(i,e,t){return i?(i!==e&&(Ga(i.parent,e,t),i.updateLocalTransform(),t.append(i.localTransform)),t):(ie("Mask bounds, renderable is not inside the root container"),t)}class Fa{constructor(e){this.priority=0,this.inverse=!1,this.pipe="alphaMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e,this.renderMaskToTexture=!(e instanceof Dt),this.mask.renderable=this.renderMaskToTexture,this.mask.includeInBuild=!this.renderMaskToTexture,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask=null)}addBounds(e,t){this.inverse||Na(this.mask,e,t)}addLocalBounds(e,t){Ua(this.mask,e,t)}containsPoint(e,t){const s=this.mask;return t(s,e)}destroy(){this.reset()}static test(e){return e instanceof Dt}}Fa.extension=A.MaskEffect;class La{constructor(e){this.priority=0,this.pipe="colorMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e}destroy(){}static test(e){return typeof e=="number"}}La.extension=A.MaskEffect;class Wa{constructor(e){this.priority=0,this.pipe="stencilMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e,this.mask.includeInBuild=!1,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask.includeInBuild=!0,this.mask=null)}addBounds(e,t){Na(this.mask,e,t)}addLocalBounds(e,t){Ua(this.mask,e,t)}containsPoint(e,t){const s=this.mask;return t(s,e)}destroy(){this.reset()}static test(e){return e instanceof Ve}}Wa.extension=A.MaskEffect;let Ha={createCanvas:(i,e)=>{const t=document.createElement("canvas");return t.width=i,t.height=e,t},createImage:()=>new Image,getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(i,e)=>fetch(i,e),parseXML:i=>new DOMParser().parseFromString(i,"text/xml")};const pe={get(){return Ha},set(i){Ha=i}};class mt extends De{constructor(e){e.resource||(e.resource=pe.get().createCanvas()),e.width||(e.width=e.resource.width,e.autoDensity||(e.width/=e.resolution)),e.height||(e.height=e.resource.height,e.autoDensity||(e.height/=e.resolution)),super(e),this.uploadMethodId="image",this.autoDensity=e.autoDensity,this.resizeCanvas(),this.transparent=!!e.transparent}resizeCanvas(){this.autoDensity&&"style"in this.resource&&(this.resource.style.width=`${this.width}px`,this.resource.style.height=`${this.height}px`),(this.resource.width!==this.pixelWidth||this.resource.height!==this.pixelHeight)&&(this.resource.width=this.pixelWidth,this.resource.height=this.pixelHeight)}resize(e=this.width,t=this.height,s=this._resolution){const r=super.resize(e,t,s);return r&&this.resizeCanvas(),r}static test(e){return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement||globalThis.OffscreenCanvas&&e instanceof OffscreenCanvas}get context2D(){return this._context2D||(this._context2D=this.resource.getContext("2d"))}}mt.extension=A.TextureSource;class $i extends De{constructor(e){super(e),this.uploadMethodId="image",this.autoGarbageCollect=!0}static test(e){return globalThis.HTMLImageElement&&e instanceof HTMLImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||globalThis.VideoFrame&&e instanceof VideoFrame}}$i.extension=A.TextureSource;var ys=(i=>(i[i.INTERACTION=50]="INTERACTION",i[i.HIGH=25]="HIGH",i[i.NORMAL=0]="NORMAL",i[i.LOW=-25]="LOW",i[i.UTILITY=-50]="UTILITY",i))(ys||{});class sn{constructor(e,t=null,s=0,r=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=e,this._context=t,this.priority=s,this._once=r}match(e,t=null){return this._fn===e&&this._context===t}emit(e){this._fn&&(this._context?this._fn.call(this._context,e):this._fn(e));const t=this.next;return this._once&&this.destroy(!0),this._destroyed&&(this.next=null),t}connect(e){this.previous=e,e.next&&(e.next.previous=this),this.next=e.next,e.next=this}destroy(e=!1){this._destroyed=!0,this._fn=null,this._context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);const t=this.next;return this.next=e?null:t,this.previous=null,t}}const Va=class nt{constructor(){this.autoStart=!1,this.deltaTime=1,this.lastTime=-1,this.speed=1,this.started=!1,this._requestId=null,this._maxElapsedMS=100,this._minElapsedMS=0,this._protected=!1,this._lastFrame=-1,this._head=new sn(null,null,1/0),this.deltaMS=1/nt.targetFPMS,this.elapsedMS=1/nt.targetFPMS,this._tick=e=>{this._requestId=null,this.started&&(this.update(e),this.started&&this._requestId===null&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){this._requestId===null&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){this._requestId!==null&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(e,t,s=ys.NORMAL){return this._addListener(new sn(e,t,s))}addOnce(e,t,s=ys.NORMAL){return this._addListener(new sn(e,t,s,!0))}_addListener(e){let t=this._head.next,s=this._head;if(!t)e.connect(s);else{for(;t;){if(e.priority>t.priority){e.connect(s);break}s=t,t=t.next}e.previous||e.connect(s)}return this._startIfPossible(),this}remove(e,t){let s=this._head.next;for(;s;)s.match(e,t)?s=s.destroy():s=s.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let e=0,t=this._head;for(;t=t.next;)e++;return e}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let e=this._head.next;for(;e;)e=e.destroy(!0);this._head.destroy(),this._head=null}}update(e=performance.now()){let t;if(e>this.lastTime){if(t=this.elapsedMS=e-this.lastTime,t>this._maxElapsedMS&&(t=this._maxElapsedMS),t*=this.speed,this._minElapsedMS){const n=e-this._lastFrame|0;if(n<this._minElapsedMS)return;this._lastFrame=e-n%this._minElapsedMS}this.deltaMS=t,this.deltaTime=this.deltaMS*nt.targetFPMS;const s=this._head;let r=s.next;for(;r;)r=r.emit(this);s.next||this._cancelIfNeeded()}else this.deltaTime=this.deltaMS=this.elapsedMS=0;this.lastTime=e}get FPS(){return 1e3/this.elapsedMS}get minFPS(){return 1e3/this._maxElapsedMS}set minFPS(e){const t=Math.min(Math.max(0,e)/1e3,nt.targetFPMS);this._maxElapsedMS=1/t,this._minElapsedMS&&e>this.maxFPS&&(this.maxFPS=e)}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(e){e===0?this._minElapsedMS=0:(e<this.minFPS&&(this.minFPS=e),this._minElapsedMS=1/(e/1e3))}static get shared(){if(!nt._shared){const e=nt._shared=new nt;e.autoStart=!0,e._protected=!0}return nt._shared}static get system(){if(!nt._system){const e=nt._system=new nt;e.autoStart=!0,e._protected=!0}return nt._system}};Va.targetFPMS=.06;let at=Va,rn;async function Ep(){return rn??(rn=(async()=>{var o;const e=pe.get().createCanvas(1,1).getContext("webgl");if(!e)return"premultiply-alpha-on-upload";const t=await new Promise(a=>{const l=document.createElement("video");l.onloadeddata=()=>a(l),l.onerror=()=>a(null),l.autoplay=!1,l.crossOrigin="anonymous",l.preload="auto",l.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",l.load()});if(!t)return"premultiply-alpha-on-upload";const s=e.createTexture();e.bindTexture(e.TEXTURE_2D,s);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.NONE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t);const n=new Uint8Array(4);return e.readPixels(0,0,1,1,e.RGBA,e.UNSIGNED_BYTE,n),e.deleteFramebuffer(r),e.deleteTexture(s),(o=e.getExtension("WEBGL_lose_context"))==null||o.loseContext(),n[0]<=n[3]?"premultiplied-alpha":"premultiply-alpha-on-upload"})()),rn}const ji=class cf extends De{constructor(e){super(e),this.isReady=!1,this.uploadMethodId="video",e={...cf.defaultOptions,...e},this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=e.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=e.autoPlay!==!1,this.alphaMode=e.alphaMode??"premultiply-alpha-on-upload",this._videoFrameRequestCallback=this._videoFrameRequestCallback.bind(this),this._videoFrameRequestCallbackHandle=null,this._load=null,this._resolve=null,this._reject=null,this._onCanPlay=this._onCanPlay.bind(this),this._onCanPlayThrough=this._onCanPlayThrough.bind(this),this._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),e.autoLoad!==!1&&this.load()}updateFrame(){if(!this.destroyed){if(this._updateFPS){const e=at.shared.elapsedMS*this.resource.playbackRate;this._msToNextUpdate=Math.floor(this._msToNextUpdate-e)}(!this._updateFPS||this._msToNextUpdate<=0)&&(this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0),this.isValid&&this.update()}}_videoFrameRequestCallback(){this.updateFrame(),this.destroyed?this._videoFrameRequestCallbackHandle=null:this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback)}get isValid(){return!!this.resource.videoWidth&&!!this.resource.videoHeight}async load(){if(this._load)return this._load;const e=this.resource,t=this.options;return(e.readyState===e.HAVE_ENOUGH_DATA||e.readyState===e.HAVE_FUTURE_DATA)&&e.width&&e.height&&(e.complete=!0),e.addEventListener("play",this._onPlayStart),e.addEventListener("pause",this._onPlayStop),e.addEventListener("seeked",this._onSeeked),this._isSourceReady()?this._mediaReady():(t.preload||e.addEventListener("canplay",this._onCanPlay),e.addEventListener("canplaythrough",this._onCanPlayThrough),e.addEventListener("error",this._onError,!0)),this.alphaMode=await Ep(),this._load=new Promise((s,r)=>{this.isValid?s(this):(this._resolve=s,this._reject=r,t.preloadTimeoutMs!==void 0&&(this._preloadTimeout=setTimeout(()=>{this._onError(new ErrorEvent(`Preload exceeded timeout of ${t.preloadTimeoutMs}ms`))})),e.load())}),this._load}_onError(e){this.resource.removeEventListener("error",this._onError,!0),this.emit("error",e),this._reject&&(this._reject(e),this._reject=null,this._resolve=null)}_isSourcePlaying(){const e=this.resource;return!e.paused&&!e.ended}_isSourceReady(){return this.resource.readyState>2}_onPlayStart(){this.isValid||this._mediaReady(),this._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0)}_onCanPlay(){this.resource.removeEventListener("canplay",this._onCanPlay),this._mediaReady()}_onCanPlayThrough(){this.resource.removeEventListener("canplaythrough",this._onCanPlay),this._preloadTimeout&&(clearTimeout(this._preloadTimeout),this._preloadTimeout=void 0),this._mediaReady()}_mediaReady(){const e=this.resource;this.isValid&&(this.isReady=!0,this.resize(e.videoWidth,e.videoHeight)),this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0,this._resolve&&(this._resolve(this),this._resolve=null,this._reject=null),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.resource.play()}destroy(){this._configureAutoUpdate();const e=this.resource;e&&(e.removeEventListener("play",this._onPlayStart),e.removeEventListener("pause",this._onPlayStop),e.removeEventListener("seeked",this._onSeeked),e.removeEventListener("canplay",this._onCanPlay),e.removeEventListener("canplaythrough",this._onCanPlayThrough),e.removeEventListener("error",this._onError,!0),e.pause(),e.src="",e.load()),super.destroy()}get autoUpdate(){return this._autoUpdate}set autoUpdate(e){e!==this._autoUpdate&&(this._autoUpdate=e,this._configureAutoUpdate())}get updateFPS(){return this._updateFPS}set updateFPS(e){e!==this._updateFPS&&(this._updateFPS=e,this._configureAutoUpdate())}_configureAutoUpdate(){this._autoUpdate&&this._isSourcePlaying()?!this._updateFPS&&this.resource.requestVideoFrameCallback?(this._isConnectedToTicker&&(at.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0),this._videoFrameRequestCallbackHandle===null&&(this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback))):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker||(at.shared.add(this.updateFrame,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(at.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(e){return globalThis.HTMLVideoElement&&e instanceof HTMLVideoElement}};ji.extension=A.TextureSource,ji.defaultOptions={...De.defaultOptions,autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1},ji.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let Sp=ji;const bs=(i,e,t=!1)=>(Array.isArray(i)||(i=[i]),e?i.map(s=>typeof s=="string"||t?e(s):s):i);class Tp{constructor(){this._parsers=[],this._cache=new Map,this._cacheMap=new Map}reset(){this._cacheMap.clear(),this._cache.clear()}has(e){return this._cache.has(e)}get(e){const t=this._cache.get(e);return t||ie(`[Assets] Asset id ${e} was not found in the Cache`),t}set(e,t){const s=bs(e);let r;for(let l=0;l<this.parsers.length;l++){const c=this.parsers[l];if(c.test(t)){r=c.getCacheableAssets(s,t);break}}const n=new Map(Object.entries(r||{}));r||s.forEach(l=>{n.set(l,t)});const o=[...n.keys()],a={cacheKeys:o,keys:s};s.forEach(l=>{this._cacheMap.set(l,a)}),o.forEach(l=>{const c=r?r[l]:t;this._cache.has(l)&&this._cache.get(l)!==c&&ie("[Cache] already has key:",l),this._cache.set(l,n.get(l))})}remove(e){if(!this._cacheMap.has(e)){ie(`[Assets] Asset id ${e} was not found in the Cache`);return}const t=this._cacheMap.get(e);t.cacheKeys.forEach(r=>{this._cache.delete(r)}),t.keys.forEach(r=>{this._cacheMap.delete(r)})}get parsers(){return this._parsers}}const vs=new Tp,nn=[];Q.handleByList(A.TextureSource,nn);function za(i={}){const e=i&&i.resource,t=e?i.resource:i,s=e?i:{resource:i};for(let r=0;r<nn.length;r++){const n=nn[r];if(n.test(t))return new n(s)}throw new Error(`Could not find a source type for resource: ${s.resource}`)}function Ap(i={},e=!1){const t=i&&i.resource,s=t?i.resource:i,r=t?i:{resource:i};if(!e&&vs.has(s))return vs.get(s);const n=new j({source:za(r)});return n.on("destroy",()=>{vs.has(s)&&vs.remove(s)}),e||vs.set(s,n),n}function wp(i,e=!1){return typeof i=="string"?vs.get(i):i instanceof De?new j({source:i}):Ap(i,e)}j.from=wp,De.from=za,Q.add(Fa,La,Wa,Sp,$i,mt,Lr);var $a=(i=>(i[i.Low=0]="Low",i[i.Normal=1]="Normal",i[i.High=2]="High",i))($a||{});function ct(i){if(typeof i!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(i)}`)}function Xs(i){return i.split("?")[0].split("#")[0]}function Ip(i){return i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Rp(i,e,t){return i.replace(new RegExp(Ip(e),"g"),t)}function Mp(i,e){let t="",s=0,r=-1,n=0,o=-1;for(let a=0;a<=i.length;++a){if(a<i.length)o=i.charCodeAt(a);else{if(o===47)break;o=47}if(o===47){if(!(r===a-1||n===1))if(r!==a-1&&n===2){if(t.length<2||s!==2||t.charCodeAt(t.length-1)!==46||t.charCodeAt(t.length-2)!==46){if(t.length>2){const l=t.lastIndexOf("/");if(l!==t.length-1){l===-1?(t="",s=0):(t=t.slice(0,l),s=t.length-1-t.lastIndexOf("/")),r=a,n=0;continue}}else if(t.length===2||t.length===1){t="",s=0,r=a,n=0;continue}}}else t.length>0?t+=`/${i.slice(r+1,a)}`:t=i.slice(r+1,a),s=a-r-1;r=a,n=0}else o===46&&n!==-1?++n:n=-1}return t}const Ys={toPosix(i){return Rp(i,"\\","/")},isUrl(i){return/^https?:/.test(this.toPosix(i))},isDataUrl(i){return/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(i)},isBlobUrl(i){return i.startsWith("blob:")},hasProtocol(i){return/^[^/:]+:/.test(this.toPosix(i))},getProtocol(i){ct(i),i=this.toPosix(i);const e=/^file:\/\/\//.exec(i);if(e)return e[0];const t=/^[^/:]+:\/{0,2}/.exec(i);return t?t[0]:""},toAbsolute(i,e,t){if(ct(i),this.isDataUrl(i)||this.isBlobUrl(i))return i;const s=Xs(this.toPosix(e??pe.get().getBaseUrl())),r=Xs(this.toPosix(t??this.rootname(s)));return i=this.toPosix(i),i.startsWith("/")?Ys.join(r,i.slice(1)):this.isAbsolute(i)?i:this.join(s,i)},normalize(i){if(ct(i),i.length===0)return".";if(this.isDataUrl(i)||this.isBlobUrl(i))return i;i=this.toPosix(i);let e="";const t=i.startsWith("/");this.hasProtocol(i)&&(e=this.rootname(i),i=i.slice(e.length));const s=i.endsWith("/");return i=Mp(i),i.length>0&&s&&(i+="/"),t?`/${i}`:e+i},isAbsolute(i){return ct(i),i=this.toPosix(i),this.hasProtocol(i)?!0:i.startsWith("/")},join(...i){if(i.length===0)return".";let e;for(let t=0;t<i.length;++t){const s=i[t];if(ct(s),s.length>0)if(e===void 0)e=s;else{const r=i[t-1]??"";this.joinExtensions.includes(this.extname(r).toLowerCase())?e+=`/../${s}`:e+=`/${s}`}}return e===void 0?".":this.normalize(e)},dirname(i){if(ct(i),i.length===0)return".";i=this.toPosix(i);let e=i.charCodeAt(0);const t=e===47;let s=-1,r=!0;const n=this.getProtocol(i),o=i;i=i.slice(n.length);for(let a=i.length-1;a>=1;--a)if(e=i.charCodeAt(a),e===47){if(!r){s=a;break}}else r=!1;return s===-1?t?"/":this.isUrl(o)?n+i:n:t&&s===1?"//":n+i.slice(0,s)},rootname(i){ct(i),i=this.toPosix(i);let e="";if(i.startsWith("/")?e="/":e=this.getProtocol(i),this.isUrl(i)){const t=i.indexOf("/",e.length);t!==-1?e=i.slice(0,t):e=i,e.endsWith("/")||(e+="/")}return e},basename(i,e){ct(i),e&&ct(e),i=Xs(this.toPosix(i));let t=0,s=-1,r=!0,n;if(e!==void 0&&e.length>0&&e.length<=i.length){if(e.length===i.length&&e===i)return"";let o=e.length-1,a=-1;for(n=i.length-1;n>=0;--n){const l=i.charCodeAt(n);if(l===47){if(!r){t=n+1;break}}else a===-1&&(r=!1,a=n+1),o>=0&&(l===e.charCodeAt(o)?--o===-1&&(s=n):(o=-1,s=a))}return t===s?s=a:s===-1&&(s=i.length),i.slice(t,s)}for(n=i.length-1;n>=0;--n)if(i.charCodeAt(n)===47){if(!r){t=n+1;break}}else s===-1&&(r=!1,s=n+1);return s===-1?"":i.slice(t,s)},extname(i){ct(i),i=Xs(this.toPosix(i));let e=-1,t=0,s=-1,r=!0,n=0;for(let o=i.length-1;o>=0;--o){const a=i.charCodeAt(o);if(a===47){if(!r){t=o+1;break}continue}s===-1&&(r=!1,s=o+1),a===46?e===-1?e=o:n!==1&&(n=1):e!==-1&&(n=-1)}return e===-1||s===-1||n===0||n===1&&e===s-1&&e===t+1?"":i.slice(e,s)},parse(i){ct(i);const e={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return e;i=Xs(this.toPosix(i));let t=i.charCodeAt(0);const s=this.isAbsolute(i);let r;e.root=this.rootname(i),s||this.hasProtocol(i)?r=1:r=0;let n=-1,o=0,a=-1,l=!0,c=i.length-1,h=0;for(;c>=r;--c){if(t=i.charCodeAt(c),t===47){if(!l){o=c+1;break}continue}a===-1&&(l=!1,a=c+1),t===46?n===-1?n=c:h!==1&&(h=1):n!==-1&&(h=-1)}return n===-1||a===-1||h===0||h===1&&n===a-1&&n===o+1?a!==-1&&(o===0&&s?e.base=e.name=i.slice(1,a):e.base=e.name=i.slice(o,a)):(o===0&&s?(e.name=i.slice(1,n),e.base=i.slice(1,a)):(e.name=i.slice(o,n),e.base=i.slice(o,a)),e.ext=i.slice(n,a)),e.dir=this.dirname(i),e},sep:"/",delimiter:":",joinExtensions:[".html"]};function ja(i,e,t,s,r){const n=e[t];for(let o=0;o<n.length;o++){const a=n[o];t<e.length-1?ja(i.replace(s[t],a),e,t+1,s,r):r.push(i.replace(s[t],a))}}function Pp(i){const e=/\{(.*?)\}/g,t=i.match(e),s=[];if(t){const r=[];t.forEach(n=>{const o=n.substring(1,n.length-1).split(",");r.push(o)}),ja(i,r,0,t,s)}else s.push(i);return s}const Xa=i=>!Array.isArray(i);class Ya{constructor(){this._defaultBundleIdentifierOptions={connector:"-",createBundleAssetId:(e,t)=>`${e}${this._bundleIdConnector}${t}`,extractAssetIdFromBundle:(e,t)=>t.replace(`${e}${this._bundleIdConnector}`,"")},this._bundleIdConnector=this._defaultBundleIdentifierOptions.connector,this._createBundleAssetId=this._defaultBundleIdentifierOptions.createBundleAssetId,this._extractAssetIdFromBundle=this._defaultBundleIdentifierOptions.extractAssetIdFromBundle,this._assetMap={},this._preferredOrder=[],this._parsers=[],this._resolverHash={},this._bundles={}}setBundleIdentifier(e){if(this._bundleIdConnector=e.connector??this._bundleIdConnector,this._createBundleAssetId=e.createBundleAssetId??this._createBundleAssetId,this._extractAssetIdFromBundle=e.extractAssetIdFromBundle??this._extractAssetIdFromBundle,this._extractAssetIdFromBundle("foo",this._createBundleAssetId("foo","bar"))!=="bar")throw new Error("[Resolver] GenerateBundleAssetId are not working correctly")}prefer(...e){e.forEach(t=>{this._preferredOrder.push(t),t.priority||(t.priority=Object.keys(t.params))}),this._resolverHash={}}set basePath(e){this._basePath=e}get basePath(){return this._basePath}set rootPath(e){this._rootPath=e}get rootPath(){return this._rootPath}get parsers(){return this._parsers}reset(){this.setBundleIdentifier(this._defaultBundleIdentifierOptions),this._assetMap={},this._preferredOrder=[],this._resolverHash={},this._rootPath=null,this._basePath=null,this._manifest=null,this._bundles={},this._defaultSearchParams=null}setDefaultSearchParams(e){if(typeof e=="string")this._defaultSearchParams=e;else{const t=e;this._defaultSearchParams=Object.keys(t).map(s=>`${encodeURIComponent(s)}=${encodeURIComponent(t[s])}`).join("&")}}getAlias(e){const{alias:t,src:s}=e;return bs(t||s,n=>typeof n=="string"?n:Array.isArray(n)?n.map(o=>(o==null?void 0:o.src)??o):n!=null&&n.src?n.src:n,!0)}removeAlias(e,t){this._assetMap[e]&&(t&&t!==this._resolverHash[e]||(delete this._resolverHash[e],delete this._assetMap[e]))}addManifest(e){this._manifest&&ie("[Resolver] Manifest already exists, this will be overwritten"),this._manifest=e,e.bundles.forEach(t=>{this.addBundle(t.name,t.assets)})}addBundle(e,t){const s=[];let r=t;Array.isArray(t)||(r=Object.entries(t).map(([n,o])=>typeof o=="string"||Array.isArray(o)?{alias:n,src:o}:{alias:n,...o})),r.forEach(n=>{const o=n.src,a=n.alias;let l;if(typeof a=="string"){const c=this._createBundleAssetId(e,a);s.push(c),l=[a,c]}else{const c=a.map(h=>this._createBundleAssetId(e,h));s.push(...c),l=[...a,...c]}this.add({...n,alias:l,src:o})}),this._bundles[e]=s}add(e){const t=[];Array.isArray(e)?t.push(...e):t.push(e);let s;s=n=>{this.hasKey(n)&&ie(`[Resolver] already has key: ${n} overwriting`)},bs(t).forEach(n=>{const{src:o}=n;let{data:a,format:l,loadParser:c,parser:h}=n;const u=bs(o).map(_=>typeof _=="string"?Pp(_):Array.isArray(_)?_:[_]),p=this.getAlias(n);Array.isArray(p)?p.forEach(s):s(p);const d=[],g=_=>{const b=this._parsers.find(v=>v.test(_));return{src:_,...b==null?void 0:b.parse(_)}};u.forEach(_=>{_.forEach(b=>{let v={};if(typeof b!="object"?v=g(b):(a=b.data??a,l=b.format??l,(b.loadParser||b.parser)&&(c=b.loadParser??c,h=b.parser??h),v={...g(b.src),...b}),!p)throw new Error(`[Resolver] alias is undefined for this asset: ${v.src}`);v=this._buildResolvedAsset(v,{aliases:p,data:a,format:l,loadParser:c,parser:h,progressSize:n.progressSize}),d.push(v)})}),p.forEach(_=>{this._assetMap[_]=d})})}resolveBundle(e){const t=Xa(e);e=bs(e);const s={};return e.forEach(r=>{const n=this._bundles[r];if(n){const o=this.resolve(n),a={};for(const l in o){const c=o[l];a[this._extractAssetIdFromBundle(r,l)]=c}s[r]=a}}),t?s[e[0]]:s}resolveUrl(e){const t=this.resolve(e);if(typeof e!="string"){const s={};for(const r in t)s[r]=t[r].src;return s}return t.src}resolve(e){const t=Xa(e);e=bs(e);const s={};return e.forEach(r=>{if(!this._resolverHash[r])if(this._assetMap[r]){let n=this._assetMap[r];const o=this._getPreferredOrder(n);o==null||o.priority.forEach(a=>{o.params[a].forEach(l=>{const c=n.filter(h=>h[a]?h[a]===l:!1);c.length&&(n=c)})}),this._resolverHash[r]=n[0]}else this._resolverHash[r]=this._buildResolvedAsset({alias:[r],src:r},{});s[r]=this._resolverHash[r]}),t?s[e[0]]:s}hasKey(e){return!!this._assetMap[e]}hasBundle(e){return!!this._bundles[e]}_getPreferredOrder(e){for(let t=0;t<e.length;t++){const s=e[t],r=this._preferredOrder.find(n=>n.params.format.includes(s.format));if(r)return r}return this._preferredOrder[0]}_appendDefaultSearchParams(e){if(!this._defaultSearchParams)return e;const t=/\?/.test(e)?"&":"?";return`${e}${t}${this._defaultSearchParams}`}_buildResolvedAsset(e,t){const{aliases:s,data:r,loadParser:n,parser:o,format:a,progressSize:l}=t;return(this._basePath||this._rootPath)&&(e.src=Ys.toAbsolute(e.src,this._basePath,this._rootPath)),e.alias=s??e.alias??[e.src],e.src=this._appendDefaultSearchParams(e.src),e.data={...r||{},...e.data},e.loadParser=n??e.loadParser,e.parser=o??e.parser,e.format=a??e.format??kp(e.src),l!==void 0&&(e.progressSize=l),e}}Ya.RETINA_PREFIX=/@([0-9\.]+)x/;function kp(i){return i.split(".").pop().split("?").shift().split("#").shift()}const qa=(i,e)=>{const t=e.split("?")[1];return t&&(i+=`?${t}`),i},Ka=class Bi{constructor(e,t){this.linkedSheets=[];let s=e;(e==null?void 0:e.source)instanceof De&&(s={texture:e,data:t});const{texture:r,data:n,cachePrefix:o=""}=s;this.cachePrefix=o,this._texture=r instanceof j?r:null,this.textureSource=r.source,this.textures={},this.animations={},this.data=n;const a=parseFloat(n.meta.scale);a?(this.resolution=a,r.source.resolution=this.resolution):this.resolution=r.source._resolution,this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}parse(){return new Promise(e=>{this._callback=e,this._batchIndex=0,this._frameKeys.length<=Bi.BATCH_SIZE?(this._processFrames(0),this._processAnimations(),this._parseComplete()):this._nextBatch()})}parseSync(){return this._processFrames(0,!0),this._processAnimations(),this.textures}_processFrames(e,t=!1){let s=e;const r=t?1/0:Bi.BATCH_SIZE;for(;s-e<r&&s<this._frameKeys.length;){const n=this._frameKeys[s],o=this._frames[n],a=o.frame;if(a){let l=null,c=null;const h=o.trimmed!==!1&&o.sourceSize?o.sourceSize:o.frame,u=new Ce(0,0,Math.floor(h.w)/this.resolution,Math.floor(h.h)/this.resolution);o.rotated?l=new Ce(Math.floor(a.x)/this.resolution,Math.floor(a.y)/this.resolution,Math.floor(a.h)/this.resolution,Math.floor(a.w)/this.resolution):l=new Ce(Math.floor(a.x)/this.resolution,Math.floor(a.y)/this.resolution,Math.floor(a.w)/this.resolution,Math.floor(a.h)/this.resolution),o.trimmed!==!1&&o.spriteSourceSize&&(c=new Ce(Math.floor(o.spriteSourceSize.x)/this.resolution,Math.floor(o.spriteSourceSize.y)/this.resolution,Math.floor(a.w)/this.resolution,Math.floor(a.h)/this.resolution)),this.textures[n]=new j({source:this.textureSource,frame:l,orig:u,trim:c,rotate:o.rotated?2:0,defaultAnchor:o.anchor,defaultBorders:o.borders,label:n.toString()})}s++}}_processAnimations(){const e=this.data.animations||{};for(const t in e){this.animations[t]=[];for(let s=0;s<e[t].length;s++){const r=e[t][s];this.animations[t].push(this.textures[r])}}}_parseComplete(){const e=this._callback;this._callback=null,this._batchIndex=0,e.call(this,this.textures)}_nextBatch(){this._processFrames(this._batchIndex*Bi.BATCH_SIZE),this._batchIndex++,setTimeout(()=>{this._batchIndex*Bi.BATCH_SIZE<this._frameKeys.length?this._nextBatch():(this._processAnimations(),this._parseComplete())},0)}destroy(e=!1){var t;for(const s in this.textures)this.textures[s].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,e&&((t=this._texture)==null||t.destroy(),this.textureSource.destroy()),this._texture=null,this.textureSource=null,this.linkedSheets=[]}};Ka.BATCH_SIZE=1e3;let Za=Ka;const Op=["jpg","png","jpeg","avif","webp","basis","etc2","bc7","bc6h","bc5","bc4","bc3","bc2","bc1","eac","astc"];function Ja(i,e,t){const s={};if(i.forEach(r=>{s[r]=e}),Object.keys(e.textures).forEach(r=>{s[`${e.cachePrefix}${r}`]=e.textures[r]}),!t){const r=Ys.dirname(i[0]);e.linkedSheets.forEach((n,o)=>{const a=Ja([`${r}/${e.data.meta.related_multi_packs[o]}`],n,!0);Object.assign(s,a)})}return s}const Bp={extension:A.Asset,cache:{test:i=>i instanceof Za,getCacheableAssets:(i,e)=>Ja(i,e,!1)},resolver:{extension:{type:A.ResolveParser,name:"resolveSpritesheet"},test:i=>{const t=i.split("?")[0].split("."),s=t.pop(),r=t.pop();return s==="json"&&Op.includes(r)},parse:i=>{var t;const e=i.split(".");return{resolution:parseFloat(((t=Ya.RETINA_PREFIX.exec(i))==null?void 0:t[1])??"1"),format:e[e.length-2],src:i}}},loader:{name:"spritesheetLoader",id:"spritesheet",extension:{type:A.LoadParser,priority:$a.Normal,name:"spritesheetLoader"},async testParse(i,e){return Ys.extname(e.src).toLowerCase()===".json"&&!!i.frames},async parse(i,e,t){var u,p;const{texture:s,imageFilename:r,textureOptions:n,cachePrefix:o}=(e==null?void 0:e.data)??{};let a=Ys.dirname(e.src);a&&a.lastIndexOf("/")!==a.length-1&&(a+="/");let l;if(s instanceof j)l=s;else{const d=qa(a+(r??i.meta.image),e.src);l=(await t.load([{src:d,data:n}]))[d]}const c=new Za({texture:l.source,data:i,cachePrefix:o});await c.parse();const h=(u=i==null?void 0:i.meta)==null?void 0:u.related_multi_packs;if(Array.isArray(h)){const d=[];for(const _ of h){if(typeof _!="string")continue;let b=a+_;(p=e.data)!=null&&p.ignoreMultiPack||(b=qa(b,e.src),d.push(t.load({src:b,data:{textureOptions:n,ignoreMultiPack:!0}})))}const g=await Promise.all(d);c.linkedSheets=g,g.forEach(_=>{_.linkedSheets=[c].concat(c.linkedSheets.filter(b=>b!==_))})}return c},async unload(i,e,t){await t.unload(i.textureSource._sourceOrigin),i.destroy(!1)}}};Q.add(Bp);class Qa{constructor(e){this._lastTransform="",this._observer=null,this._tickerAttached=!1,this.updateTranslation=()=>{if(!this._canvas)return;const t=this._canvas.getBoundingClientRect(),s=this._canvas.width,r=this._canvas.height,n=t.width/s*this._renderer.resolution,o=t.height/r*this._renderer.resolution,a=t.left,l=t.top,c=`translate(${a}px, ${l}px) scale(${n}, ${o})`;c!==this._lastTransform&&(this._domElement.style.transform=c,this._lastTransform=c)},this._domElement=e.domElement,this._renderer=e.renderer,!(globalThis.OffscreenCanvas&&this._renderer.canvas instanceof OffscreenCanvas)&&(this._canvas=this._renderer.canvas,this._attachObserver())}get canvas(){return this._canvas}ensureAttached(){!this._domElement.parentNode&&this._canvas.parentNode&&(this._canvas.parentNode.appendChild(this._domElement),this.updateTranslation())}_attachObserver(){"ResizeObserver"in globalThis?(this._observer&&(this._observer.disconnect(),this._observer=null),this._observer=new ResizeObserver(e=>{for(const t of e){if(t.target!==this._canvas)continue;const s=this.canvas.width,r=this.canvas.height,n=t.contentRect.width/s*this._renderer.resolution,o=t.contentRect.height/r*this._renderer.resolution;(this._lastScaleX!==n||this._lastScaleY!==o)&&(this.updateTranslation(),this._lastScaleX=n,this._lastScaleY=o)}}),this._observer.observe(this._canvas)):this._tickerAttached||at.shared.add(this.updateTranslation,this,ys.HIGH)}destroy(){this._observer?(this._observer.disconnect(),this._observer=null):this._tickerAttached&&at.shared.remove(this.updateTranslation),this._domElement=null,this._renderer=null,this._canvas=null,this._tickerAttached=!1,this._lastTransform="",this._lastScaleX=null,this._lastScaleY=null}}class qs{constructor(e){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=qs.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new ye,this.page=new ye,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=e}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(e,t,s){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(e,t,s,r,n){throw new Error("initUIEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}preventDefault(){this.nativeEvent instanceof Event&&this.nativeEvent.cancelable&&this.nativeEvent.preventDefault(),this.defaultPrevented=!0}stopImmediatePropagation(){this.propagationImmediatelyStopped=!0}stopPropagation(){this.propagationStopped=!0}}var on=/iPhone/i,el=/iPod/i,tl=/iPad/i,sl=/\biOS-universal(?:.+)Mac\b/i,an=/\bAndroid(?:.+)Mobile\b/i,il=/Android/i,xs=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,Xi=/Silk/i,At=/Windows Phone/i,rl=/\bWindows(?:.+)ARM\b/i,nl=/BlackBerry/i,ol=/BB10/i,al=/Opera Mini/i,ll=/\b(CriOS|Chrome)(?:.+)Mobile/i,cl=/Mobile(?:.+)Firefox\b/i,hl=function(i){return typeof i<"u"&&i.platform==="MacIntel"&&typeof i.maxTouchPoints=="number"&&i.maxTouchPoints>1&&typeof MSStream>"u"};function Dp(i){return function(e){return e.test(i)}}function ul(i){var e={userAgent:"",platform:"",maxTouchPoints:0};!i&&typeof navigator<"u"?e={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof i=="string"?e.userAgent=i:i&&i.userAgent&&(e={userAgent:i.userAgent,platform:i.platform,maxTouchPoints:i.maxTouchPoints||0});var t=e.userAgent,s=t.split("[FBAN");typeof s[1]<"u"&&(t=s[0]),s=t.split("Twitter"),typeof s[1]<"u"&&(t=s[0]);var r=Dp(t),n={apple:{phone:r(on)&&!r(At),ipod:r(el),tablet:!r(on)&&(r(tl)||hl(e))&&!r(At),universal:r(sl),device:(r(on)||r(el)||r(tl)||r(sl)||hl(e))&&!r(At)},amazon:{phone:r(xs),tablet:!r(xs)&&r(Xi),device:r(xs)||r(Xi)},android:{phone:!r(At)&&r(xs)||!r(At)&&r(an),tablet:!r(At)&&!r(xs)&&!r(an)&&(r(Xi)||r(il)),device:!r(At)&&(r(xs)||r(Xi)||r(an)||r(il))||r(/\bokhttp\b/i)},windows:{phone:r(At),tablet:r(rl),device:r(At)||r(rl)},other:{blackberry:r(nl),blackberry10:r(ol),opera:r(al),firefox:r(cl),chrome:r(ll),device:r(nl)||r(ol)||r(al)||r(cl)||r(ll)},any:!1,phone:!1,tablet:!1};return n.any=n.apple.device||n.android.device||n.windows.device||n.other.device,n.phone=n.apple.phone||n.android.phone||n.windows.phone,n.tablet=n.apple.tablet||n.android.tablet||n.windows.tablet,n}const Np=(ul.default??ul)(globalThis.navigator),Up=9,dl=100,Gp=0,Fp=0,fl=2,pl=1,Lp=-1e3,Wp=-1e3,Hp=2,ln=class hf{constructor(e,t=Np){this._mobileInfo=t,this.debug=!1,this._activateOnTab=!0,this._deactivateOnMouseMove=!0,this._isActive=!1,this._isMobileAccessibility=!1,this._div=null,this._pools={},this._renderId=0,this._children=[],this._androidUpdateCount=0,this._androidUpdateFrequency=500,this._isRunningTests=!1,this._boundOnKeyDown=this._onKeyDown.bind(this),this._boundOnMouseMove=this._onMouseMove.bind(this),this._hookDiv=null,(t.tablet||t.phone)&&this._createTouchHook(),this._renderer=e}get isActive(){return this._isActive}get isMobileAccessibility(){return this._isMobileAccessibility}get hookDiv(){return this._hookDiv}get div(){return this._div}_createTouchHook(){const e=document.createElement("button");e.style.width=`${pl}px`,e.style.height=`${pl}px`,e.style.position="absolute",e.style.top=`${Lp}px`,e.style.left=`${Wp}px`,e.style.zIndex=Hp.toString(),e.style.backgroundColor="#FF0000",e.title="select to enable accessibility for this content",e.addEventListener("focus",()=>{this._isMobileAccessibility=!0,this._activate(),this._destroyTouchHook()}),document.body.appendChild(e),this._hookDiv=e}_destroyTouchHook(){this._hookDiv&&(document.body.removeChild(this._hookDiv),this._hookDiv=null)}_activate(){if(this._isActive)return;this._isActive=!0,this._div||(this._div=document.createElement("div"),this._div.style.position="absolute",this._div.style.top=`${Gp}px`,this._div.style.left=`${Fp}px`,this._div.style.pointerEvents="none",this._div.style.zIndex=fl.toString(),this._canvasObserver=new Qa({domElement:this._div,renderer:this._renderer})),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._deactivateOnMouseMove&&globalThis.document.addEventListener("mousemove",this._boundOnMouseMove,!0);const e=this._renderer.view.canvas;if(e.parentNode)this._canvasObserver.ensureAttached(),this._initAccessibilitySetup();else{const t=new MutationObserver(()=>{e.parentNode&&(t.disconnect(),this._canvasObserver.ensureAttached(),this._initAccessibilitySetup())});t.observe(document.body,{childList:!0,subtree:!0})}}_initAccessibilitySetup(){this._renderer.runners.postrender.add(this),this._renderer.lastObjectRendered&&this._updateAccessibleObjects(this._renderer.lastObjectRendered)}_deactivate(){var e,t;if(!(!this._isActive||this._isMobileAccessibility)){this._isActive=!1,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._renderer.runners.postrender.remove(this);for(const s of this._children)(e=s._accessibleDiv)!=null&&e.parentNode&&(s._accessibleDiv.parentNode.removeChild(s._accessibleDiv),s._accessibleDiv=null),s._accessibleActive=!1;for(const s in this._pools)this._pools[s].forEach(n=>{n.parentNode&&n.parentNode.removeChild(n)}),delete this._pools[s];(t=this._div)!=null&&t.parentNode&&this._div.parentNode.removeChild(this._div),this._pools={},this._children=[]}}_updateAccessibleObjects(e){if(!e.visible||!e.accessibleChildren)return;e.accessible&&(e._accessibleActive||this._addChild(e),e._renderId=this._renderId);const t=e.children;if(t)for(let s=0;s<t.length;s++)this._updateAccessibleObjects(t[s])}init(e){const s={accessibilityOptions:{...hf.defaultOptions,...(e==null?void 0:e.accessibilityOptions)||{}}};this.debug=s.accessibilityOptions.debug,this._activateOnTab=s.accessibilityOptions.activateOnTab,this._deactivateOnMouseMove=s.accessibilityOptions.deactivateOnMouseMove,s.accessibilityOptions.enabledByDefault&&this._activate(),this._renderer.runners.postrender.remove(this)}postrender(){const e=performance.now();if(this._mobileInfo.android.device&&e<this._androidUpdateCount||(this._androidUpdateCount=e+this._androidUpdateFrequency,(!this._renderer.renderingToScreen||!this._renderer.view.canvas)&&!this._isRunningTests))return;const t=new Set;if(this._renderer.lastObjectRendered){this._updateAccessibleObjects(this._renderer.lastObjectRendered);for(const s of this._children)s._renderId===this._renderId&&t.add(this._children.indexOf(s))}for(let s=this._children.length-1;s>=0;s--){const r=this._children[s];t.has(s)||(r._accessibleDiv&&r._accessibleDiv.parentNode&&(r._accessibleDiv.parentNode.removeChild(r._accessibleDiv),this._getPool(r.accessibleType).push(r._accessibleDiv),r._accessibleDiv=null),r._accessibleActive=!1,Ma(this._children,s,1))}this._renderer.renderingToScreen&&this._canvasObserver.ensureAttached();for(let s=0;s<this._children.length;s++){const r=this._children[s];if(!r._accessibleActive||!r._accessibleDiv)continue;const n=r._accessibleDiv,o=r.hitArea||r.getBounds().rectangle;if(r.hitArea){const a=r.worldTransform;n.style.left=`${a.tx+o.x*a.a}px`,n.style.top=`${a.ty+o.y*a.d}px`,n.style.width=`${o.width*a.a}px`,n.style.height=`${o.height*a.d}px`}else this._capHitArea(o),n.style.left=`${o.x}px`,n.style.top=`${o.y}px`,n.style.width=`${o.width}px`,n.style.height=`${o.height}px`}this._renderId++}_updateDebugHTML(e){e.innerHTML=`type: ${e.type}</br> title : ${e.title}</br> tabIndex: ${e.tabIndex}`}_capHitArea(e){e.x<0&&(e.width+=e.x,e.x=0),e.y<0&&(e.height+=e.y,e.y=0);const{width:t,height:s}=this._renderer;e.x+e.width>t&&(e.width=t-e.x),e.y+e.height>s&&(e.height=s-e.y)}_addChild(e){let s=this._getPool(e.accessibleType).pop();s?(s.innerHTML="",s.removeAttribute("title"),s.removeAttribute("aria-label"),s.tabIndex=0):(e.accessibleType==="button"?s=document.createElement("button"):(s=document.createElement(e.accessibleType),s.style.cssText=`
|
|
4
|
+
`),n?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",r),console.warn(s),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",r),console.warn(s))),ca.add(e)});Object.defineProperties(ee,{quiet:{get:()=>fs.quiet,set:i=>{fs.quiet=i},enumerable:!0,configurable:!1},noColor:{get:()=>fs.noColor,set:i=>{fs.noColor=i},enumerable:!0,configurable:!1}});const ha=()=>{};function Gi(i){return i+=i===0?1:0,--i,i|=i>>>1,i|=i>>>2,i|=i>>>4,i|=i>>>8,i|=i>>>16,i+1}function ua(i){return!(i&i-1)&&!!i}function da(i){const e={};for(const t in i)i[t]!==void 0&&(e[t]=i[t]);return e}const fa=Object.create(null);function $f(i){const e=fa[i];return e===void 0&&(fa[i]=be("resource")),e}const pa=class af extends lt{constructor(e={}){super(),this._resourceType="textureSampler",this._touched=0,this._maxAnisotropy=1,this.destroyed=!1,e={...af.defaultOptions,...e},this.addressMode=e.addressMode,this.addressModeU=e.addressModeU??this.addressModeU,this.addressModeV=e.addressModeV??this.addressModeV,this.addressModeW=e.addressModeW??this.addressModeW,this.scaleMode=e.scaleMode,this.magFilter=e.magFilter??this.magFilter,this.minFilter=e.minFilter??this.minFilter,this.mipmapFilter=e.mipmapFilter??this.mipmapFilter,this.lodMinClamp=e.lodMinClamp,this.lodMaxClamp=e.lodMaxClamp,this.compare=e.compare,this.maxAnisotropy=e.maxAnisotropy??1}set addressMode(e){this.addressModeU=e,this.addressModeV=e,this.addressModeW=e}get addressMode(){return this.addressModeU}set wrapMode(e){ee(Be,"TextureStyle.wrapMode is now TextureStyle.addressMode"),this.addressMode=e}get wrapMode(){return this.addressMode}set scaleMode(e){this.magFilter=e,this.minFilter=e,this.mipmapFilter=e}get scaleMode(){return this.magFilter}set maxAnisotropy(e){this._maxAnisotropy=Math.min(e,16),this._maxAnisotropy>1&&(this.scaleMode="linear")}get maxAnisotropy(){return this._maxAnisotropy}get _resourceId(){return this._sharedResourceId||this._generateResourceId()}update(){this._sharedResourceId=null,this.emit("change",this)}_generateResourceId(){const e=`${this.addressModeU}-${this.addressModeV}-${this.addressModeW}-${this.magFilter}-${this.minFilter}-${this.mipmapFilter}-${this.lodMinClamp}-${this.lodMaxClamp}-${this.compare}-${this._maxAnisotropy}`;return this._sharedResourceId=$f(e),this._resourceId}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this.removeAllListeners()}};pa.defaultOptions={addressMode:"clamp-to-edge",scaleMode:"linear"};let Fr=pa;const ma=class lf extends lt{constructor(e={}){super(),this.options=e,this._gpuData=Object.create(null),this._gcLastUsed=-1,this.uid=be("textureSource"),this._resourceType="textureSource",this._resourceId=be("resource"),this.uploadMethodId="unknown",this._resolution=1,this.pixelWidth=1,this.pixelHeight=1,this.width=1,this.height=1,this.sampleCount=1,this.mipLevelCount=1,this.autoGenerateMipmaps=!1,this.format="rgba8unorm",this.dimension="2d",this.viewDimension="2d",this.arrayLayerCount=1,this.antialias=!1,this._touched=0,this._batchTick=-1,this._textureBindLocation=-1,e={...lf.defaultOptions,...e},this.label=e.label??"",this.resource=e.resource,this.autoGarbageCollect=e.autoGarbageCollect,this._resolution=e.resolution,e.width?this.pixelWidth=e.width*this._resolution:this.pixelWidth=this.resource?this.resourceWidth??1:1,e.height?this.pixelHeight=e.height*this._resolution:this.pixelHeight=this.resource?this.resourceHeight??1:1,this.width=this.pixelWidth/this._resolution,this.height=this.pixelHeight/this._resolution,this.format=e.format,this.dimension=e.dimensions,this.viewDimension=e.viewDimension??e.dimensions,this.arrayLayerCount=e.arrayLayerCount,this.mipLevelCount=e.mipLevelCount,this.autoGenerateMipmaps=e.autoGenerateMipmaps,this.sampleCount=e.sampleCount,this.antialias=e.antialias,this.alphaMode=e.alphaMode,this.style=new Fr(da(e)),this.destroyed=!1,this._refreshPOT()}get source(){return this}get style(){return this._style}set style(e){var t,s;this.style!==e&&((t=this._style)==null||t.off("change",this._onStyleChange,this),this._style=e,(s=this._style)==null||s.on("change",this._onStyleChange,this),this._onStyleChange())}set maxAnisotropy(e){this._style.maxAnisotropy=e}get maxAnisotropy(){return this._style.maxAnisotropy}get addressMode(){return this._style.addressMode}set addressMode(e){this._style.addressMode=e}get repeatMode(){return this._style.addressMode}set repeatMode(e){this._style.addressMode=e}get magFilter(){return this._style.magFilter}set magFilter(e){this._style.magFilter=e}get minFilter(){return this._style.minFilter}set minFilter(e){this._style.minFilter=e}get mipmapFilter(){return this._style.mipmapFilter}set mipmapFilter(e){this._style.mipmapFilter=e}get lodMinClamp(){return this._style.lodMinClamp}set lodMinClamp(e){this._style.lodMinClamp=e}get lodMaxClamp(){return this._style.lodMaxClamp}set lodMaxClamp(e){this._style.lodMaxClamp=e}_onStyleChange(){this.emit("styleChange",this)}update(){if(this.resource){const e=this._resolution;if(this.resize(this.resourceWidth/e,this.resourceHeight/e))return}this.emit("update",this)}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this._style&&(this._style.destroy(),this._style=null),this.uploadMethodId=null,this.resource=null,this.removeAllListeners()}unload(){var e,t;this._resourceId=be("resource"),this.emit("change",this),this.emit("unload",this);for(const s in this._gpuData)(t=(e=this._gpuData[s])==null?void 0:e.destroy)==null||t.call(e);this._gpuData=Object.create(null)}get resourceWidth(){const{resource:e}=this;return e.naturalWidth||e.videoWidth||e.displayWidth||e.width}get resourceHeight(){const{resource:e}=this;return e.naturalHeight||e.videoHeight||e.displayHeight||e.height}get resolution(){return this._resolution}set resolution(e){this._resolution!==e&&(this._resolution=e,this.width=this.pixelWidth/e,this.height=this.pixelHeight/e)}resize(e,t,s){s||(s=this._resolution),e||(e=this.width),t||(t=this.height);const r=Math.round(e*s),n=Math.round(t*s);return this.width=r/s,this.height=n/s,this._resolution=s,this.pixelWidth===r&&this.pixelHeight===n?!1:(this._refreshPOT(),this.pixelWidth=r,this.pixelHeight=n,this.emit("resize",this),this._resourceId=be("resource"),this.emit("change",this),!0)}updateMipmaps(){this.autoGenerateMipmaps&&this.mipLevelCount>1&&this.emit("updateMipmaps",this)}set wrapMode(e){this._style.wrapMode=e}get wrapMode(){return this._style.wrapMode}set scaleMode(e){this._style.scaleMode=e}get scaleMode(){return this._style.scaleMode}_refreshPOT(){this.isPowerOfTwo=ua(this.pixelWidth)&&ua(this.pixelHeight)}static test(e){throw new Error("Unimplemented")}};ma.defaultOptions={resolution:1,format:"bgra8unorm",alphaMode:"premultiply-alpha-on-upload",dimensions:"2d",viewDimension:"2d",arrayLayerCount:1,mipLevelCount:1,autoGenerateMipmaps:!1,sampleCount:1,antialias:!1,autoGarbageCollect:!1};let De=ma;class Lr extends De{constructor(e){const t=e.resource||new Float32Array(e.width*e.height*4);let s=e.format;s||(t instanceof Float32Array?s="rgba32float":t instanceof Int32Array||t instanceof Uint32Array?s="rgba32uint":t instanceof Int16Array||t instanceof Uint16Array?s="rgba16uint":(t instanceof Int8Array,s="bgra8unorm")),super({...e,resource:t,format:s}),this.uploadMethodId="buffer"}static test(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array}}Lr.extension=A.TextureSource;const ga=new H;class _a{constructor(e,t){this.mapCoord=new H,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._textureID=-1,this._updateID=0,this.clampOffset=0,typeof t>"u"?this.clampMargin=e.width<10?0:.5:this.clampMargin=t,this.isSimple=!1,this.texture=e}get texture(){return this._texture}set texture(e){var t;this.texture!==e&&((t=this._texture)==null||t.removeListener("update",this.update,this),this._texture=e,this._texture.addListener("update",this.update,this),this.update())}multiplyUvs(e,t){t===void 0&&(t=e);const s=this.mapCoord;for(let r=0;r<e.length;r+=2){const n=e[r],o=e[r+1];t[r]=n*s.a+o*s.c+s.tx,t[r+1]=n*s.b+o*s.d+s.ty}return t}update(){const e=this._texture;this._updateID++;const t=e.uvs;this.mapCoord.set(t.x1-t.x0,t.y1-t.y0,t.x3-t.x0,t.y3-t.y0,t.x0,t.y0);const s=e.orig,r=e.trim;r&&(ga.set(s.width/r.width,0,0,s.height/r.height,-r.x/r.width,-r.y/r.height),this.mapCoord.append(ga));const n=e.source,o=this.uClampFrame,a=this.clampMargin/n._resolution,l=this.clampOffset/n._resolution;return o[0]=(e.frame.x+a+l)/n.width,o[1]=(e.frame.y+a+l)/n.height,o[2]=(e.frame.x+e.frame.width-a+l)/n.width,o[3]=(e.frame.y+e.frame.height-a+l)/n.height,this.uClampOffset[0]=this.clampOffset/n.pixelWidth,this.uClampOffset[1]=this.clampOffset/n.pixelHeight,this.isSimple=e.frame.width===n.width&&e.frame.height===n.height&&e.rotate===0,!0}}class j extends lt{constructor({source:e,label:t,frame:s,orig:r,trim:n,defaultAnchor:o,defaultBorders:a,rotate:l,dynamic:c}={}){if(super(),this.uid=be("texture"),this.uvs={x0:0,y0:0,x1:0,y1:0,x2:0,y2:0,x3:0,y3:0},this.frame=new Ce,this.noFrame=!1,this.dynamic=!1,this.isTexture=!0,this.label=t,this.source=(e==null?void 0:e.source)??new De,this.noFrame=!s,s)this.frame.copyFrom(s);else{const{width:h,height:u}=this._source;this.frame.width=h,this.frame.height=u}this.orig=r||this.frame,this.trim=n,this.rotate=l??0,this.defaultAnchor=o,this.defaultBorders=a,this.destroyed=!1,this.dynamic=c||!1,this.updateUvs()}set source(e){this._source&&this._source.off("resize",this.update,this),this._source=e,e.on("resize",this.update,this),this.emit("update",this)}get source(){return this._source}get textureMatrix(){return this._textureMatrix||(this._textureMatrix=new _a(this)),this._textureMatrix}get width(){return this.orig.width}get height(){return this.orig.height}updateUvs(){const{uvs:e,frame:t}=this,{width:s,height:r}=this._source,n=t.x/s,o=t.y/r,a=t.width/s,l=t.height/r;let c=this.rotate;if(c){const h=a/2,u=l/2,p=n+h,d=o+u;c=re.add(c,re.NW),e.x0=p+h*re.uX(c),e.y0=d+u*re.uY(c),c=re.add(c,2),e.x1=p+h*re.uX(c),e.y1=d+u*re.uY(c),c=re.add(c,2),e.x2=p+h*re.uX(c),e.y2=d+u*re.uY(c),c=re.add(c,2),e.x3=p+h*re.uX(c),e.y3=d+u*re.uY(c)}else e.x0=n,e.y0=o,e.x1=n+a,e.y1=o,e.x2=n+a,e.y2=o+l,e.x3=n,e.y3=o+l}destroy(e=!1){this._source&&(this._source.off("resize",this.update,this),e&&(this._source.destroy(),this._source=null)),this._textureMatrix=null,this.destroyed=!0,this.emit("destroy",this),this.removeAllListeners()}update(){this.noFrame&&(this.frame.width=this._source.width,this.frame.height=this._source.height),this.updateUvs(),this.emit("update",this)}get baseTexture(){return ee(Be,"Texture.baseTexture is now Texture.source"),this._source}}j.EMPTY=new j({label:"EMPTY",source:new De({label:"EMPTY"})}),j.EMPTY.destroy=ha,j.WHITE=new j({source:new Lr({resource:new Uint8Array([255,255,255,255]),width:1,height:1,alphaMode:"premultiply-alpha-on-upload",label:"WHITE"}),label:"WHITE"}),j.WHITE.destroy=ha;function jf(i,e,t){const{width:s,height:r}=t.orig,n=t.trim;if(n){const o=n.width,a=n.height;i.minX=n.x-e._x*s,i.maxX=i.minX+o,i.minY=n.y-e._y*r,i.maxY=i.minY+a}else i.minX=-e._x*s,i.maxX=i.minX+s,i.minY=-e._y*r,i.maxY=i.minY+r}const ya=new H;class Ye{constructor(e=1/0,t=1/0,s=-1/0,r=-1/0){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=ya,this.minX=e,this.minY=t,this.maxX=s,this.maxY=r}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}get rectangle(){this._rectangle||(this._rectangle=new Ce);const e=this._rectangle;return this.minX>this.maxX||this.minY>this.maxY?(e.x=0,e.y=0,e.width=0,e.height=0):e.copyFromBounds(this),e}clear(){return this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=ya,this}set(e,t,s,r){this.minX=e,this.minY=t,this.maxX=s,this.maxY=r}addFrame(e,t,s,r,n){n||(n=this.matrix);const o=n.a,a=n.b,l=n.c,c=n.d,h=n.tx,u=n.ty;let p=this.minX,d=this.minY,g=this.maxX,_=this.maxY,b=o*e+l*t+h,v=a*e+c*t+u;b<p&&(p=b),v<d&&(d=v),b>g&&(g=b),v>_&&(_=v),b=o*s+l*t+h,v=a*s+c*t+u,b<p&&(p=b),v<d&&(d=v),b>g&&(g=b),v>_&&(_=v),b=o*e+l*r+h,v=a*e+c*r+u,b<p&&(p=b),v<d&&(d=v),b>g&&(g=b),v>_&&(_=v),b=o*s+l*r+h,v=a*s+c*r+u,b<p&&(p=b),v<d&&(d=v),b>g&&(g=b),v>_&&(_=v),this.minX=p,this.minY=d,this.maxX=g,this.maxY=_}addRect(e,t){this.addFrame(e.x,e.y,e.x+e.width,e.y+e.height,t)}addBounds(e,t){this.addFrame(e.minX,e.minY,e.maxX,e.maxY,t)}addBoundsMask(e){this.minX=this.minX>e.minX?this.minX:e.minX,this.minY=this.minY>e.minY?this.minY:e.minY,this.maxX=this.maxX<e.maxX?this.maxX:e.maxX,this.maxY=this.maxY<e.maxY?this.maxY:e.maxY}applyMatrix(e){const t=this.minX,s=this.minY,r=this.maxX,n=this.maxY,{a:o,b:a,c:l,d:c,tx:h,ty:u}=e;let p=o*t+l*s+h,d=a*t+c*s+u;this.minX=p,this.minY=d,this.maxX=p,this.maxY=d,p=o*r+l*s+h,d=a*r+c*s+u,this.minX=p<this.minX?p:this.minX,this.minY=d<this.minY?d:this.minY,this.maxX=p>this.maxX?p:this.maxX,this.maxY=d>this.maxY?d:this.maxY,p=o*t+l*n+h,d=a*t+c*n+u,this.minX=p<this.minX?p:this.minX,this.minY=d<this.minY?d:this.minY,this.maxX=p>this.maxX?p:this.maxX,this.maxY=d>this.maxY?d:this.maxY,p=o*r+l*n+h,d=a*r+c*n+u,this.minX=p<this.minX?p:this.minX,this.minY=d<this.minY?d:this.minY,this.maxX=p>this.maxX?p:this.maxX,this.maxY=d>this.maxY?d:this.maxY}fit(e){return this.minX<e.left&&(this.minX=e.left),this.maxX>e.right&&(this.maxX=e.right),this.minY<e.top&&(this.minY=e.top),this.maxY>e.bottom&&(this.maxY=e.bottom),this}fitBounds(e,t,s,r){return this.minX<e&&(this.minX=e),this.maxX>t&&(this.maxX=t),this.minY<s&&(this.minY=s),this.maxY>r&&(this.maxY=r),this}pad(e,t=e){return this.minX-=e,this.maxX+=e,this.minY-=t,this.maxY+=t,this}ceil(){return this.minX=Math.floor(this.minX),this.minY=Math.floor(this.minY),this.maxX=Math.ceil(this.maxX),this.maxY=Math.ceil(this.maxY),this}clone(){return new Ye(this.minX,this.minY,this.maxX,this.maxY)}scale(e,t=e){return this.minX*=e,this.minY*=t,this.maxX*=e,this.maxY*=t,this}get x(){return this.minX}set x(e){const t=this.maxX-this.minX;this.minX=e,this.maxX=e+t}get y(){return this.minY}set y(e){const t=this.maxY-this.minY;this.minY=e,this.maxY=e+t}get width(){return this.maxX-this.minX}set width(e){this.maxX=this.minX+e}get height(){return this.maxY-this.minY}set height(e){this.maxY=this.minY+e}get left(){return this.minX}get right(){return this.maxX}get top(){return this.minY}get bottom(){return this.maxY}get isPositive(){return this.maxX-this.minX>0&&this.maxY-this.minY>0}get isValid(){return this.minX+this.minY!==1/0}addVertexData(e,t,s,r){let n=this.minX,o=this.minY,a=this.maxX,l=this.maxY;r||(r=this.matrix);const c=r.a,h=r.b,u=r.c,p=r.d,d=r.tx,g=r.ty;for(let _=t;_<s;_+=2){const b=e[_],v=e[_+1],C=c*b+u*v+d,E=h*b+p*v+g;n=C<n?C:n,o=E<o?E:o,a=C>a?C:a,l=E>l?E:l}this.minX=n,this.minY=o,this.maxX=a,this.maxY=l}containsPoint(e,t){return this.minX<=e&&this.minY<=t&&this.maxX>=e&&this.maxY>=t}toString(){return`[pixi.js:Bounds minX=${this.minX} minY=${this.minY} maxX=${this.maxX} maxY=${this.maxY} width=${this.width} height=${this.height}]`}copyFrom(e){return this.minX=e.minX,this.minY=e.minY,this.maxX=e.maxX,this.maxY=e.maxY,this}}var Xf={grad:.9,turn:360,rad:360/(2*Math.PI)},St=function(i){return typeof i=="string"?i.length>0:typeof i=="number"},Fe=function(i,e,t){return e===void 0&&(e=0),t===void 0&&(t=Math.pow(10,e)),Math.round(t*i)/t+0},ot=function(i,e,t){return e===void 0&&(e=0),t===void 0&&(t=1),i>t?t:i>e?i:e},ba=function(i){return(i=isFinite(i)?i%360:0)>0?i:i+360},va=function(i){return{r:ot(i.r,0,255),g:ot(i.g,0,255),b:ot(i.b,0,255),a:ot(i.a)}},Wr=function(i){return{r:Fe(i.r),g:Fe(i.g),b:Fe(i.b),a:Fe(i.a,3)}},Yf=/^#([0-9a-f]{3,8})$/i,Fi=function(i){var e=i.toString(16);return e.length<2?"0"+e:e},xa=function(i){var e=i.r,t=i.g,s=i.b,r=i.a,n=Math.max(e,t,s),o=n-Math.min(e,t,s),a=o?n===e?(t-s)/o:n===t?2+(s-e)/o:4+(e-t)/o:0;return{h:60*(a<0?a+6:a),s:n?o/n*100:0,v:n/255*100,a:r}},Ca=function(i){var e=i.h,t=i.s,s=i.v,r=i.a;e=e/360*6,t/=100,s/=100;var n=Math.floor(e),o=s*(1-t),a=s*(1-(e-n)*t),l=s*(1-(1-e+n)*t),c=n%6;return{r:255*[s,a,o,o,l,s][c],g:255*[l,s,s,a,o,o][c],b:255*[o,o,l,s,s,a][c],a:r}},Ea=function(i){return{h:ba(i.h),s:ot(i.s,0,100),l:ot(i.l,0,100),a:ot(i.a)}},Sa=function(i){return{h:Fe(i.h),s:Fe(i.s),l:Fe(i.l),a:Fe(i.a,3)}},Ta=function(i){return Ca((t=(e=i).s,{h:e.h,s:(t*=((s=e.l)<50?s:100-s)/100)>0?2*t/(s+t)*100:0,v:s+t,a:e.a}));var e,t,s},$s=function(i){return{h:(e=xa(i)).h,s:(r=(200-(t=e.s))*(s=e.v)/100)>0&&r<200?t*s/100/(r<=100?r:200-r)*100:0,l:r/2,a:e.a};var e,t,s,r},qf=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Kf=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Zf=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Jf=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Hr={string:[[function(i){var e=Yf.exec(i);return e?(i=e[1]).length<=4?{r:parseInt(i[0]+i[0],16),g:parseInt(i[1]+i[1],16),b:parseInt(i[2]+i[2],16),a:i.length===4?Fe(parseInt(i[3]+i[3],16)/255,2):1}:i.length===6||i.length===8?{r:parseInt(i.substr(0,2),16),g:parseInt(i.substr(2,2),16),b:parseInt(i.substr(4,2),16),a:i.length===8?Fe(parseInt(i.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(i){var e=Zf.exec(i)||Jf.exec(i);return e?e[2]!==e[4]||e[4]!==e[6]?null:va({r:Number(e[1])/(e[2]?100/255:1),g:Number(e[3])/(e[4]?100/255:1),b:Number(e[5])/(e[6]?100/255:1),a:e[7]===void 0?1:Number(e[7])/(e[8]?100:1)}):null},"rgb"],[function(i){var e=qf.exec(i)||Kf.exec(i);if(!e)return null;var t,s,r=Ea({h:(t=e[1],s=e[2],s===void 0&&(s="deg"),Number(t)*(Xf[s]||1)),s:Number(e[3]),l:Number(e[4]),a:e[5]===void 0?1:Number(e[5])/(e[6]?100:1)});return Ta(r)},"hsl"]],object:[[function(i){var e=i.r,t=i.g,s=i.b,r=i.a,n=r===void 0?1:r;return St(e)&&St(t)&&St(s)?va({r:Number(e),g:Number(t),b:Number(s),a:Number(n)}):null},"rgb"],[function(i){var e=i.h,t=i.s,s=i.l,r=i.a,n=r===void 0?1:r;if(!St(e)||!St(t)||!St(s))return null;var o=Ea({h:Number(e),s:Number(t),l:Number(s),a:Number(n)});return Ta(o)},"hsl"],[function(i){var e=i.h,t=i.s,s=i.v,r=i.a,n=r===void 0?1:r;if(!St(e)||!St(t)||!St(s))return null;var o=(function(a){return{h:ba(a.h),s:ot(a.s,0,100),v:ot(a.v,0,100),a:ot(a.a)}})({h:Number(e),s:Number(t),v:Number(s),a:Number(n)});return Ca(o)},"hsv"]]},Aa=function(i,e){for(var t=0;t<e.length;t++){var s=e[t][0](i);if(s)return[s,e[t][1]]}return[null,void 0]},Qf=function(i){return typeof i=="string"?Aa(i.trim(),Hr.string):typeof i=="object"&&i!==null?Aa(i,Hr.object):[null,void 0]},Vr=function(i,e){var t=$s(i);return{h:t.h,s:ot(t.s+100*e,0,100),l:t.l,a:t.a}},zr=function(i){return(299*i.r+587*i.g+114*i.b)/1e3/255},wa=function(i,e){var t=$s(i);return{h:t.h,s:t.s,l:ot(t.l+100*e,0,100),a:t.a}},$r=(function(){function i(e){this.parsed=Qf(e)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return i.prototype.isValid=function(){return this.parsed!==null},i.prototype.brightness=function(){return Fe(zr(this.rgba),2)},i.prototype.isDark=function(){return zr(this.rgba)<.5},i.prototype.isLight=function(){return zr(this.rgba)>=.5},i.prototype.toHex=function(){return e=Wr(this.rgba),t=e.r,s=e.g,r=e.b,o=(n=e.a)<1?Fi(Fe(255*n)):"","#"+Fi(t)+Fi(s)+Fi(r)+o;var e,t,s,r,n,o},i.prototype.toRgb=function(){return Wr(this.rgba)},i.prototype.toRgbString=function(){return e=Wr(this.rgba),t=e.r,s=e.g,r=e.b,(n=e.a)<1?"rgba("+t+", "+s+", "+r+", "+n+")":"rgb("+t+", "+s+", "+r+")";var e,t,s,r,n},i.prototype.toHsl=function(){return Sa($s(this.rgba))},i.prototype.toHslString=function(){return e=Sa($s(this.rgba)),t=e.h,s=e.s,r=e.l,(n=e.a)<1?"hsla("+t+", "+s+"%, "+r+"%, "+n+")":"hsl("+t+", "+s+"%, "+r+"%)";var e,t,s,r,n},i.prototype.toHsv=function(){return e=xa(this.rgba),{h:Fe(e.h),s:Fe(e.s),v:Fe(e.v),a:Fe(e.a,3)};var e},i.prototype.invert=function(){return pt({r:255-(e=this.rgba).r,g:255-e.g,b:255-e.b,a:e.a});var e},i.prototype.saturate=function(e){return e===void 0&&(e=.1),pt(Vr(this.rgba,e))},i.prototype.desaturate=function(e){return e===void 0&&(e=.1),pt(Vr(this.rgba,-e))},i.prototype.grayscale=function(){return pt(Vr(this.rgba,-1))},i.prototype.lighten=function(e){return e===void 0&&(e=.1),pt(wa(this.rgba,e))},i.prototype.darken=function(e){return e===void 0&&(e=.1),pt(wa(this.rgba,-e))},i.prototype.rotate=function(e){return e===void 0&&(e=15),this.hue(this.hue()+e)},i.prototype.alpha=function(e){return typeof e=="number"?pt({r:(t=this.rgba).r,g:t.g,b:t.b,a:e}):Fe(this.rgba.a,3);var t},i.prototype.hue=function(e){var t=$s(this.rgba);return typeof e=="number"?pt({h:e,s:t.s,l:t.l,a:t.a}):Fe(t.h)},i.prototype.isEqual=function(e){return this.toHex()===pt(e).toHex()},i})(),pt=function(i){return i instanceof $r?i:new $r(i)},Ia=[],ep=function(i){i.forEach(function(e){Ia.indexOf(e)<0&&(e($r,Hr),Ia.push(e))})};function tp(i,e){var t={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},s={};for(var r in t)s[t[r]]=r;var n={};i.prototype.toName=function(o){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var a,l,c=s[this.toHex()];if(c)return c;if(o!=null&&o.closest){var h=this.toRgb(),u=1/0,p="black";if(!n.length)for(var d in t)n[d]=new i(t[d]).toRgb();for(var g in t){var _=(a=h,l=n[g],Math.pow(a.r-l.r,2)+Math.pow(a.g-l.g,2)+Math.pow(a.b-l.b,2));_<u&&(u=_,p=g)}return p}},e.string.push([function(o){var a=o.toLowerCase(),l=a==="transparent"?"#0000":t[a];return l?new i(l).toRgb():null},"name"])}ep([tp]);const ps=class Oi{constructor(e=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=e}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(e){return this.value=e,this}set value(e){if(e instanceof Oi)this._value=this._cloneSource(e._value),this._int=e._int,this._components.set(e._components);else{if(e===null)throw new Error("Cannot set Color#value to null");(this._value===null||!this._isSourceEqual(this._value,e))&&(this._value=this._cloneSource(e),this._normalize(this._value))}}get value(){return this._value}_cloneSource(e){return typeof e=="string"||typeof e=="number"||e instanceof Number||e===null?e:Array.isArray(e)||ArrayBuffer.isView(e)?e.slice(0):typeof e=="object"&&e!==null?{...e}:e}_isSourceEqual(e,t){const s=typeof e;if(s!==typeof t)return!1;if(s==="number"||s==="string"||e instanceof Number)return e===t;if(Array.isArray(e)&&Array.isArray(t)||ArrayBuffer.isView(e)&&ArrayBuffer.isView(t))return e.length!==t.length?!1:e.every((n,o)=>n===t[o]);if(e!==null&&t!==null){const n=Object.keys(e),o=Object.keys(t);return n.length!==o.length?!1:n.every(a=>e[a]===t[a])}return e===t}toRgba(){const[e,t,s,r]=this._components;return{r:e,g:t,b:s,a:r}}toRgb(){const[e,t,s]=this._components;return{r:e,g:t,b:s}}toRgbaString(){const[e,t,s]=this.toUint8RgbArray();return`rgba(${e},${t},${s},${this.alpha})`}toUint8RgbArray(e){const[t,s,r]=this._components;return this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb),e[0]=Math.round(t*255),e[1]=Math.round(s*255),e[2]=Math.round(r*255),e}toArray(e){this._arrayRgba||(this._arrayRgba=[]),e||(e=this._arrayRgba);const[t,s,r,n]=this._components;return e[0]=t,e[1]=s,e[2]=r,e[3]=n,e}toRgbArray(e){this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb);const[t,s,r]=this._components;return e[0]=t,e[1]=s,e[2]=r,e}toNumber(){return this._int}toBgrNumber(){const[e,t,s]=this.toUint8RgbArray();return(s<<16)+(t<<8)+e}toLittleEndianNumber(){const e=this._int;return(e>>16)+(e&65280)+((e&255)<<16)}multiply(e){const[t,s,r,n]=Oi._temp.setValue(e)._components;return this._components[0]*=t,this._components[1]*=s,this._components[2]*=r,this._components[3]*=n,this._refreshInt(),this._value=null,this}premultiply(e,t=!0){return t&&(this._components[0]*=e,this._components[1]*=e,this._components[2]*=e),this._components[3]=e,this._refreshInt(),this._value=null,this}toPremultiplied(e,t=!0){if(e===1)return(255<<24)+this._int;if(e===0)return t?0:this._int;let s=this._int>>16&255,r=this._int>>8&255,n=this._int&255;return t&&(s=s*e+.5|0,r=r*e+.5|0,n=n*e+.5|0),(e*255<<24)+(s<<16)+(r<<8)+n}toHex(){const e=this._int.toString(16);return`#${"000000".substring(0,6-e.length)+e}`}toHexa(){const t=Math.round(this._components[3]*255).toString(16);return this.toHex()+"00".substring(0,2-t.length)+t}setAlpha(e){return this._components[3]=this._clamp(e),this._value=null,this}_normalize(e){let t,s,r,n;if((typeof e=="number"||e instanceof Number)&&e>=0&&e<=16777215){const o=e;t=(o>>16&255)/255,s=(o>>8&255)/255,r=(o&255)/255,n=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[t,s,r,n=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[t,s,r,n=255]=e,t/=255,s/=255,r/=255,n/=255;else if(typeof e=="string"||typeof e=="object"){if(typeof e=="string"){const a=Oi.HEX_PATTERN.exec(e);a&&(e=`#${a[2]}`)}const o=pt(e);o.isValid()&&({r:t,g:s,b:r,a:n}=o.rgba,t/=255,s/=255,r/=255)}if(t!==void 0)this._components[0]=t,this._components[1]=s,this._components[2]=r,this._components[3]=n,this._refreshInt();else throw new Error(`Unable to convert color ${e}`)}_refreshInt(){this._clamp(this._components);const[e,t,s]=this._components;this._int=(e*255<<16)+(t*255<<8)+(s*255|0)}_clamp(e,t=0,s=1){return typeof e=="number"?Math.min(Math.max(e,t),s):(e.forEach((r,n)=>{e[n]=Math.min(Math.max(r,t),s)}),e)}static isColorLike(e){return typeof e=="number"||typeof e=="string"||e instanceof Number||e instanceof Oi||Array.isArray(e)||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Float32Array||e.r!==void 0&&e.g!==void 0&&e.b!==void 0||e.r!==void 0&&e.g!==void 0&&e.b!==void 0&&e.a!==void 0||e.h!==void 0&&e.s!==void 0&&e.l!==void 0||e.h!==void 0&&e.s!==void 0&&e.l!==void 0&&e.a!==void 0||e.h!==void 0&&e.s!==void 0&&e.v!==void 0||e.h!==void 0&&e.s!==void 0&&e.v!==void 0&&e.a!==void 0}};ps.shared=new ps,ps._temp=new ps,ps.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let Pe=ps;const sp={cullArea:null,cullable:!1,cullableChildren:!0};let jr=0;const Ra=500;function ie(...i){jr!==Ra&&(jr++,jr===Ra?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...i))}const ms={_registeredResources:new Set,register(i){this._registeredResources.add(i)},unregister(i){this._registeredResources.delete(i)},release(){this._registeredResources.forEach(i=>i.clear())},get registeredCount(){return this._registeredResources.size},isRegistered(i){return this._registeredResources.has(i)},reset(){this._registeredResources.clear()}};class ip{constructor(e,t){this._pool=[],this._count=0,this._index=0,this._classType=e,t&&this.prepopulate(t)}prepopulate(e){for(let t=0;t<e;t++)this._pool[this._index++]=new this._classType;this._count+=e}get(e){var s;let t;return this._index>0?t=this._pool[--this._index]:(t=new this._classType,this._count++),(s=t.init)==null||s.call(t,e),t}return(e){var t;(t=e.reset)==null||t.call(e),this._pool[this._index++]=e}get totalSize(){return this._count}get totalFree(){return this._index}get totalUsed(){return this._count-this._index}clear(){if(this._pool.length>0&&this._pool[0].destroy)for(let e=0;e<this._index;e++)this._pool[e].destroy();this._pool.length=0,this._count=0,this._index=0}}class rp{constructor(){this._poolsByClass=new Map}prepopulate(e,t){this.getPool(e).prepopulate(t)}get(e,t){return this.getPool(e).get(t)}return(e){this.getPool(e.constructor).return(e)}getPool(e){return this._poolsByClass.has(e)||this._poolsByClass.set(e,new ip(e)),this._poolsByClass.get(e)}stats(){const e={};return this._poolsByClass.forEach(t=>{const s=e[t._classType.name]?t._classType.name+t._classType.ID:t._classType.name;e[s]={free:t.totalFree,used:t.totalUsed,size:t.totalSize}}),e}clear(){this._poolsByClass.forEach(e=>e.clear()),this._poolsByClass.clear()}}const Le=new rp;ms.register(Le);const np={get isCachedAsTexture(){var i;return!!((i=this.renderGroup)!=null&&i.isCachedAsTexture)},cacheAsTexture(i){typeof i=="boolean"&&i===!1?this.disableRenderGroup():(this.enableRenderGroup(),this.renderGroup.enableCacheAsTexture(i===!0?{}:i))},updateCacheTexture(){var i;(i=this.renderGroup)==null||i.updateCacheTexture()},get cacheAsBitmap(){return this.isCachedAsTexture},set cacheAsBitmap(i){ee("v8.6.0","cacheAsBitmap is deprecated, use cacheAsTexture instead."),this.cacheAsTexture(i)}};function Ma(i,e,t){const s=i.length;let r;if(e>=s||t===0)return;t=e+t>s?s-e:t;const n=s-t;for(r=e;r<n;++r)i[r]=i[r+t];i.length=n}const op={allowChildren:!0,removeChildren(i=0,e){var n;const t=e??this.children.length,s=t-i,r=[];if(s>0&&s<=t){for(let a=t-1;a>=i;a--){const l=this.children[a];l&&(r.push(l),l.parent=null)}Ma(this.children,i,t);const o=this.renderGroup||this.parentRenderGroup;o&&o.removeChildren(r);for(let a=0;a<r.length;++a){const l=r[a];(n=l.parentRenderLayer)==null||n.detach(l),this.emit("childRemoved",l,this,a),r[a].emit("removed",this)}return r.length>0&&this._didViewChangeTick++,r}else if(s===0&&this.children.length===0)return r;throw new RangeError("removeChildren: numeric values are outside the acceptable range.")},removeChildAt(i){const e=this.getChildAt(i);return this.removeChild(e)},getChildAt(i){if(i<0||i>=this.children.length)throw new Error(`getChildAt: Index (${i}) does not exist.`);return this.children[i]},setChildIndex(i,e){if(e<0||e>=this.children.length)throw new Error(`The index ${e} supplied is out of bounds ${this.children.length}`);this.getChildIndex(i),this.addChildAt(i,e)},getChildIndex(i){const e=this.children.indexOf(i);if(e===-1)throw new Error("The supplied Container must be a child of the caller");return e},addChildAt(i,e){this.allowChildren||ee(Be,"addChildAt: Only Containers will be allowed to add children in v8.0.0");const{children:t}=this;if(e<0||e>t.length)throw new Error(`${i}addChildAt: The index ${e} supplied is out of bounds ${t.length}`);const s=i.parent===this;if(i.parent){const n=i.parent.children.indexOf(i);if(s){if(n===e)return i;i.parent.children.splice(n,1)}else i.removeFromParent()}e===t.length?t.push(i):t.splice(e,0,i),i.parent=this,i.didChange=!0,i._updateFlags=15;const r=this.renderGroup||this.parentRenderGroup;return r&&r.addChild(i),this.sortableChildren&&(this.sortDirty=!0),s||(this.emit("childAdded",i,this,e),i.emit("added",this)),i},swapChildren(i,e){if(i===e)return;const t=this.getChildIndex(i),s=this.getChildIndex(e);this.children[t]=e,this.children[s]=i;const r=this.renderGroup||this.parentRenderGroup;r&&(r.structureDidChange=!0),this._didContainerChangeTick++},removeFromParent(){var i;(i=this.parent)==null||i.removeChild(this)},reparentChild(...i){return i.length===1?this.reparentChildAt(i[0],this.children.length):(i.forEach(e=>this.reparentChildAt(e,this.children.length)),i[0])},reparentChildAt(i,e){if(i.parent===this)return this.setChildIndex(i,e),i;const t=i.worldTransform.clone();i.removeFromParent(),this.addChildAt(i,e);const s=this.worldTransform.clone();return s.invert(),t.prepend(s),i.setFromMatrix(t),i},replaceChild(i,e){i.updateLocalTransform(),this.addChildAt(e,this.getChildIndex(i)),e.setFromMatrix(i.localTransform),e.updateLocalTransform(),this.removeChild(i)}},ap={collectRenderables(i,e,t){this.parentRenderLayer&&this.parentRenderLayer!==t||this.globalDisplayStatus<7||!this.includeInBuild||(this.sortableChildren&&this.sortChildren(),this.isSimple?this.collectRenderablesSimple(i,e,t):this.renderGroup?e.renderPipes.renderGroup.addRenderGroup(this.renderGroup,i):this.collectRenderablesWithEffects(i,e,t))},collectRenderablesSimple(i,e,t){const s=this.children,r=s.length;for(let n=0;n<r;n++)s[n].collectRenderables(i,e,t)},collectRenderablesWithEffects(i,e,t){const{renderPipes:s}=e;for(let r=0;r<this.effects.length;r++){const n=this.effects[r];s[n.pipe].push(n,this,i)}this.collectRenderablesSimple(i,e,t);for(let r=this.effects.length-1;r>=0;r--){const n=this.effects[r];s[n.pipe].pop(n,this,i)}}};class Li{constructor(){this.pipe="filter",this.priority=1}destroy(){for(let e=0;e<this.filters.length;e++)this.filters[e].destroy();this.filters=null,this.filterArea=null}}class lp{constructor(){this._effectClasses=[],this._tests=[],this._initialized=!1}init(){this._initialized||(this._initialized=!0,this._effectClasses.forEach(e=>{this.add({test:e.test,maskClass:e})}))}add(e){this._tests.push(e)}getMaskEffect(e){this._initialized||this.init();for(let t=0;t<this._tests.length;t++){const s=this._tests[t];if(s.test(e))return Le.get(s.maskClass,e)}return e}returnMaskEffect(e){Le.return(e)}}const Xr=new lp;Q.handleByList(A.MaskEffect,Xr._effectClasses);const cp={_maskEffect:null,_maskOptions:{inverse:!1},_filterEffect:null,effects:[],_markStructureAsChanged(){const i=this.renderGroup||this.parentRenderGroup;i&&(i.structureDidChange=!0)},addEffect(i){this.effects.indexOf(i)===-1&&(this.effects.push(i),this.effects.sort((t,s)=>t.priority-s.priority),this._markStructureAsChanged(),this._updateIsSimple())},removeEffect(i){const e=this.effects.indexOf(i);e!==-1&&(this.effects.splice(e,1),this._markStructureAsChanged(),this._updateIsSimple())},set mask(i){const e=this._maskEffect;(e==null?void 0:e.mask)!==i&&(e&&(this.removeEffect(e),Xr.returnMaskEffect(e),this._maskEffect=null),i!=null&&(this._maskEffect=Xr.getMaskEffect(i),this.addEffect(this._maskEffect)))},get mask(){var i;return(i=this._maskEffect)==null?void 0:i.mask},setMask(i){this._maskOptions={...this._maskOptions,...i},i.mask&&(this.mask=i.mask),this._markStructureAsChanged()},set filters(i){var n;!Array.isArray(i)&&i&&(i=[i]);const e=this._filterEffect||(this._filterEffect=new Li);i=i;const t=(i==null?void 0:i.length)>0,s=((n=e.filters)==null?void 0:n.length)>0,r=t!==s;i=Array.isArray(i)?i.slice(0):i,e.filters=Object.freeze(i),r&&(t?this.addEffect(e):(this.removeEffect(e),e.filters=i??null))},get filters(){var i;return(i=this._filterEffect)==null?void 0:i.filters},set filterArea(i){this._filterEffect||(this._filterEffect=new Li),this._filterEffect.filterArea=i},get filterArea(){var i;return(i=this._filterEffect)==null?void 0:i.filterArea}},hp={label:null,get name(){return ee(Be,"Container.name property has been removed, use Container.label instead"),this.label},set name(i){ee(Be,"Container.name property has been removed, use Container.label instead"),this.label=i},getChildByName(i,e=!1){return this.getChildByLabel(i,e)},getChildByLabel(i,e=!1){const t=this.children;for(let s=0;s<t.length;s++){const r=t[s];if(r.label===i||i instanceof RegExp&&i.test(r.label))return r}if(e)for(let s=0;s<t.length;s++){const n=t[s].getChildByLabel(i,!0);if(n)return n}return null},getChildrenByLabel(i,e=!1,t=[]){const s=this.children;for(let r=0;r<s.length;r++){const n=s[r];(n.label===i||i instanceof RegExp&&i.test(n.label))&&t.push(n)}if(e)for(let r=0;r<s.length;r++)s[r].getChildrenByLabel(i,!0,t);return t}},qe=Le.getPool(H),Tt=Le.getPool(Ye),up=new H,dp={getFastGlobalBounds(i,e){e||(e=new Ye),e.clear(),this._getGlobalBoundsRecursive(!!i,e,this.parentRenderLayer),e.isValid||e.set(0,0,0,0);const t=this.renderGroup||this.parentRenderGroup;return e.applyMatrix(t.worldTransform),e},_getGlobalBoundsRecursive(i,e,t){let s=e;if(i&&this.parentRenderLayer&&this.parentRenderLayer!==t||this.localDisplayStatus!==7||!this.measurable)return;const r=!!this.effects.length;if((this.renderGroup||r)&&(s=Tt.get().clear()),this.boundsArea)e.addRect(this.boundsArea,this.worldTransform);else{if(this.renderPipeId){const o=this.bounds;s.addFrame(o.minX,o.minY,o.maxX,o.maxY,this.groupTransform)}const n=this.children;for(let o=0;o<n.length;o++)n[o]._getGlobalBoundsRecursive(i,s,t)}if(r){let n=!1;const o=this.renderGroup||this.parentRenderGroup;for(let a=0;a<this.effects.length;a++)this.effects[a].addBounds&&(n||(n=!0,s.applyMatrix(o.worldTransform)),this.effects[a].addBounds(s,!0));n&&s.applyMatrix(o.worldTransform.copyTo(up).invert()),e.addBounds(s),Tt.return(s)}else this.renderGroup&&(e.addBounds(s,this.relativeGroupTransform),Tt.return(s))}};function Yr(i,e,t){t.clear();let s,r;return i.parent?e?s=i.parent.worldTransform:(r=qe.get().identity(),s=qr(i,r)):s=H.IDENTITY,Pa(i,t,s,e),r&&qe.return(r),t.isValid||t.set(0,0,0,0),t}function Pa(i,e,t,s){var a,l;if(!i.visible||!i.measurable)return;let r;s?r=i.worldTransform:(i.updateLocalTransform(),r=qe.get(),r.appendFrom(i.localTransform,t));const n=e,o=!!i.effects.length;if(o&&(e=Tt.get().clear()),i.boundsArea)e.addRect(i.boundsArea,r);else{const c=i.bounds;c&&!c.isEmpty()&&(e.matrix=r,e.addBounds(c));for(let h=0;h<i.children.length;h++)Pa(i.children[h],e,r,s)}if(o){for(let c=0;c<i.effects.length;c++)(l=(a=i.effects[c]).addBounds)==null||l.call(a,e);n.addBounds(e,H.IDENTITY),Tt.return(e)}s||qe.return(r)}function qr(i,e){const t=i.parent;return t&&(qr(t,e),t.updateLocalTransform(),e.append(t.localTransform)),e}function gs(i,e){if(i===16777215||!e)return e;if(e===16777215||!i)return i;const t=i>>16&255,s=i>>8&255,r=i&255,n=e>>16&255,o=e>>8&255,a=e&255,l=t*n/255|0,c=s*o/255|0,h=r*a/255|0;return(l<<16)+(c<<8)+h}const ka=16777215;function Wi(i,e){return i===ka?e:e===ka?i:gs(i,e)}function _s(i){return((i&255)<<16)+(i&65280)+(i>>16&255)}const fp={getGlobalAlpha(i){if(i)return this.renderGroup?this.renderGroup.worldAlpha:this.parentRenderGroup?this.parentRenderGroup.worldAlpha*this.alpha:this.alpha;let e=this.alpha,t=this.parent;for(;t;)e*=t.alpha,t=t.parent;return e},getGlobalTransform(i=new H,e){if(e)return i.copyFrom(this.worldTransform);this.updateLocalTransform();const t=qr(this,qe.get().identity());return i.appendFrom(this.localTransform,t),qe.return(t),i},getGlobalTint(i){if(i)return this.renderGroup?_s(this.renderGroup.worldColor):this.parentRenderGroup?_s(Wi(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let e=this.localColor,t=this.parent;for(;t;)e=Wi(e,t.localColor),t=t.parent;return _s(e)}};function Kr(i,e,t){return e.clear(),t||(t=H.IDENTITY),Oa(i,e,t,i,!0),e.isValid||e.set(0,0,0,0),e}function Oa(i,e,t,s,r){var l,c;let n;if(r)n=qe.get(),n=t.copyTo(n);else{if(!i.visible||!i.measurable)return;i.updateLocalTransform();const h=i.localTransform;n=qe.get(),n.appendFrom(h,t)}const o=e,a=!!i.effects.length;if(a&&(e=Tt.get().clear()),i.boundsArea)e.addRect(i.boundsArea,n);else{i.renderPipeId&&(e.matrix=n,e.addBounds(i.bounds));const h=i.children;for(let u=0;u<h.length;u++)Oa(h[u],e,n,s,!1)}if(a){for(let h=0;h<i.effects.length;h++)(c=(l=i.effects[h]).addLocalBounds)==null||c.call(l,e,s);o.addBounds(e,H.IDENTITY),Tt.return(e)}qe.return(n)}function Ba(i,e){const t=i.children;for(let s=0;s<t.length;s++){const r=t[s],n=r.uid,o=(r._didViewChangeTick&65535)<<16|r._didContainerChangeTick&65535,a=e.index;(e.data[a]!==n||e.data[a+1]!==o)&&(e.data[e.index]=n,e.data[e.index+1]=o,e.didChange=!0),e.index=a+2,r.children.length&&Ba(r,e)}return e.didChange}const pp=new H,mp={_localBoundsCacheId:-1,_localBoundsCacheData:null,_setWidth(i,e){const t=Math.sign(this.scale.x)||1;e!==0?this.scale.x=i/e*t:this.scale.x=t},_setHeight(i,e){const t=Math.sign(this.scale.y)||1;e!==0?this.scale.y=i/e*t:this.scale.y=t},getLocalBounds(){this._localBoundsCacheData||(this._localBoundsCacheData={data:[],index:1,didChange:!1,localBounds:new Ye});const i=this._localBoundsCacheData;return i.index=1,i.didChange=!1,i.data[0]!==this._didViewChangeTick&&(i.didChange=!0,i.data[0]=this._didViewChangeTick),Ba(this,i),i.didChange&&Kr(this,i.localBounds,pp),i.localBounds},getBounds(i,e){return Yr(this,i,e||new Ye)}},gp={_onRender:null,set onRender(i){const e=this.renderGroup||this.parentRenderGroup;if(!i){this._onRender&&(e==null||e.removeOnRender(this)),this._onRender=null;return}this._onRender||e==null||e.addOnRender(this),this._onRender=i},get onRender(){return this._onRender}},_p={_zIndex:0,sortDirty:!1,sortableChildren:!1,get zIndex(){return this._zIndex},set zIndex(i){this._zIndex!==i&&(this._zIndex=i,this.depthOfChildModified())},depthOfChildModified(){this.parent&&(this.parent.sortableChildren=!0,this.parent.sortDirty=!0),this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0)},sortChildren(){this.sortDirty&&(this.sortDirty=!1,this.children.sort(yp))}};function yp(i,e){return i._zIndex-e._zIndex}const bp={getGlobalPosition(i=new ye,e=!1){return this.parent?this.parent.toGlobal(this._position,i,e):(i.x=this._position.x,i.y=this._position.y),i},toGlobal(i,e,t=!1){const s=this.getGlobalTransform(qe.get(),t);return e=s.apply(i,e),qe.return(s),e},toLocal(i,e,t,s){e&&(i=e.toGlobal(i,t,s));const r=this.getGlobalTransform(qe.get(),s);return t=r.applyInverse(i,t),qe.return(r),t}};class Zr{constructor(){this.uid=be("instructionSet"),this.instructions=[],this.instructionSize=0,this.renderables=[],this.gcTick=0}reset(){this.instructionSize=0}destroy(){this.instructions.length=0,this.renderables.length=0,this.renderPipes=null,this.gcTick=0}add(e){this.instructions[this.instructionSize++]=e}log(){this.instructions.length=this.instructionSize,console.table(this.instructions,["type","action"])}}let vp=0;class xp{constructor(e){this._poolKeyHash=Object.create(null),this._texturePool={},this.textureOptions=e||{},this.enableFullScreen=!1,this.textureStyle=new Fr(this.textureOptions)}createTexture(e,t,s,r){const n=new De({...this.textureOptions,width:e,height:t,resolution:1,antialias:s,autoGarbageCollect:!1,autoGenerateMipmaps:r});return new j({source:n,label:`texturePool_${vp++}`})}getOptimalTexture(e,t,s=1,r,n=!1){let o=Math.ceil(e*s-1e-6),a=Math.ceil(t*s-1e-6);o=Gi(o),a=Gi(a);const l=r?1:0,c=n?1:0,h=(o<<17)+(a<<2)+(c<<1)+l;this._texturePool[h]||(this._texturePool[h]=[]);let u=this._texturePool[h].pop();return u||(u=this.createTexture(o,a,r,n)),u.source._resolution=s,u.source.width=o/s,u.source.height=a/s,u.source.pixelWidth=o,u.source.pixelHeight=a,u.frame.x=0,u.frame.y=0,u.frame.width=e,u.frame.height=t,u.updateUvs(),this._poolKeyHash[u.uid]=h,u}getSameSizeTexture(e,t=!1){const s=e.source;return this.getOptimalTexture(e.width,e.height,s._resolution,t)}returnTexture(e,t=!1){const s=this._poolKeyHash[e.uid];t&&(e.source.style=this.textureStyle),this._texturePool[s].push(e)}clear(e){if(e=e!==!1,e)for(const t in this._texturePool){const s=this._texturePool[t];if(s)for(let r=0;r<s.length;r++)s[r].destroy(!0)}this._texturePool={}}}const Qe=new xp;ms.register(Qe);class Jr{constructor(){this.renderPipeId="renderGroup",this.root=null,this.canBundle=!1,this.renderGroupParent=null,this.renderGroupChildren=[],this.worldTransform=new H,this.worldColorAlpha=4294967295,this.worldColor=16777215,this.worldAlpha=1,this.childrenToUpdate=Object.create(null),this.updateTick=0,this.gcTick=0,this.childrenRenderablesToUpdate={list:[],index:0},this.structureDidChange=!0,this.instructionSet=new Zr,this._onRenderContainers=[],this.textureNeedsUpdate=!0,this.isCachedAsTexture=!1,this._matrixDirty=7}init(e){this.root=e,e._onRender&&this.addOnRender(e),e.didChange=!0;const t=e.children;for(let s=0;s<t.length;s++){const r=t[s];r._updateFlags=15,this.addChild(r)}}enableCacheAsTexture(e={}){this.textureOptions=e,this.isCachedAsTexture=!0,this.textureNeedsUpdate=!0}disableCacheAsTexture(){this.isCachedAsTexture=!1,this.texture&&(Qe.returnTexture(this.texture,!0),this.texture=null)}updateCacheTexture(){this.textureNeedsUpdate=!0;const e=this._parentCacheAsTextureRenderGroup;e&&!e.textureNeedsUpdate&&e.updateCacheTexture()}reset(){this.renderGroupChildren.length=0;for(const e in this.childrenToUpdate){const t=this.childrenToUpdate[e];t.list.fill(null),t.index=0}this.childrenRenderablesToUpdate.index=0,this.childrenRenderablesToUpdate.list.fill(null),this.root=null,this.updateTick=0,this.structureDidChange=!0,this._onRenderContainers.length=0,this.renderGroupParent=null,this.disableCacheAsTexture()}get localTransform(){return this.root.localTransform}addRenderGroupChild(e){e.renderGroupParent&&e.renderGroupParent._removeRenderGroupChild(e),e.renderGroupParent=this,this.renderGroupChildren.push(e)}_removeRenderGroupChild(e){const t=this.renderGroupChildren.indexOf(e);t>-1&&this.renderGroupChildren.splice(t,1),e.renderGroupParent=null}addChild(e){if(this.structureDidChange=!0,e.parentRenderGroup=this,e.updateTick=-1,e.parent===this.root?e.relativeRenderGroupDepth=1:e.relativeRenderGroupDepth=e.parent.relativeRenderGroupDepth+1,e.didChange=!0,this.onChildUpdate(e),e.renderGroup){this.addRenderGroupChild(e.renderGroup);return}e._onRender&&this.addOnRender(e);const t=e.children;for(let s=0;s<t.length;s++)this.addChild(t[s])}removeChild(e){if(this.structureDidChange=!0,e._onRender&&(e.renderGroup||this.removeOnRender(e)),e.parentRenderGroup=null,e.renderGroup){this._removeRenderGroupChild(e.renderGroup);return}const t=e.children;for(let s=0;s<t.length;s++)this.removeChild(t[s])}removeChildren(e){for(let t=0;t<e.length;t++)this.removeChild(e[t])}onChildUpdate(e){let t=this.childrenToUpdate[e.relativeRenderGroupDepth];t||(t=this.childrenToUpdate[e.relativeRenderGroupDepth]={index:0,list:[]}),t.list[t.index++]=e}updateRenderable(e){e.globalDisplayStatus<7||(this.instructionSet.renderPipes[e.renderPipeId].updateRenderable(e),e.didViewUpdate=!1)}onChildViewUpdate(e){this.childrenRenderablesToUpdate.list[this.childrenRenderablesToUpdate.index++]=e}get isRenderable(){return this.root.localDisplayStatus===7&&this.worldAlpha>0}addOnRender(e){this._onRenderContainers.push(e)}removeOnRender(e){this._onRenderContainers.splice(this._onRenderContainers.indexOf(e),1)}runOnRender(e){for(let t=0;t<this._onRenderContainers.length;t++)this._onRenderContainers[t]._onRender(e)}destroy(){this.disableCacheAsTexture(),this.renderGroupParent=null,this.root=null,this.childrenRenderablesToUpdate=null,this.childrenToUpdate=null,this.renderGroupChildren=null,this._onRenderContainers=null,this.instructionSet=null}getChildren(e=[]){const t=this.root.children;for(let s=0;s<t.length;s++)this._getChildren(t[s],e);return e}_getChildren(e,t=[]){if(t.push(e),e.renderGroup)return t;const s=e.children;for(let r=0;r<s.length;r++)this._getChildren(s[r],t);return t}invalidateMatrices(){this._matrixDirty=7}get inverseWorldTransform(){return(this._matrixDirty&1)===0?this._inverseWorldTransform:(this._matrixDirty&=-2,this._inverseWorldTransform||(this._inverseWorldTransform=new H),this._inverseWorldTransform.copyFrom(this.worldTransform).invert())}get textureOffsetInverseTransform(){return(this._matrixDirty&2)===0?this._textureOffsetInverseTransform:(this._matrixDirty&=-3,this._textureOffsetInverseTransform||(this._textureOffsetInverseTransform=new H),this._textureOffsetInverseTransform.copyFrom(this.inverseWorldTransform).translate(-this._textureBounds.x,-this._textureBounds.y))}get inverseParentTextureTransform(){if((this._matrixDirty&4)===0)return this._inverseParentTextureTransform;this._matrixDirty&=-5;const e=this._parentCacheAsTextureRenderGroup;return e?(this._inverseParentTextureTransform||(this._inverseParentTextureTransform=new H),this._inverseParentTextureTransform.copyFrom(this.worldTransform).prepend(e.inverseWorldTransform).translate(-e._textureBounds.x,-e._textureBounds.y)):this.worldTransform}get cacheToLocalTransform(){return this.isCachedAsTexture?this.textureOffsetInverseTransform:this._parentCacheAsTextureRenderGroup?this._parentCacheAsTextureRenderGroup.textureOffsetInverseTransform:null}}function Cp(i,e,t={}){for(const s in e)!t[s]&&e[s]!==void 0&&(i[s]=e[s])}const Qr=new je(null),Hi=new je(null),en=new je(null,1,1),Vi=new je(null),zi=1,tn=2,js=4;class Ve extends lt{constructor(e={}){var t,s;super(),this.uid=be("renderable"),this._updateFlags=15,this.renderGroup=null,this.parentRenderGroup=null,this.parentRenderGroupIndex=0,this.didChange=!1,this.didViewUpdate=!1,this.relativeRenderGroupDepth=0,this.children=[],this.parent=null,this.includeInBuild=!0,this.measurable=!0,this.isSimple=!0,this.parentRenderLayer=null,this.updateTick=-1,this.localTransform=new H,this.relativeGroupTransform=new H,this.groupTransform=this.relativeGroupTransform,this.destroyed=!1,this._position=new je(this,0,0),this._scale=en,this._pivot=Hi,this._origin=Vi,this._skew=Qr,this._cx=1,this._sx=0,this._cy=0,this._sy=1,this._rotation=0,this.localColor=16777215,this.localAlpha=1,this.groupAlpha=1,this.groupColor=16777215,this.groupColorAlpha=4294967295,this.localBlendMode="inherit",this.groupBlendMode="normal",this.localDisplayStatus=7,this.globalDisplayStatus=7,this._didContainerChangeTick=0,this._didViewChangeTick=0,this._didLocalTransformChangeId=-1,this.effects=[],Cp(this,e,{children:!0,parent:!0,effects:!0}),(t=e.children)==null||t.forEach(r=>this.addChild(r)),(s=e.parent)==null||s.addChild(this)}static mixin(e){ee("8.8.0","Container.mixin is deprecated, please use extensions.mixin instead."),Q.mixin(Ve,e)}set _didChangeId(e){this._didViewChangeTick=e>>12&4095,this._didContainerChangeTick=e&4095}get _didChangeId(){return this._didContainerChangeTick&4095|(this._didViewChangeTick&4095)<<12}addChild(...e){if(this.allowChildren||ee(Be,"addChild: Only Containers will be allowed to add children in v8.0.0"),e.length>1){for(let r=0;r<e.length;r++)this.addChild(e[r]);return e[0]}const t=e[0],s=this.renderGroup||this.parentRenderGroup;return t.parent===this?(this.children.splice(this.children.indexOf(t),1),this.children.push(t),s&&(s.structureDidChange=!0),t):(t.parent&&t.parent.removeChild(t),this.children.push(t),this.sortableChildren&&(this.sortDirty=!0),t.parent=this,t.didChange=!0,t._updateFlags=15,s&&s.addChild(t),this.emit("childAdded",t,this,this.children.length-1),t.emit("added",this),this._didViewChangeTick++,t._zIndex!==0&&t.depthOfChildModified(),t)}removeChild(...e){if(e.length>1){for(let r=0;r<e.length;r++)this.removeChild(e[r]);return e[0]}const t=e[0],s=this.children.indexOf(t);return s>-1&&(this._didViewChangeTick++,this.children.splice(s,1),this.renderGroup?this.renderGroup.removeChild(t):this.parentRenderGroup&&this.parentRenderGroup.removeChild(t),t.parentRenderLayer&&t.parentRenderLayer.detach(t),t.parent=null,this.emit("childRemoved",t,this,s),t.emit("removed",this)),t}_onUpdate(e){e&&e===this._skew&&this._updateSkew(),this._didContainerChangeTick++,!this.didChange&&(this.didChange=!0,this.parentRenderGroup&&this.parentRenderGroup.onChildUpdate(this))}set isRenderGroup(e){!!this.renderGroup!==e&&(e?this.enableRenderGroup():this.disableRenderGroup())}get isRenderGroup(){return!!this.renderGroup}enableRenderGroup(){if(this.renderGroup)return;const e=this.parentRenderGroup;e==null||e.removeChild(this),this.renderGroup=Le.get(Jr,this),this.groupTransform=H.IDENTITY,e==null||e.addChild(this),this._updateIsSimple()}disableRenderGroup(){if(!this.renderGroup)return;const e=this.parentRenderGroup;e==null||e.removeChild(this),Le.return(this.renderGroup),this.renderGroup=null,this.groupTransform=this.relativeGroupTransform,e==null||e.addChild(this),this._updateIsSimple()}_updateIsSimple(){this.isSimple=!this.renderGroup&&this.effects.length===0}get worldTransform(){return this._worldTransform||(this._worldTransform=new H),this.renderGroup?this._worldTransform.copyFrom(this.renderGroup.worldTransform):this.parentRenderGroup&&this._worldTransform.appendFrom(this.relativeGroupTransform,this.parentRenderGroup.worldTransform),this._worldTransform}get x(){return this._position.x}set x(e){this._position.x=e}get y(){return this._position.y}set y(e){this._position.y=e}get position(){return this._position}set position(e){this._position.copyFrom(e)}get rotation(){return this._rotation}set rotation(e){this._rotation!==e&&(this._rotation=e,this._onUpdate(this._skew))}get angle(){return this.rotation*Ff}set angle(e){this.rotation=e*Lf}get pivot(){return this._pivot===Hi&&(this._pivot=new je(this,0,0)),this._pivot}set pivot(e){this._pivot===Hi&&(this._pivot=new je(this,0,0),this._origin!==Vi&&ie("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof e=="number"?this._pivot.set(e):this._pivot.copyFrom(e)}get skew(){return this._skew===Qr&&(this._skew=new je(this,0,0)),this._skew}set skew(e){this._skew===Qr&&(this._skew=new je(this,0,0)),this._skew.copyFrom(e)}get scale(){return this._scale===en&&(this._scale=new je(this,1,1)),this._scale}set scale(e){this._scale===en&&(this._scale=new je(this,0,0)),typeof e=="string"&&(e=parseFloat(e)),typeof e=="number"?this._scale.set(e):this._scale.copyFrom(e)}get origin(){return this._origin===Vi&&(this._origin=new je(this,0,0)),this._origin}set origin(e){this._origin===Vi&&(this._origin=new je(this,0,0),this._pivot!==Hi&&ie("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof e=="number"?this._origin.set(e):this._origin.copyFrom(e)}get width(){return Math.abs(this.scale.x*this.getLocalBounds().width)}set width(e){const t=this.getLocalBounds().width;this._setWidth(e,t)}get height(){return Math.abs(this.scale.y*this.getLocalBounds().height)}set height(e){const t=this.getLocalBounds().height;this._setHeight(e,t)}getSize(e){e||(e={});const t=this.getLocalBounds();return e.width=Math.abs(this.scale.x*t.width),e.height=Math.abs(this.scale.y*t.height),e}setSize(e,t){const s=this.getLocalBounds();typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,s.width),t!==void 0&&this._setHeight(t,s.height)}_updateSkew(){const e=this._rotation,t=this._skew;this._cx=Math.cos(e+t._y),this._sx=Math.sin(e+t._y),this._cy=-Math.sin(e-t._x),this._sy=Math.cos(e-t._x)}updateTransform(e){return this.position.set(typeof e.x=="number"?e.x:this.position.x,typeof e.y=="number"?e.y:this.position.y),this.scale.set(typeof e.scaleX=="number"?e.scaleX||1:this.scale.x,typeof e.scaleY=="number"?e.scaleY||1:this.scale.y),this.rotation=typeof e.rotation=="number"?e.rotation:this.rotation,this.skew.set(typeof e.skewX=="number"?e.skewX:this.skew.x,typeof e.skewY=="number"?e.skewY:this.skew.y),this.pivot.set(typeof e.pivotX=="number"?e.pivotX:this.pivot.x,typeof e.pivotY=="number"?e.pivotY:this.pivot.y),this.origin.set(typeof e.originX=="number"?e.originX:this.origin.x,typeof e.originY=="number"?e.originY:this.origin.y),this}setFromMatrix(e){e.decompose(this)}updateLocalTransform(){const e=this._didContainerChangeTick;if(this._didLocalTransformChangeId===e)return;this._didLocalTransformChangeId=e;const t=this.localTransform,s=this._scale,r=this._pivot,n=this._origin,o=this._position,a=s._x,l=s._y,c=r._x,h=r._y,u=-n._x,p=-n._y;t.a=this._cx*a,t.b=this._sx*a,t.c=this._cy*l,t.d=this._sy*l,t.tx=o._x-(c*t.a+h*t.c)+(u*t.a+p*t.c)-u,t.ty=o._y-(c*t.b+h*t.d)+(u*t.b+p*t.d)-p}set alpha(e){e!==this.localAlpha&&(this.localAlpha=e,this._updateFlags|=zi,this._onUpdate())}get alpha(){return this.localAlpha}set tint(e){const s=Pe.shared.setValue(e??16777215).toBgrNumber();s!==this.localColor&&(this.localColor=s,this._updateFlags|=zi,this._onUpdate())}get tint(){return _s(this.localColor)}set blendMode(e){this.localBlendMode!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=tn,this.localBlendMode=e,this._onUpdate())}get blendMode(){return this.localBlendMode}get visible(){return!!(this.localDisplayStatus&2)}set visible(e){const t=e?2:0;(this.localDisplayStatus&2)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=js,this.localDisplayStatus^=2,this._onUpdate(),this.emit("visibleChanged",e))}get culled(){return!(this.localDisplayStatus&4)}set culled(e){const t=e?0:4;(this.localDisplayStatus&4)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=js,this.localDisplayStatus^=4,this._onUpdate())}get renderable(){return!!(this.localDisplayStatus&1)}set renderable(e){const t=e?1:0;(this.localDisplayStatus&1)!==t&&(this._updateFlags|=js,this.localDisplayStatus^=1,this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._onUpdate())}get isRenderable(){return this.localDisplayStatus===7&&this.groupAlpha>0}destroy(e=!1){var r;if(this.destroyed)return;this.destroyed=!0;let t;if(this.children.length&&(t=this.removeChildren(0,this.children.length)),this.removeFromParent(),this.parent=null,this._maskEffect=null,this._filterEffect=null,this.effects=null,this._position=null,this._scale=null,this._pivot=null,this._origin=null,this._skew=null,this.emit("destroyed",this),this.removeAllListeners(),(typeof e=="boolean"?e:e==null?void 0:e.children)&&t)for(let n=0;n<t.length;++n)t[n].destroy(e);(r=this.renderGroup)==null||r.destroy(),this.renderGroup=null}}Q.mixin(Ve,op,dp,bp,gp,mp,cp,hp,_p,sp,np,fp,ap);class Da extends Ve{constructor(e){super(e),this.canBundle=!0,this.allowChildren=!1,this._roundPixels=0,this._lastUsed=-1,this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this._bounds=new Ye(0,1,0,0),this._boundsDirty=!0,this.autoGarbageCollect=e.autoGarbageCollect??!0}get bounds(){return this._boundsDirty?(this.updateBounds(),this._boundsDirty=!1,this._bounds):this._bounds}get roundPixels(){return!!this._roundPixels}set roundPixels(e){this._roundPixels=e?1:0}containsPoint(e){const t=this.bounds,{x:s,y:r}=e;return s>=t.minX&&s<=t.maxX&&r>=t.minY&&r<=t.maxY}onViewUpdate(){if(this._didViewChangeTick++,this._boundsDirty=!0,this.didViewUpdate)return;this.didViewUpdate=!0;const e=this.renderGroup||this.parentRenderGroup;e&&e.onChildViewUpdate(this)}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null),this.onViewUpdate()}destroy(e){this.unload(),super.destroy(e),this._bounds=null}collectRenderablesSimple(e,t,s){const{renderPipes:r}=t;r.blendMode.pushBlendMode(this,this.groupBlendMode,e);const o=r[this.renderPipeId];o!=null&&o.addRenderable&&o.addRenderable(this,e),this.didViewUpdate=!1;const a=this.children,l=a.length;for(let c=0;c<l;c++)a[c].collectRenderables(e,t,s);r.blendMode.popBlendMode(e)}}class Dt extends Da{constructor(e=j.EMPTY){e instanceof j&&(e={texture:e});const{texture:t=j.EMPTY,anchor:s,roundPixels:r,width:n,height:o,...a}=e;super({label:"Sprite",...a}),this.renderPipeId="sprite",this.batched=!0,this._visualBounds={minX:0,maxX:1,minY:0,maxY:0},this._anchor=new je({_onUpdate:()=>{this.onViewUpdate()}}),s?this.anchor=s:t.defaultAnchor&&(this.anchor=t.defaultAnchor),this.texture=t,this.allowChildren=!1,this.roundPixels=r??!1,n!==void 0&&(this.width=n),o!==void 0&&(this.height=o)}static from(e,t=!1){return e instanceof j?new Dt(e):new Dt(j.from(e,t))}set texture(e){e||(e=j.EMPTY);const t=this._texture;t!==e&&(t&&t.dynamic&&t.off("update",this.onViewUpdate,this),e.dynamic&&e.on("update",this.onViewUpdate,this),this._texture=e,this._width&&this._setWidth(this._width,this._texture.orig.width),this._height&&this._setHeight(this._height,this._texture.orig.height),this.onViewUpdate())}get texture(){return this._texture}get visualBounds(){return jf(this._visualBounds,this._anchor,this._texture),this._visualBounds}get sourceBounds(){return ee("8.6.1","Sprite.sourceBounds is deprecated, use visualBounds instead."),this.visualBounds}updateBounds(){const e=this._anchor,t=this._texture,s=this._bounds,{width:r,height:n}=t.orig;s.minX=-e._x*r,s.maxX=s.minX+r,s.minY=-e._y*n,s.maxY=s.minY+n}destroy(e=!1){if(super.destroy(e),typeof e=="boolean"?e:e==null?void 0:e.texture){const s=typeof e=="boolean"?e:e==null?void 0:e.textureSource;this._texture.destroy(s)}this._texture=null,this._visualBounds=null,this._bounds=null,this._anchor=null}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(e){this._setWidth(e,this._texture.orig.width),this._width=e}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(e){this._setHeight(e,this._texture.orig.height),this._height=e}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this._texture.orig.width,e.height=Math.abs(this.scale.y)*this._texture.orig.height,e}setSize(e,t){typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,this._texture.orig.width),t!==void 0&&this._setHeight(t,this._texture.orig.height)}}const Ep=new Ye;function Na(i,e,t){const s=Ep;i.measurable=!0,Yr(i,t,s),e.addBoundsMask(s),i.measurable=!1}function Ua(i,e,t){const s=Tt.get();i.measurable=!0;const r=qe.get().identity(),n=Ga(i,t,r);Kr(i,s,n),i.measurable=!1,e.addBoundsMask(s),qe.return(r),Tt.return(s)}function Ga(i,e,t){return i?(i!==e&&(Ga(i.parent,e,t),i.updateLocalTransform(),t.append(i.localTransform)),t):(ie("Mask bounds, renderable is not inside the root container"),t)}class Fa{constructor(e){this.priority=0,this.inverse=!1,this.pipe="alphaMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e,this.renderMaskToTexture=!(e instanceof Dt),this.mask.renderable=this.renderMaskToTexture,this.mask.includeInBuild=!this.renderMaskToTexture,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask=null)}addBounds(e,t){this.inverse||Na(this.mask,e,t)}addLocalBounds(e,t){Ua(this.mask,e,t)}containsPoint(e,t){const s=this.mask;return t(s,e)}destroy(){this.reset()}static test(e){return e instanceof Dt}}Fa.extension=A.MaskEffect;class La{constructor(e){this.priority=0,this.pipe="colorMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e}destroy(){}static test(e){return typeof e=="number"}}La.extension=A.MaskEffect;class Wa{constructor(e){this.priority=0,this.pipe="stencilMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e,this.mask.includeInBuild=!1,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask.includeInBuild=!0,this.mask=null)}addBounds(e,t){Na(this.mask,e,t)}addLocalBounds(e,t){Ua(this.mask,e,t)}containsPoint(e,t){const s=this.mask;return t(s,e)}destroy(){this.reset()}static test(e){return e instanceof Ve}}Wa.extension=A.MaskEffect;let Ha={createCanvas:(i,e)=>{const t=document.createElement("canvas");return t.width=i,t.height=e,t},createImage:()=>new Image,getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(i,e)=>fetch(i,e),parseXML:i=>new DOMParser().parseFromString(i,"text/xml")};const pe={get(){return Ha},set(i){Ha=i}};class mt extends De{constructor(e){e.resource||(e.resource=pe.get().createCanvas()),e.width||(e.width=e.resource.width,e.autoDensity||(e.width/=e.resolution)),e.height||(e.height=e.resource.height,e.autoDensity||(e.height/=e.resolution)),super(e),this.uploadMethodId="image",this.autoDensity=e.autoDensity,this.resizeCanvas(),this.transparent=!!e.transparent}resizeCanvas(){this.autoDensity&&"style"in this.resource&&(this.resource.style.width=`${this.width}px`,this.resource.style.height=`${this.height}px`),(this.resource.width!==this.pixelWidth||this.resource.height!==this.pixelHeight)&&(this.resource.width=this.pixelWidth,this.resource.height=this.pixelHeight)}resize(e=this.width,t=this.height,s=this._resolution){const r=super.resize(e,t,s);return r&&this.resizeCanvas(),r}static test(e){return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement||globalThis.OffscreenCanvas&&e instanceof OffscreenCanvas}get context2D(){return this._context2D||(this._context2D=this.resource.getContext("2d"))}}mt.extension=A.TextureSource;class $i extends De{constructor(e){super(e),this.uploadMethodId="image",this.autoGarbageCollect=!0}static test(e){return globalThis.HTMLImageElement&&e instanceof HTMLImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||globalThis.VideoFrame&&e instanceof VideoFrame}}$i.extension=A.TextureSource;var ys=(i=>(i[i.INTERACTION=50]="INTERACTION",i[i.HIGH=25]="HIGH",i[i.NORMAL=0]="NORMAL",i[i.LOW=-25]="LOW",i[i.UTILITY=-50]="UTILITY",i))(ys||{});class sn{constructor(e,t=null,s=0,r=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=e,this._context=t,this.priority=s,this._once=r}match(e,t=null){return this._fn===e&&this._context===t}emit(e){this._fn&&(this._context?this._fn.call(this._context,e):this._fn(e));const t=this.next;return this._once&&this.destroy(!0),this._destroyed&&(this.next=null),t}connect(e){this.previous=e,e.next&&(e.next.previous=this),this.next=e.next,e.next=this}destroy(e=!1){this._destroyed=!0,this._fn=null,this._context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);const t=this.next;return this.next=e?null:t,this.previous=null,t}}const Va=class nt{constructor(){this.autoStart=!1,this.deltaTime=1,this.lastTime=-1,this.speed=1,this.started=!1,this._requestId=null,this._maxElapsedMS=100,this._minElapsedMS=0,this._protected=!1,this._lastFrame=-1,this._head=new sn(null,null,1/0),this.deltaMS=1/nt.targetFPMS,this.elapsedMS=1/nt.targetFPMS,this._tick=e=>{this._requestId=null,this.started&&(this.update(e),this.started&&this._requestId===null&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){this._requestId===null&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){this._requestId!==null&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(e,t,s=ys.NORMAL){return this._addListener(new sn(e,t,s))}addOnce(e,t,s=ys.NORMAL){return this._addListener(new sn(e,t,s,!0))}_addListener(e){let t=this._head.next,s=this._head;if(!t)e.connect(s);else{for(;t;){if(e.priority>t.priority){e.connect(s);break}s=t,t=t.next}e.previous||e.connect(s)}return this._startIfPossible(),this}remove(e,t){let s=this._head.next;for(;s;)s.match(e,t)?s=s.destroy():s=s.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let e=0,t=this._head;for(;t=t.next;)e++;return e}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let e=this._head.next;for(;e;)e=e.destroy(!0);this._head.destroy(),this._head=null}}update(e=performance.now()){let t;if(e>this.lastTime){if(t=this.elapsedMS=e-this.lastTime,t>this._maxElapsedMS&&(t=this._maxElapsedMS),t*=this.speed,this._minElapsedMS){const n=e-this._lastFrame|0;if(n<this._minElapsedMS)return;this._lastFrame=e-n%this._minElapsedMS}this.deltaMS=t,this.deltaTime=this.deltaMS*nt.targetFPMS;const s=this._head;let r=s.next;for(;r;)r=r.emit(this);s.next||this._cancelIfNeeded()}else this.deltaTime=this.deltaMS=this.elapsedMS=0;this.lastTime=e}get FPS(){return 1e3/this.elapsedMS}get minFPS(){return 1e3/this._maxElapsedMS}set minFPS(e){const t=Math.min(Math.max(0,e)/1e3,nt.targetFPMS);this._maxElapsedMS=1/t,this._minElapsedMS&&e>this.maxFPS&&(this.maxFPS=e)}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(e){e===0?this._minElapsedMS=0:(e<this.minFPS&&(this.minFPS=e),this._minElapsedMS=1/(e/1e3))}static get shared(){if(!nt._shared){const e=nt._shared=new nt;e.autoStart=!0,e._protected=!0}return nt._shared}static get system(){if(!nt._system){const e=nt._system=new nt;e.autoStart=!0,e._protected=!0}return nt._system}};Va.targetFPMS=.06;let at=Va,rn;async function Sp(){return rn??(rn=(async()=>{var o;const e=pe.get().createCanvas(1,1).getContext("webgl");if(!e)return"premultiply-alpha-on-upload";const t=await new Promise(a=>{const l=document.createElement("video");l.onloadeddata=()=>a(l),l.onerror=()=>a(null),l.autoplay=!1,l.crossOrigin="anonymous",l.preload="auto",l.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",l.load()});if(!t)return"premultiply-alpha-on-upload";const s=e.createTexture();e.bindTexture(e.TEXTURE_2D,s);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.NONE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t);const n=new Uint8Array(4);return e.readPixels(0,0,1,1,e.RGBA,e.UNSIGNED_BYTE,n),e.deleteFramebuffer(r),e.deleteTexture(s),(o=e.getExtension("WEBGL_lose_context"))==null||o.loseContext(),n[0]<=n[3]?"premultiplied-alpha":"premultiply-alpha-on-upload"})()),rn}const ji=class cf extends De{constructor(e){super(e),this.isReady=!1,this.uploadMethodId="video",e={...cf.defaultOptions,...e},this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=e.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=e.autoPlay!==!1,this.alphaMode=e.alphaMode??"premultiply-alpha-on-upload",this._videoFrameRequestCallback=this._videoFrameRequestCallback.bind(this),this._videoFrameRequestCallbackHandle=null,this._load=null,this._resolve=null,this._reject=null,this._onCanPlay=this._onCanPlay.bind(this),this._onCanPlayThrough=this._onCanPlayThrough.bind(this),this._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),e.autoLoad!==!1&&this.load()}updateFrame(){if(!this.destroyed){if(this._updateFPS){const e=at.shared.elapsedMS*this.resource.playbackRate;this._msToNextUpdate=Math.floor(this._msToNextUpdate-e)}(!this._updateFPS||this._msToNextUpdate<=0)&&(this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0),this.isValid&&this.update()}}_videoFrameRequestCallback(){this.updateFrame(),this.destroyed?this._videoFrameRequestCallbackHandle=null:this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback)}get isValid(){return!!this.resource.videoWidth&&!!this.resource.videoHeight}async load(){if(this._load)return this._load;const e=this.resource,t=this.options;return(e.readyState===e.HAVE_ENOUGH_DATA||e.readyState===e.HAVE_FUTURE_DATA)&&e.width&&e.height&&(e.complete=!0),e.addEventListener("play",this._onPlayStart),e.addEventListener("pause",this._onPlayStop),e.addEventListener("seeked",this._onSeeked),this._isSourceReady()?this._mediaReady():(t.preload||e.addEventListener("canplay",this._onCanPlay),e.addEventListener("canplaythrough",this._onCanPlayThrough),e.addEventListener("error",this._onError,!0)),this.alphaMode=await Sp(),this._load=new Promise((s,r)=>{this.isValid?s(this):(this._resolve=s,this._reject=r,t.preloadTimeoutMs!==void 0&&(this._preloadTimeout=setTimeout(()=>{this._onError(new ErrorEvent(`Preload exceeded timeout of ${t.preloadTimeoutMs}ms`))})),e.load())}),this._load}_onError(e){this.resource.removeEventListener("error",this._onError,!0),this.emit("error",e),this._reject&&(this._reject(e),this._reject=null,this._resolve=null)}_isSourcePlaying(){const e=this.resource;return!e.paused&&!e.ended}_isSourceReady(){return this.resource.readyState>2}_onPlayStart(){this.isValid||this._mediaReady(),this._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0)}_onCanPlay(){this.resource.removeEventListener("canplay",this._onCanPlay),this._mediaReady()}_onCanPlayThrough(){this.resource.removeEventListener("canplaythrough",this._onCanPlay),this._preloadTimeout&&(clearTimeout(this._preloadTimeout),this._preloadTimeout=void 0),this._mediaReady()}_mediaReady(){const e=this.resource;this.isValid&&(this.isReady=!0,this.resize(e.videoWidth,e.videoHeight)),this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0,this._resolve&&(this._resolve(this),this._resolve=null,this._reject=null),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.resource.play()}destroy(){this._configureAutoUpdate();const e=this.resource;e&&(e.removeEventListener("play",this._onPlayStart),e.removeEventListener("pause",this._onPlayStop),e.removeEventListener("seeked",this._onSeeked),e.removeEventListener("canplay",this._onCanPlay),e.removeEventListener("canplaythrough",this._onCanPlayThrough),e.removeEventListener("error",this._onError,!0),e.pause(),e.src="",e.load()),super.destroy()}get autoUpdate(){return this._autoUpdate}set autoUpdate(e){e!==this._autoUpdate&&(this._autoUpdate=e,this._configureAutoUpdate())}get updateFPS(){return this._updateFPS}set updateFPS(e){e!==this._updateFPS&&(this._updateFPS=e,this._configureAutoUpdate())}_configureAutoUpdate(){this._autoUpdate&&this._isSourcePlaying()?!this._updateFPS&&this.resource.requestVideoFrameCallback?(this._isConnectedToTicker&&(at.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0),this._videoFrameRequestCallbackHandle===null&&(this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback))):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker||(at.shared.add(this.updateFrame,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(at.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(e){return globalThis.HTMLVideoElement&&e instanceof HTMLVideoElement}};ji.extension=A.TextureSource,ji.defaultOptions={...De.defaultOptions,autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1},ji.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let Tp=ji;const bs=(i,e,t=!1)=>(Array.isArray(i)||(i=[i]),e?i.map(s=>typeof s=="string"||t?e(s):s):i);class Ap{constructor(){this._parsers=[],this._cache=new Map,this._cacheMap=new Map}reset(){this._cacheMap.clear(),this._cache.clear()}has(e){return this._cache.has(e)}get(e){const t=this._cache.get(e);return t||ie(`[Assets] Asset id ${e} was not found in the Cache`),t}set(e,t){const s=bs(e);let r;for(let l=0;l<this.parsers.length;l++){const c=this.parsers[l];if(c.test(t)){r=c.getCacheableAssets(s,t);break}}const n=new Map(Object.entries(r||{}));r||s.forEach(l=>{n.set(l,t)});const o=[...n.keys()],a={cacheKeys:o,keys:s};s.forEach(l=>{this._cacheMap.set(l,a)}),o.forEach(l=>{const c=r?r[l]:t;this._cache.has(l)&&this._cache.get(l)!==c&&ie("[Cache] already has key:",l),this._cache.set(l,n.get(l))})}remove(e){if(!this._cacheMap.has(e)){ie(`[Assets] Asset id ${e} was not found in the Cache`);return}const t=this._cacheMap.get(e);t.cacheKeys.forEach(r=>{this._cache.delete(r)}),t.keys.forEach(r=>{this._cacheMap.delete(r)})}get parsers(){return this._parsers}}const vs=new Ap,nn=[];Q.handleByList(A.TextureSource,nn);function za(i={}){const e=i&&i.resource,t=e?i.resource:i,s=e?i:{resource:i};for(let r=0;r<nn.length;r++){const n=nn[r];if(n.test(t))return new n(s)}throw new Error(`Could not find a source type for resource: ${s.resource}`)}function wp(i={},e=!1){const t=i&&i.resource,s=t?i.resource:i,r=t?i:{resource:i};if(!e&&vs.has(s))return vs.get(s);const n=new j({source:za(r)});return n.on("destroy",()=>{vs.has(s)&&vs.remove(s)}),e||vs.set(s,n),n}function Ip(i,e=!1){return typeof i=="string"?vs.get(i):i instanceof De?new j({source:i}):wp(i,e)}j.from=Ip,De.from=za,Q.add(Fa,La,Wa,Tp,$i,mt,Lr);var $a=(i=>(i[i.Low=0]="Low",i[i.Normal=1]="Normal",i[i.High=2]="High",i))($a||{});function ct(i){if(typeof i!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(i)}`)}function Xs(i){return i.split("?")[0].split("#")[0]}function Rp(i){return i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Mp(i,e,t){return i.replace(new RegExp(Rp(e),"g"),t)}function Pp(i,e){let t="",s=0,r=-1,n=0,o=-1;for(let a=0;a<=i.length;++a){if(a<i.length)o=i.charCodeAt(a);else{if(o===47)break;o=47}if(o===47){if(!(r===a-1||n===1))if(r!==a-1&&n===2){if(t.length<2||s!==2||t.charCodeAt(t.length-1)!==46||t.charCodeAt(t.length-2)!==46){if(t.length>2){const l=t.lastIndexOf("/");if(l!==t.length-1){l===-1?(t="",s=0):(t=t.slice(0,l),s=t.length-1-t.lastIndexOf("/")),r=a,n=0;continue}}else if(t.length===2||t.length===1){t="",s=0,r=a,n=0;continue}}}else t.length>0?t+=`/${i.slice(r+1,a)}`:t=i.slice(r+1,a),s=a-r-1;r=a,n=0}else o===46&&n!==-1?++n:n=-1}return t}const Ys={toPosix(i){return Mp(i,"\\","/")},isUrl(i){return/^https?:/.test(this.toPosix(i))},isDataUrl(i){return/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(i)},isBlobUrl(i){return i.startsWith("blob:")},hasProtocol(i){return/^[^/:]+:/.test(this.toPosix(i))},getProtocol(i){ct(i),i=this.toPosix(i);const e=/^file:\/\/\//.exec(i);if(e)return e[0];const t=/^[^/:]+:\/{0,2}/.exec(i);return t?t[0]:""},toAbsolute(i,e,t){if(ct(i),this.isDataUrl(i)||this.isBlobUrl(i))return i;const s=Xs(this.toPosix(e??pe.get().getBaseUrl())),r=Xs(this.toPosix(t??this.rootname(s)));return i=this.toPosix(i),i.startsWith("/")?Ys.join(r,i.slice(1)):this.isAbsolute(i)?i:this.join(s,i)},normalize(i){if(ct(i),i.length===0)return".";if(this.isDataUrl(i)||this.isBlobUrl(i))return i;i=this.toPosix(i);let e="";const t=i.startsWith("/");this.hasProtocol(i)&&(e=this.rootname(i),i=i.slice(e.length));const s=i.endsWith("/");return i=Pp(i),i.length>0&&s&&(i+="/"),t?`/${i}`:e+i},isAbsolute(i){return ct(i),i=this.toPosix(i),this.hasProtocol(i)?!0:i.startsWith("/")},join(...i){if(i.length===0)return".";let e;for(let t=0;t<i.length;++t){const s=i[t];if(ct(s),s.length>0)if(e===void 0)e=s;else{const r=i[t-1]??"";this.joinExtensions.includes(this.extname(r).toLowerCase())?e+=`/../${s}`:e+=`/${s}`}}return e===void 0?".":this.normalize(e)},dirname(i){if(ct(i),i.length===0)return".";i=this.toPosix(i);let e=i.charCodeAt(0);const t=e===47;let s=-1,r=!0;const n=this.getProtocol(i),o=i;i=i.slice(n.length);for(let a=i.length-1;a>=1;--a)if(e=i.charCodeAt(a),e===47){if(!r){s=a;break}}else r=!1;return s===-1?t?"/":this.isUrl(o)?n+i:n:t&&s===1?"//":n+i.slice(0,s)},rootname(i){ct(i),i=this.toPosix(i);let e="";if(i.startsWith("/")?e="/":e=this.getProtocol(i),this.isUrl(i)){const t=i.indexOf("/",e.length);t!==-1?e=i.slice(0,t):e=i,e.endsWith("/")||(e+="/")}return e},basename(i,e){ct(i),e&&ct(e),i=Xs(this.toPosix(i));let t=0,s=-1,r=!0,n;if(e!==void 0&&e.length>0&&e.length<=i.length){if(e.length===i.length&&e===i)return"";let o=e.length-1,a=-1;for(n=i.length-1;n>=0;--n){const l=i.charCodeAt(n);if(l===47){if(!r){t=n+1;break}}else a===-1&&(r=!1,a=n+1),o>=0&&(l===e.charCodeAt(o)?--o===-1&&(s=n):(o=-1,s=a))}return t===s?s=a:s===-1&&(s=i.length),i.slice(t,s)}for(n=i.length-1;n>=0;--n)if(i.charCodeAt(n)===47){if(!r){t=n+1;break}}else s===-1&&(r=!1,s=n+1);return s===-1?"":i.slice(t,s)},extname(i){ct(i),i=Xs(this.toPosix(i));let e=-1,t=0,s=-1,r=!0,n=0;for(let o=i.length-1;o>=0;--o){const a=i.charCodeAt(o);if(a===47){if(!r){t=o+1;break}continue}s===-1&&(r=!1,s=o+1),a===46?e===-1?e=o:n!==1&&(n=1):e!==-1&&(n=-1)}return e===-1||s===-1||n===0||n===1&&e===s-1&&e===t+1?"":i.slice(e,s)},parse(i){ct(i);const e={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return e;i=Xs(this.toPosix(i));let t=i.charCodeAt(0);const s=this.isAbsolute(i);let r;e.root=this.rootname(i),s||this.hasProtocol(i)?r=1:r=0;let n=-1,o=0,a=-1,l=!0,c=i.length-1,h=0;for(;c>=r;--c){if(t=i.charCodeAt(c),t===47){if(!l){o=c+1;break}continue}a===-1&&(l=!1,a=c+1),t===46?n===-1?n=c:h!==1&&(h=1):n!==-1&&(h=-1)}return n===-1||a===-1||h===0||h===1&&n===a-1&&n===o+1?a!==-1&&(o===0&&s?e.base=e.name=i.slice(1,a):e.base=e.name=i.slice(o,a)):(o===0&&s?(e.name=i.slice(1,n),e.base=i.slice(1,a)):(e.name=i.slice(o,n),e.base=i.slice(o,a)),e.ext=i.slice(n,a)),e.dir=this.dirname(i),e},sep:"/",delimiter:":",joinExtensions:[".html"]};function ja(i,e,t,s,r){const n=e[t];for(let o=0;o<n.length;o++){const a=n[o];t<e.length-1?ja(i.replace(s[t],a),e,t+1,s,r):r.push(i.replace(s[t],a))}}function kp(i){const e=/\{(.*?)\}/g,t=i.match(e),s=[];if(t){const r=[];t.forEach(n=>{const o=n.substring(1,n.length-1).split(",");r.push(o)}),ja(i,r,0,t,s)}else s.push(i);return s}const Xa=i=>!Array.isArray(i);class Ya{constructor(){this._defaultBundleIdentifierOptions={connector:"-",createBundleAssetId:(e,t)=>`${e}${this._bundleIdConnector}${t}`,extractAssetIdFromBundle:(e,t)=>t.replace(`${e}${this._bundleIdConnector}`,"")},this._bundleIdConnector=this._defaultBundleIdentifierOptions.connector,this._createBundleAssetId=this._defaultBundleIdentifierOptions.createBundleAssetId,this._extractAssetIdFromBundle=this._defaultBundleIdentifierOptions.extractAssetIdFromBundle,this._assetMap={},this._preferredOrder=[],this._parsers=[],this._resolverHash={},this._bundles={}}setBundleIdentifier(e){if(this._bundleIdConnector=e.connector??this._bundleIdConnector,this._createBundleAssetId=e.createBundleAssetId??this._createBundleAssetId,this._extractAssetIdFromBundle=e.extractAssetIdFromBundle??this._extractAssetIdFromBundle,this._extractAssetIdFromBundle("foo",this._createBundleAssetId("foo","bar"))!=="bar")throw new Error("[Resolver] GenerateBundleAssetId are not working correctly")}prefer(...e){e.forEach(t=>{this._preferredOrder.push(t),t.priority||(t.priority=Object.keys(t.params))}),this._resolverHash={}}set basePath(e){this._basePath=e}get basePath(){return this._basePath}set rootPath(e){this._rootPath=e}get rootPath(){return this._rootPath}get parsers(){return this._parsers}reset(){this.setBundleIdentifier(this._defaultBundleIdentifierOptions),this._assetMap={},this._preferredOrder=[],this._resolverHash={},this._rootPath=null,this._basePath=null,this._manifest=null,this._bundles={},this._defaultSearchParams=null}setDefaultSearchParams(e){if(typeof e=="string")this._defaultSearchParams=e;else{const t=e;this._defaultSearchParams=Object.keys(t).map(s=>`${encodeURIComponent(s)}=${encodeURIComponent(t[s])}`).join("&")}}getAlias(e){const{alias:t,src:s}=e;return bs(t||s,n=>typeof n=="string"?n:Array.isArray(n)?n.map(o=>(o==null?void 0:o.src)??o):n!=null&&n.src?n.src:n,!0)}removeAlias(e,t){this._assetMap[e]&&(t&&t!==this._resolverHash[e]||(delete this._resolverHash[e],delete this._assetMap[e]))}addManifest(e){this._manifest&&ie("[Resolver] Manifest already exists, this will be overwritten"),this._manifest=e,e.bundles.forEach(t=>{this.addBundle(t.name,t.assets)})}addBundle(e,t){const s=[];let r=t;Array.isArray(t)||(r=Object.entries(t).map(([n,o])=>typeof o=="string"||Array.isArray(o)?{alias:n,src:o}:{alias:n,...o})),r.forEach(n=>{const o=n.src,a=n.alias;let l;if(typeof a=="string"){const c=this._createBundleAssetId(e,a);s.push(c),l=[a,c]}else{const c=a.map(h=>this._createBundleAssetId(e,h));s.push(...c),l=[...a,...c]}this.add({...n,alias:l,src:o})}),this._bundles[e]=s}add(e){const t=[];Array.isArray(e)?t.push(...e):t.push(e);let s;s=n=>{this.hasKey(n)&&ie(`[Resolver] already has key: ${n} overwriting`)},bs(t).forEach(n=>{const{src:o}=n;let{data:a,format:l,loadParser:c,parser:h}=n;const u=bs(o).map(_=>typeof _=="string"?kp(_):Array.isArray(_)?_:[_]),p=this.getAlias(n);Array.isArray(p)?p.forEach(s):s(p);const d=[],g=_=>{const b=this._parsers.find(v=>v.test(_));return{src:_,...b==null?void 0:b.parse(_)}};u.forEach(_=>{_.forEach(b=>{let v={};if(typeof b!="object"?v=g(b):(a=b.data??a,l=b.format??l,(b.loadParser||b.parser)&&(c=b.loadParser??c,h=b.parser??h),v={...g(b.src),...b}),!p)throw new Error(`[Resolver] alias is undefined for this asset: ${v.src}`);v=this._buildResolvedAsset(v,{aliases:p,data:a,format:l,loadParser:c,parser:h,progressSize:n.progressSize}),d.push(v)})}),p.forEach(_=>{this._assetMap[_]=d})})}resolveBundle(e){const t=Xa(e);e=bs(e);const s={};return e.forEach(r=>{const n=this._bundles[r];if(n){const o=this.resolve(n),a={};for(const l in o){const c=o[l];a[this._extractAssetIdFromBundle(r,l)]=c}s[r]=a}}),t?s[e[0]]:s}resolveUrl(e){const t=this.resolve(e);if(typeof e!="string"){const s={};for(const r in t)s[r]=t[r].src;return s}return t.src}resolve(e){const t=Xa(e);e=bs(e);const s={};return e.forEach(r=>{if(!this._resolverHash[r])if(this._assetMap[r]){let n=this._assetMap[r];const o=this._getPreferredOrder(n);o==null||o.priority.forEach(a=>{o.params[a].forEach(l=>{const c=n.filter(h=>h[a]?h[a]===l:!1);c.length&&(n=c)})}),this._resolverHash[r]=n[0]}else this._resolverHash[r]=this._buildResolvedAsset({alias:[r],src:r},{});s[r]=this._resolverHash[r]}),t?s[e[0]]:s}hasKey(e){return!!this._assetMap[e]}hasBundle(e){return!!this._bundles[e]}_getPreferredOrder(e){for(let t=0;t<e.length;t++){const s=e[t],r=this._preferredOrder.find(n=>n.params.format.includes(s.format));if(r)return r}return this._preferredOrder[0]}_appendDefaultSearchParams(e){if(!this._defaultSearchParams)return e;const t=/\?/.test(e)?"&":"?";return`${e}${t}${this._defaultSearchParams}`}_buildResolvedAsset(e,t){const{aliases:s,data:r,loadParser:n,parser:o,format:a,progressSize:l}=t;return(this._basePath||this._rootPath)&&(e.src=Ys.toAbsolute(e.src,this._basePath,this._rootPath)),e.alias=s??e.alias??[e.src],e.src=this._appendDefaultSearchParams(e.src),e.data={...r||{},...e.data},e.loadParser=n??e.loadParser,e.parser=o??e.parser,e.format=a??e.format??Op(e.src),l!==void 0&&(e.progressSize=l),e}}Ya.RETINA_PREFIX=/@([0-9\.]+)x/;function Op(i){return i.split(".").pop().split("?").shift().split("#").shift()}const qa=(i,e)=>{const t=e.split("?")[1];return t&&(i+=`?${t}`),i},Ka=class Bi{constructor(e,t){this.linkedSheets=[];let s=e;(e==null?void 0:e.source)instanceof De&&(s={texture:e,data:t});const{texture:r,data:n,cachePrefix:o=""}=s;this.cachePrefix=o,this._texture=r instanceof j?r:null,this.textureSource=r.source,this.textures={},this.animations={},this.data=n;const a=parseFloat(n.meta.scale);a?(this.resolution=a,r.source.resolution=this.resolution):this.resolution=r.source._resolution,this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}parse(){return new Promise(e=>{this._callback=e,this._batchIndex=0,this._frameKeys.length<=Bi.BATCH_SIZE?(this._processFrames(0),this._processAnimations(),this._parseComplete()):this._nextBatch()})}parseSync(){return this._processFrames(0,!0),this._processAnimations(),this.textures}_processFrames(e,t=!1){let s=e;const r=t?1/0:Bi.BATCH_SIZE;for(;s-e<r&&s<this._frameKeys.length;){const n=this._frameKeys[s],o=this._frames[n],a=o.frame;if(a){let l=null,c=null;const h=o.trimmed!==!1&&o.sourceSize?o.sourceSize:o.frame,u=new Ce(0,0,Math.floor(h.w)/this.resolution,Math.floor(h.h)/this.resolution);o.rotated?l=new Ce(Math.floor(a.x)/this.resolution,Math.floor(a.y)/this.resolution,Math.floor(a.h)/this.resolution,Math.floor(a.w)/this.resolution):l=new Ce(Math.floor(a.x)/this.resolution,Math.floor(a.y)/this.resolution,Math.floor(a.w)/this.resolution,Math.floor(a.h)/this.resolution),o.trimmed!==!1&&o.spriteSourceSize&&(c=new Ce(Math.floor(o.spriteSourceSize.x)/this.resolution,Math.floor(o.spriteSourceSize.y)/this.resolution,Math.floor(a.w)/this.resolution,Math.floor(a.h)/this.resolution)),this.textures[n]=new j({source:this.textureSource,frame:l,orig:u,trim:c,rotate:o.rotated?2:0,defaultAnchor:o.anchor,defaultBorders:o.borders,label:n.toString()})}s++}}_processAnimations(){const e=this.data.animations||{};for(const t in e){this.animations[t]=[];for(let s=0;s<e[t].length;s++){const r=e[t][s];this.animations[t].push(this.textures[r])}}}_parseComplete(){const e=this._callback;this._callback=null,this._batchIndex=0,e.call(this,this.textures)}_nextBatch(){this._processFrames(this._batchIndex*Bi.BATCH_SIZE),this._batchIndex++,setTimeout(()=>{this._batchIndex*Bi.BATCH_SIZE<this._frameKeys.length?this._nextBatch():(this._processAnimations(),this._parseComplete())},0)}destroy(e=!1){var t;for(const s in this.textures)this.textures[s].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,e&&((t=this._texture)==null||t.destroy(),this.textureSource.destroy()),this._texture=null,this.textureSource=null,this.linkedSheets=[]}};Ka.BATCH_SIZE=1e3;let Za=Ka;const Bp=["jpg","png","jpeg","avif","webp","basis","etc2","bc7","bc6h","bc5","bc4","bc3","bc2","bc1","eac","astc"];function Ja(i,e,t){const s={};if(i.forEach(r=>{s[r]=e}),Object.keys(e.textures).forEach(r=>{s[`${e.cachePrefix}${r}`]=e.textures[r]}),!t){const r=Ys.dirname(i[0]);e.linkedSheets.forEach((n,o)=>{const a=Ja([`${r}/${e.data.meta.related_multi_packs[o]}`],n,!0);Object.assign(s,a)})}return s}const Dp={extension:A.Asset,cache:{test:i=>i instanceof Za,getCacheableAssets:(i,e)=>Ja(i,e,!1)},resolver:{extension:{type:A.ResolveParser,name:"resolveSpritesheet"},test:i=>{const t=i.split("?")[0].split("."),s=t.pop(),r=t.pop();return s==="json"&&Bp.includes(r)},parse:i=>{var t;const e=i.split(".");return{resolution:parseFloat(((t=Ya.RETINA_PREFIX.exec(i))==null?void 0:t[1])??"1"),format:e[e.length-2],src:i}}},loader:{name:"spritesheetLoader",id:"spritesheet",extension:{type:A.LoadParser,priority:$a.Normal,name:"spritesheetLoader"},async testParse(i,e){return Ys.extname(e.src).toLowerCase()===".json"&&!!i.frames},async parse(i,e,t){var u,p;const{texture:s,imageFilename:r,textureOptions:n,cachePrefix:o}=(e==null?void 0:e.data)??{};let a=Ys.dirname(e.src);a&&a.lastIndexOf("/")!==a.length-1&&(a+="/");let l;if(s instanceof j)l=s;else{const d=qa(a+(r??i.meta.image),e.src);l=(await t.load([{src:d,data:n}]))[d]}const c=new Za({texture:l.source,data:i,cachePrefix:o});await c.parse();const h=(u=i==null?void 0:i.meta)==null?void 0:u.related_multi_packs;if(Array.isArray(h)){const d=[];for(const _ of h){if(typeof _!="string")continue;let b=a+_;(p=e.data)!=null&&p.ignoreMultiPack||(b=qa(b,e.src),d.push(t.load({src:b,data:{textureOptions:n,ignoreMultiPack:!0}})))}const g=await Promise.all(d);c.linkedSheets=g,g.forEach(_=>{_.linkedSheets=[c].concat(c.linkedSheets.filter(b=>b!==_))})}return c},async unload(i,e,t){await t.unload(i.textureSource._sourceOrigin),i.destroy(!1)}}};Q.add(Dp);class Qa{constructor(e){this._lastTransform="",this._observer=null,this._tickerAttached=!1,this.updateTranslation=()=>{if(!this._canvas)return;const t=this._canvas.getBoundingClientRect(),s=this._canvas.width,r=this._canvas.height,n=t.width/s*this._renderer.resolution,o=t.height/r*this._renderer.resolution,a=t.left,l=t.top,c=`translate(${a}px, ${l}px) scale(${n}, ${o})`;c!==this._lastTransform&&(this._domElement.style.transform=c,this._lastTransform=c)},this._domElement=e.domElement,this._renderer=e.renderer,!(globalThis.OffscreenCanvas&&this._renderer.canvas instanceof OffscreenCanvas)&&(this._canvas=this._renderer.canvas,this._attachObserver())}get canvas(){return this._canvas}ensureAttached(){!this._domElement.parentNode&&this._canvas.parentNode&&(this._canvas.parentNode.appendChild(this._domElement),this.updateTranslation())}_attachObserver(){"ResizeObserver"in globalThis?(this._observer&&(this._observer.disconnect(),this._observer=null),this._observer=new ResizeObserver(e=>{for(const t of e){if(t.target!==this._canvas)continue;const s=this.canvas.width,r=this.canvas.height,n=t.contentRect.width/s*this._renderer.resolution,o=t.contentRect.height/r*this._renderer.resolution;(this._lastScaleX!==n||this._lastScaleY!==o)&&(this.updateTranslation(),this._lastScaleX=n,this._lastScaleY=o)}}),this._observer.observe(this._canvas)):this._tickerAttached||at.shared.add(this.updateTranslation,this,ys.HIGH)}destroy(){this._observer?(this._observer.disconnect(),this._observer=null):this._tickerAttached&&at.shared.remove(this.updateTranslation),this._domElement=null,this._renderer=null,this._canvas=null,this._tickerAttached=!1,this._lastTransform="",this._lastScaleX=null,this._lastScaleY=null}}class qs{constructor(e){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=qs.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new ye,this.page=new ye,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=e}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(e,t,s){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(e,t,s,r,n){throw new Error("initUIEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}preventDefault(){this.nativeEvent instanceof Event&&this.nativeEvent.cancelable&&this.nativeEvent.preventDefault(),this.defaultPrevented=!0}stopImmediatePropagation(){this.propagationImmediatelyStopped=!0}stopPropagation(){this.propagationStopped=!0}}var on=/iPhone/i,el=/iPod/i,tl=/iPad/i,sl=/\biOS-universal(?:.+)Mac\b/i,an=/\bAndroid(?:.+)Mobile\b/i,il=/Android/i,xs=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,Xi=/Silk/i,At=/Windows Phone/i,rl=/\bWindows(?:.+)ARM\b/i,nl=/BlackBerry/i,ol=/BB10/i,al=/Opera Mini/i,ll=/\b(CriOS|Chrome)(?:.+)Mobile/i,cl=/Mobile(?:.+)Firefox\b/i,hl=function(i){return typeof i<"u"&&i.platform==="MacIntel"&&typeof i.maxTouchPoints=="number"&&i.maxTouchPoints>1&&typeof MSStream>"u"};function Np(i){return function(e){return e.test(i)}}function ul(i){var e={userAgent:"",platform:"",maxTouchPoints:0};!i&&typeof navigator<"u"?e={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof i=="string"?e.userAgent=i:i&&i.userAgent&&(e={userAgent:i.userAgent,platform:i.platform,maxTouchPoints:i.maxTouchPoints||0});var t=e.userAgent,s=t.split("[FBAN");typeof s[1]<"u"&&(t=s[0]),s=t.split("Twitter"),typeof s[1]<"u"&&(t=s[0]);var r=Np(t),n={apple:{phone:r(on)&&!r(At),ipod:r(el),tablet:!r(on)&&(r(tl)||hl(e))&&!r(At),universal:r(sl),device:(r(on)||r(el)||r(tl)||r(sl)||hl(e))&&!r(At)},amazon:{phone:r(xs),tablet:!r(xs)&&r(Xi),device:r(xs)||r(Xi)},android:{phone:!r(At)&&r(xs)||!r(At)&&r(an),tablet:!r(At)&&!r(xs)&&!r(an)&&(r(Xi)||r(il)),device:!r(At)&&(r(xs)||r(Xi)||r(an)||r(il))||r(/\bokhttp\b/i)},windows:{phone:r(At),tablet:r(rl),device:r(At)||r(rl)},other:{blackberry:r(nl),blackberry10:r(ol),opera:r(al),firefox:r(cl),chrome:r(ll),device:r(nl)||r(ol)||r(al)||r(cl)||r(ll)},any:!1,phone:!1,tablet:!1};return n.any=n.apple.device||n.android.device||n.windows.device||n.other.device,n.phone=n.apple.phone||n.android.phone||n.windows.phone,n.tablet=n.apple.tablet||n.android.tablet||n.windows.tablet,n}const Up=(ul.default??ul)(globalThis.navigator),Gp=9,dl=100,Fp=0,Lp=0,fl=2,pl=1,Wp=-1e3,Hp=-1e3,Vp=2,ln=class hf{constructor(e,t=Up){this._mobileInfo=t,this.debug=!1,this._activateOnTab=!0,this._deactivateOnMouseMove=!0,this._isActive=!1,this._isMobileAccessibility=!1,this._div=null,this._pools={},this._renderId=0,this._children=[],this._androidUpdateCount=0,this._androidUpdateFrequency=500,this._isRunningTests=!1,this._boundOnKeyDown=this._onKeyDown.bind(this),this._boundOnMouseMove=this._onMouseMove.bind(this),this._hookDiv=null,(t.tablet||t.phone)&&this._createTouchHook(),this._renderer=e}get isActive(){return this._isActive}get isMobileAccessibility(){return this._isMobileAccessibility}get hookDiv(){return this._hookDiv}get div(){return this._div}_createTouchHook(){const e=document.createElement("button");e.style.width=`${pl}px`,e.style.height=`${pl}px`,e.style.position="absolute",e.style.top=`${Wp}px`,e.style.left=`${Hp}px`,e.style.zIndex=Vp.toString(),e.style.backgroundColor="#FF0000",e.title="select to enable accessibility for this content",e.addEventListener("focus",()=>{this._isMobileAccessibility=!0,this._activate(),this._destroyTouchHook()}),document.body.appendChild(e),this._hookDiv=e}_destroyTouchHook(){this._hookDiv&&(document.body.removeChild(this._hookDiv),this._hookDiv=null)}_activate(){if(this._isActive)return;this._isActive=!0,this._div||(this._div=document.createElement("div"),this._div.style.position="absolute",this._div.style.top=`${Fp}px`,this._div.style.left=`${Lp}px`,this._div.style.pointerEvents="none",this._div.style.zIndex=fl.toString(),this._canvasObserver=new Qa({domElement:this._div,renderer:this._renderer})),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._deactivateOnMouseMove&&globalThis.document.addEventListener("mousemove",this._boundOnMouseMove,!0);const e=this._renderer.view.canvas;if(e.parentNode)this._canvasObserver.ensureAttached(),this._initAccessibilitySetup();else{const t=new MutationObserver(()=>{e.parentNode&&(t.disconnect(),this._canvasObserver.ensureAttached(),this._initAccessibilitySetup())});t.observe(document.body,{childList:!0,subtree:!0})}}_initAccessibilitySetup(){this._renderer.runners.postrender.add(this),this._renderer.lastObjectRendered&&this._updateAccessibleObjects(this._renderer.lastObjectRendered)}_deactivate(){var e,t;if(!(!this._isActive||this._isMobileAccessibility)){this._isActive=!1,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._renderer.runners.postrender.remove(this);for(const s of this._children)(e=s._accessibleDiv)!=null&&e.parentNode&&(s._accessibleDiv.parentNode.removeChild(s._accessibleDiv),s._accessibleDiv=null),s._accessibleActive=!1;for(const s in this._pools)this._pools[s].forEach(n=>{n.parentNode&&n.parentNode.removeChild(n)}),delete this._pools[s];(t=this._div)!=null&&t.parentNode&&this._div.parentNode.removeChild(this._div),this._pools={},this._children=[]}}_updateAccessibleObjects(e){if(!e.visible||!e.accessibleChildren)return;e.accessible&&(e._accessibleActive||this._addChild(e),e._renderId=this._renderId);const t=e.children;if(t)for(let s=0;s<t.length;s++)this._updateAccessibleObjects(t[s])}init(e){const s={accessibilityOptions:{...hf.defaultOptions,...(e==null?void 0:e.accessibilityOptions)||{}}};this.debug=s.accessibilityOptions.debug,this._activateOnTab=s.accessibilityOptions.activateOnTab,this._deactivateOnMouseMove=s.accessibilityOptions.deactivateOnMouseMove,s.accessibilityOptions.enabledByDefault&&this._activate(),this._renderer.runners.postrender.remove(this)}postrender(){const e=performance.now();if(this._mobileInfo.android.device&&e<this._androidUpdateCount||(this._androidUpdateCount=e+this._androidUpdateFrequency,(!this._renderer.renderingToScreen||!this._renderer.view.canvas)&&!this._isRunningTests))return;const t=new Set;if(this._renderer.lastObjectRendered){this._updateAccessibleObjects(this._renderer.lastObjectRendered);for(const s of this._children)s._renderId===this._renderId&&t.add(this._children.indexOf(s))}for(let s=this._children.length-1;s>=0;s--){const r=this._children[s];t.has(s)||(r._accessibleDiv&&r._accessibleDiv.parentNode&&(r._accessibleDiv.parentNode.removeChild(r._accessibleDiv),this._getPool(r.accessibleType).push(r._accessibleDiv),r._accessibleDiv=null),r._accessibleActive=!1,Ma(this._children,s,1))}this._renderer.renderingToScreen&&this._canvasObserver.ensureAttached();for(let s=0;s<this._children.length;s++){const r=this._children[s];if(!r._accessibleActive||!r._accessibleDiv)continue;const n=r._accessibleDiv,o=r.hitArea||r.getBounds().rectangle;if(r.hitArea){const a=r.worldTransform;n.style.left=`${a.tx+o.x*a.a}px`,n.style.top=`${a.ty+o.y*a.d}px`,n.style.width=`${o.width*a.a}px`,n.style.height=`${o.height*a.d}px`}else this._capHitArea(o),n.style.left=`${o.x}px`,n.style.top=`${o.y}px`,n.style.width=`${o.width}px`,n.style.height=`${o.height}px`}this._renderId++}_updateDebugHTML(e){e.innerHTML=`type: ${e.type}</br> title : ${e.title}</br> tabIndex: ${e.tabIndex}`}_capHitArea(e){e.x<0&&(e.width+=e.x,e.x=0),e.y<0&&(e.height+=e.y,e.y=0);const{width:t,height:s}=this._renderer;e.x+e.width>t&&(e.width=t-e.x),e.y+e.height>s&&(e.height=s-e.y)}_addChild(e){let s=this._getPool(e.accessibleType).pop();s?(s.innerHTML="",s.removeAttribute("title"),s.removeAttribute("aria-label"),s.tabIndex=0):(e.accessibleType==="button"?s=document.createElement("button"):(s=document.createElement(e.accessibleType),s.style.cssText=`
|
|
5
5
|
color: transparent;
|
|
6
6
|
pointer-events: none;
|
|
7
7
|
padding: 0;
|
|
@@ -14,7 +14,7 @@ Deprecated since v${i}`,n=typeof console.groupCollapsed=="function"&&!fs.noColor
|
|
|
14
14
|
-webkit-user-select: none;
|
|
15
15
|
-moz-user-select: none;
|
|
16
16
|
-ms-user-select: none;
|
|
17
|
-
`,e.accessibleText&&(s.innerText=e.accessibleText)),s.style.width=`${dl}px`,s.style.height=`${dl}px`,s.style.backgroundColor=this.debug?"rgba(255,255,255,0.5)":"transparent",s.style.position="absolute",s.style.zIndex=fl.toString(),s.style.borderStyle="none",navigator.userAgent.toLowerCase().includes("chrome")?s.setAttribute("aria-live","off"):s.setAttribute("aria-live","polite"),navigator.userAgent.match(/rv:.*Gecko\//)?s.setAttribute("aria-relevant","additions"):s.setAttribute("aria-relevant","text"),s.addEventListener("click",this._onClick.bind(this)),s.addEventListener("focus",this._onFocus.bind(this)),s.addEventListener("focusout",this._onFocusOut.bind(this))),s.style.pointerEvents=e.accessiblePointerEvents,s.type=e.accessibleType,e.accessibleTitle&&e.accessibleTitle!==null?s.title=e.accessibleTitle:(!e.accessibleHint||e.accessibleHint===null)&&(s.title=`container ${e.tabIndex}`),e.accessibleHint&&e.accessibleHint!==null&&s.setAttribute("aria-label",e.accessibleHint),e.interactive?s.tabIndex=e.tabIndex:s.tabIndex=0,this.debug&&this._updateDebugHTML(s),e._accessibleActive=!0,e._accessibleDiv=s,s.container=e,this._children.push(e),this._div.appendChild(e._accessibleDiv)}_dispatchEvent(e,t){const{container:s}=e.target,r=this._renderer.events.rootBoundary,n=Object.assign(new qs(r),{target:s});r.rootTarget=this._renderer.lastObjectRendered,t.forEach(o=>r.dispatchEvent(n,o))}_onClick(e){this._dispatchEvent(e,["click","pointertap","tap"])}_onFocus(e){e.target.getAttribute("aria-live")||e.target.setAttribute("aria-live","assertive"),this._dispatchEvent(e,["mouseover"])}_onFocusOut(e){e.target.getAttribute("aria-live")||e.target.setAttribute("aria-live","polite"),this._dispatchEvent(e,["mouseout"])}_onKeyDown(e){e.keyCode!==
|
|
17
|
+
`,e.accessibleText&&(s.innerText=e.accessibleText)),s.style.width=`${dl}px`,s.style.height=`${dl}px`,s.style.backgroundColor=this.debug?"rgba(255,255,255,0.5)":"transparent",s.style.position="absolute",s.style.zIndex=fl.toString(),s.style.borderStyle="none",navigator.userAgent.toLowerCase().includes("chrome")?s.setAttribute("aria-live","off"):s.setAttribute("aria-live","polite"),navigator.userAgent.match(/rv:.*Gecko\//)?s.setAttribute("aria-relevant","additions"):s.setAttribute("aria-relevant","text"),s.addEventListener("click",this._onClick.bind(this)),s.addEventListener("focus",this._onFocus.bind(this)),s.addEventListener("focusout",this._onFocusOut.bind(this))),s.style.pointerEvents=e.accessiblePointerEvents,s.type=e.accessibleType,e.accessibleTitle&&e.accessibleTitle!==null?s.title=e.accessibleTitle:(!e.accessibleHint||e.accessibleHint===null)&&(s.title=`container ${e.tabIndex}`),e.accessibleHint&&e.accessibleHint!==null&&s.setAttribute("aria-label",e.accessibleHint),e.interactive?s.tabIndex=e.tabIndex:s.tabIndex=0,this.debug&&this._updateDebugHTML(s),e._accessibleActive=!0,e._accessibleDiv=s,s.container=e,this._children.push(e),this._div.appendChild(e._accessibleDiv)}_dispatchEvent(e,t){const{container:s}=e.target,r=this._renderer.events.rootBoundary,n=Object.assign(new qs(r),{target:s});r.rootTarget=this._renderer.lastObjectRendered,t.forEach(o=>r.dispatchEvent(n,o))}_onClick(e){this._dispatchEvent(e,["click","pointertap","tap"])}_onFocus(e){e.target.getAttribute("aria-live")||e.target.setAttribute("aria-live","assertive"),this._dispatchEvent(e,["mouseover"])}_onFocusOut(e){e.target.getAttribute("aria-live")||e.target.setAttribute("aria-live","polite"),this._dispatchEvent(e,["mouseout"])}_onKeyDown(e){e.keyCode!==Gp||!this._activateOnTab||this._activate()}_onMouseMove(e){e.movementX===0&&e.movementY===0||this._deactivate()}destroy(){var e;this._deactivate(),this._destroyTouchHook(),(e=this._canvasObserver)==null||e.destroy(),this._canvasObserver=null,this._div=null,this._pools=null,this._children=null,this._renderer=null,this._hookDiv=null,globalThis.removeEventListener("keydown",this._boundOnKeyDown),this._boundOnKeyDown=null,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._boundOnMouseMove=null}setAccessibilityEnabled(e){e?this._activate():this._deactivate()}_getPool(e){return this._pools[e]||(this._pools[e]=[]),this._pools[e]}};ln.extension={type:[A.WebGLSystem,A.WebGPUSystem],name:"accessibility"},ln.defaultOptions={enabledByDefault:!1,debug:!1,activateOnTab:!0,deactivateOnMouseMove:!0};let zp=ln;const $p={accessible:!1,accessibleTitle:null,accessibleHint:null,tabIndex:0,accessibleType:"button",accessibleText:null,accessiblePointerEvents:"auto",accessibleChildren:!0,_accessibleActive:!1,_accessibleDiv:null,_renderId:-1},cn=Object.create(null),ml=Object.create(null);function Ks(i,e){let t=ml[i];return t===void 0&&(cn[e]===void 0&&(cn[e]=1),ml[i]=t=cn[e]++),t}let Cs;function gl(){return(!Cs||Cs!=null&&Cs.isContextLost())&&(Cs=pe.get().createCanvas().getContext("webgl",{})),Cs}let Yi;function jp(){if(!Yi){Yi="mediump";const i=gl();i&&i.getShaderPrecisionFormat&&(Yi=i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision?"highp":"mediump")}return Yi}function Xp(i,e,t){return e?i:t?(i=i.replace("out vec4 finalColor;",""),`
|
|
18
18
|
|
|
19
19
|
#ifdef GL_ES // This checks if it is WebGL1
|
|
20
20
|
#define in varying
|
|
@@ -29,18 +29,18 @@ Deprecated since v${i}`,n=typeof console.groupCollapsed=="function"&&!fs.noColor
|
|
|
29
29
|
#define out varying
|
|
30
30
|
#endif
|
|
31
31
|
${i}
|
|
32
|
-
`}function
|
|
33
|
-
${i}`}else if(s!=="highp"&&i.substring(0,15)==="precision highp")return i.replace("precision highp","precision mediump");return i}function
|
|
34
|
-
${i}`:i}const
|
|
35
|
-
${i}`}function Jp(i,e){return e?i.replace("#version 300 es",""):i}const hn={stripVersion:Jp,ensurePrecision:Xp,addProgramDefines:jp,setProgramName:Zp,insertVersion:Yp},Zs=Object.create(null),_l=class Jo{constructor(e){e={...Jo.defaultOptions,...e};const t=e.fragment.indexOf("#version 300 es")!==-1,s={stripVersion:t,ensurePrecision:{requestedFragmentPrecision:e.preferredFragmentPrecision,requestedVertexPrecision:e.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:$p()},setProgramName:{name:e.name},addProgramDefines:t,insertVersion:t};let r=e.fragment,n=e.vertex;Object.keys(hn).forEach(o=>{const a=s[o];r=hn[o](r,a,!0),n=hn[o](n,a,!1)}),this.fragment=r,this.vertex=n,this.transformFeedbackVaryings=e.transformFeedbackVaryings,this._key=Ks(`${this.vertex}:${this.fragment}`,"gl-program")}destroy(){this.fragment=null,this.vertex=null,this._attributeData=null,this._uniformData=null,this._uniformBlockData=null,this.transformFeedbackVaryings=null,Zs[this._cacheKey]=null}static from(e){const t=`${e.vertex}:${e.fragment}`;return Zs[t]||(Zs[t]=new Jo(e),Zs[t]._cacheKey=t),Zs[t]}};_l.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let Es=_l;const yl={uint8x2:{size:2,stride:2,normalised:!1},uint8x4:{size:4,stride:4,normalised:!1},sint8x2:{size:2,stride:2,normalised:!1},sint8x4:{size:4,stride:4,normalised:!1},unorm8x2:{size:2,stride:2,normalised:!0},unorm8x4:{size:4,stride:4,normalised:!0},snorm8x2:{size:2,stride:2,normalised:!0},snorm8x4:{size:4,stride:4,normalised:!0},uint16x2:{size:2,stride:4,normalised:!1},uint16x4:{size:4,stride:8,normalised:!1},sint16x2:{size:2,stride:4,normalised:!1},sint16x4:{size:4,stride:8,normalised:!1},unorm16x2:{size:2,stride:4,normalised:!0},unorm16x4:{size:4,stride:8,normalised:!0},snorm16x2:{size:2,stride:4,normalised:!0},snorm16x4:{size:4,stride:8,normalised:!0},float16x2:{size:2,stride:4,normalised:!1},float16x4:{size:4,stride:8,normalised:!1},float32:{size:1,stride:4,normalised:!1},float32x2:{size:2,stride:8,normalised:!1},float32x3:{size:3,stride:12,normalised:!1},float32x4:{size:4,stride:16,normalised:!1},uint32:{size:1,stride:4,normalised:!1},uint32x2:{size:2,stride:8,normalised:!1},uint32x3:{size:3,stride:12,normalised:!1},uint32x4:{size:4,stride:16,normalised:!1},sint32:{size:1,stride:4,normalised:!1},sint32x2:{size:2,stride:8,normalised:!1},sint32x3:{size:3,stride:12,normalised:!1},sint32x4:{size:4,stride:16,normalised:!1}};function Js(i){return yl[i]??yl.float32}const Qp={f32:"float32","vec2<f32>":"float32x2","vec3<f32>":"float32x3","vec4<f32>":"float32x4",vec2f:"float32x2",vec3f:"float32x3",vec4f:"float32x4",i32:"sint32","vec2<i32>":"sint32x2","vec3<i32>":"sint32x3","vec4<i32>":"sint32x4",vec2i:"sint32x2",vec3i:"sint32x3",vec4i:"sint32x4",u32:"uint32","vec2<u32>":"uint32x2","vec3<u32>":"uint32x3","vec4<u32>":"uint32x4",vec2u:"uint32x2",vec3u:"uint32x3",vec4u:"uint32x4",bool:"uint32","vec2<bool>":"uint32x2","vec3<bool>":"uint32x3","vec4<bool>":"uint32x4"},bl=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|\)|$)/g;function vl(i,e){let t;for(;(t=bl.exec(i))!==null;){const s=Qp[t[3]]??"float32";e[t[2]]={location:parseInt(t[1],10),format:s,stride:Js(s).stride,offset:0,instance:!1,start:0}}bl.lastIndex=0}function em(i){return i.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"")}function tm({source:i,entryPoint:e}){const t={},s=em(i),r=s.indexOf(`fn ${e}(`);if(r===-1)return t;const n=s.indexOf("->",r);if(n===-1)return t;const o=s.substring(r,n);if(vl(o,t),Object.keys(t).length===0){const a=o.match(/\(\s*\w+\s*:\s*(\w+)/);if(a){const l=a[1],c=new RegExp(`struct\\s+${l}\\s*\\{([^}]+)\\}`,"s"),h=s.match(c);h&&vl(h[1],t)}}return t}function un(i){var u,p;const e=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,t=/@group\((\d+)\)/,s=/@binding\((\d+)\)/,r=/var(<[^>]+>)? (\w+)/,n=/:\s*([\w<>]+)/,o=/struct\s+(\w+)\s*{([^}]+)}/g,a=/(\w+)\s*:\s*([\w\<\>]+)/g,l=/struct\s+(\w+)/,c=(u=i.match(e))==null?void 0:u.map(d=>({group:parseInt(d.match(t)[1],10),binding:parseInt(d.match(s)[1],10),name:d.match(r)[2],isUniform:d.match(r)[1]==="<uniform>",type:d.match(n)[1]}));if(!c)return{groups:[],structs:[]};const h=((p=i.match(o))==null?void 0:p.map(d=>{const g=d.match(l)[1],_=d.match(a).reduce((b,v)=>{const[C,E]=v.split(":");return b[C.trim()]=E.trim(),b},{});return _?{name:g,members:_}:null}).filter(({name:d})=>c.some(g=>g.type===d||g.type.includes(`<${d}>`))))??[];return{groups:c,structs:h}}var ss=(i=>(i[i.VERTEX=1]="VERTEX",i[i.FRAGMENT=2]="FRAGMENT",i[i.COMPUTE=4]="COMPUTE",i))(ss||{});function sm({groups:i}){const e=[];for(let t=0;t<i.length;t++){const s=i[t];e[s.group]||(e[s.group]=[]),s.isUniform?e[s.group].push({binding:s.binding,visibility:ss.VERTEX|ss.FRAGMENT,buffer:{type:"uniform"}}):s.type==="sampler"?e[s.group].push({binding:s.binding,visibility:ss.FRAGMENT,sampler:{type:"filtering"}}):s.type==="texture_2d"||s.type.startsWith("texture_2d<")?e[s.group].push({binding:s.binding,visibility:ss.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d",multisampled:!1}}):s.type==="texture_2d_array"||s.type.startsWith("texture_2d_array<")?e[s.group].push({binding:s.binding,visibility:ss.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d-array",multisampled:!1}}):(s.type==="texture_cube"||s.type.startsWith("texture_cube<"))&&e[s.group].push({binding:s.binding,visibility:ss.FRAGMENT,texture:{sampleType:"float",viewDimension:"cube",multisampled:!1}})}for(let t=0;t<e.length;t++)e[t]||(e[t]=[]);return e}function im({groups:i}){const e=[];for(let t=0;t<i.length;t++){const s=i[t];e[s.group]||(e[s.group]={}),e[s.group][s.name]=s.binding}return e}function rm(i,e){const t=new Set,s=new Set,r=[...i.structs,...e.structs].filter(o=>t.has(o.name)?!1:(t.add(o.name),!0)),n=[...i.groups,...e.groups].filter(o=>{const a=`${o.name}-${o.binding}`;return s.has(a)?!1:(s.add(a),!0)});return{structs:r,groups:n}}const Qs=Object.create(null);class is{constructor(e){var a,l;this._layoutKey=0,this._attributeLocationsKey=0;const{fragment:t,vertex:s,layout:r,gpuLayout:n,name:o}=e;if(this.name=o,this.fragment=t,this.vertex=s,t.source===s.source){const c=un(t.source);this.structsAndGroups=c}else{const c=un(s.source),h=un(t.source);this.structsAndGroups=rm(c,h)}this.layout=r??im(this.structsAndGroups),this.gpuLayout=n??sm(this.structsAndGroups),this.autoAssignGlobalUniforms=((a=this.layout[0])==null?void 0:a.globalUniforms)!==void 0,this.autoAssignLocalUniforms=((l=this.layout[1])==null?void 0:l.localUniforms)!==void 0,this._generateProgramKey()}_generateProgramKey(){const{vertex:e,fragment:t}=this,s=e.source+t.source+e.entryPoint+t.entryPoint;this._layoutKey=Ks(s,"program")}get attributeData(){return this._attributeData??(this._attributeData=tm(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null,Qs[this._cacheKey]=null}static from(e){const t=`${e.vertex.source}:${e.fragment.source}:${e.fragment.entryPoint}:${e.vertex.entryPoint}`;return Qs[t]||(Qs[t]=new is(e),Qs[t]._cacheKey=t),Qs[t]}}const xl=["f32","i32","vec2<f32>","vec3<f32>","vec4<f32>","mat2x2<f32>","mat3x3<f32>","mat4x4<f32>","mat3x2<f32>","mat4x2<f32>","mat2x3<f32>","mat4x3<f32>","mat2x4<f32>","mat3x4<f32>","vec2<i32>","vec3<i32>","vec4<i32>"],nm=xl.reduce((i,e)=>(i[e]=!0,i),{});function om(i,e){switch(i){case"f32":return 0;case"vec2<f32>":return new Float32Array(2*e);case"vec3<f32>":return new Float32Array(3*e);case"vec4<f32>":return new Float32Array(4*e);case"mat2x2<f32>":return new Float32Array([1,0,0,1]);case"mat3x3<f32>":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4x4<f32>":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const Cl=class uf{constructor(e,t){this._touched=0,this.uid=be("uniform"),this._resourceType="uniformGroup",this._resourceId=be("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,t={...uf.defaultOptions,...t},this.uniformStructures=e;const s={};for(const r in e){const n=e[r];if(n.name=r,n.size=n.size??1,!nm[n.type]){const o=n.type.match(/^array<(\w+(?:<\w+>)?),\s*(\d+)>$/);if(o){const[,a,l]=o;throw new Error(`Uniform type ${n.type} is not supported. Use type: '${a}', size: ${l} instead.`)}throw new Error(`Uniform type ${n.type} is not supported. Supported uniform types are: ${xl.join(", ")}`)}n.value??(n.value=om(n.type,n.size)),s[r]=n.value}this.uniforms=s,this._dirtyId=1,this.ubo=t.ubo,this.isStatic=t.isStatic,this._signature=Ks(Object.keys(s).map(r=>`${r}-${e[r].type}`).join("-"),"uniform-group")}update(){this._dirtyId++}};Cl.defaultOptions={ubo:!1,isStatic:!1};let gt=Cl;class Nt{constructor(e){this.resources=Object.create(null),this._dirty=!0;let t=0;for(const s in e){const r=e[s];this.setResource(r,t++)}this._updateKey()}_updateKey(){if(!this._dirty)return;this._dirty=!1;const e=[];let t=0;for(const s in this.resources)e[t++]=this.resources[s]._resourceId;this._key=e.join("|")}setResource(e,t){var r,n;const s=this.resources[t];e!==s&&((r=s==null?void 0:s.off)==null||r.call(s,"change",this.onResourceChange,this),(n=e.on)==null||n.call(e,"change",this.onResourceChange,this),this.resources[t]=e,this._dirty=!0)}getResource(e){return this.resources[e]}_touch(e,t){const s=this.resources;for(const r in s)s[r]._gcLastUsed=e,s[r]._touched=t}destroy(){var t;const e=this.resources;for(const s in e){const r=e[s];(t=r==null?void 0:r.off)==null||t.call(r,"change",this.onResourceChange,this)}this.resources=null}onResourceChange(e){this._dirty=!0,e.destroyed?this.destroy():this._updateKey()}}var _t=(i=>(i[i.WEBGL=1]="WEBGL",i[i.WEBGPU=2]="WEBGPU",i[i.CANVAS=4]="CANVAS",i[i.BOTH=3]="BOTH",i))(_t||{});class wt extends lt{constructor(e){super(),this.uid=be("shader"),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[],this._destroyed=!1;let{gpuProgram:t,glProgram:s,groups:r,resources:n,compatibleRenderers:o,groupMap:a}=e;this.gpuProgram=t,this.glProgram=s,o===void 0&&(o=0,t&&(o|=_t.WEBGPU),s&&(o|=_t.WEBGL)),this.compatibleRenderers=o;const l={};if(!n&&!r&&(n={}),n&&r)throw new Error("[Shader] Cannot have both resources and groups");if(!t&&r&&!a)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(!t&&r&&a)for(const c in a)for(const h in a[c]){const u=a[c][h];l[u]={group:c,binding:h,name:u}}else if(t&&r&&!a){const c=t.structsAndGroups.groups;a={},c.forEach(h=>{a[h.group]=a[h.group]||{},a[h.group][h.binding]=h.name,l[h.name]=h})}else if(n){r={},a={},t&&t.structsAndGroups.groups.forEach(u=>{a[u.group]=a[u.group]||{},a[u.group][u.binding]=u.name,l[u.name]=u});let c=0;for(const h in n)l[h]||(r[99]||(r[99]=new Nt,this._ownedBindGroups.push(r[99])),l[h]={group:99,binding:c,name:h},a[99]=a[99]||{},a[99][c]=h,c++);for(const h in n){const u=h;let p=n[h];!p.source&&!p._resourceType&&(p=new gt(p));const d=l[u];d&&(r[d.group]||(r[d.group]=new Nt,this._ownedBindGroups.push(r[d.group])),r[d.group].setResource(p,d.binding))}}this.groups=r,this._uniformBindMap=a,this.resources=this._buildResourceAccessor(r,l)}addResource(e,t,s){var r,n;(r=this._uniformBindMap)[t]||(r[t]={}),(n=this._uniformBindMap[t])[s]||(n[s]=e),this.groups[t]||(this.groups[t]=new Nt,this._ownedBindGroups.push(this.groups[t]))}_buildResourceAccessor(e,t){const s={};for(const r in t){const n=t[r];Object.defineProperty(s,n.name,{get(){return e[n.group].getResource(n.binding)},set(o){e[n.group].setResource(o,n.binding)}})}return s}destroy(e=!1){var t,s;this._destroyed||(this._destroyed=!0,this.emit("destroy",this),e&&((t=this.gpuProgram)==null||t.destroy(),(s=this.glProgram)==null||s.destroy()),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(r=>{r.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null)}static from(e){const{gpu:t,gl:s,...r}=e;let n,o;return t&&(n=is.from(t)),s&&(o=Es.from(s)),new wt({gpuProgram:n,glProgram:o,...r})}}const am={normal:0,add:1,multiply:2,screen:3,overlay:4,erase:5,"normal-npm":6,"add-npm":7,"screen-npm":8,min:9,max:10},dn=0,fn=1,pn=2,mn=3,gn=4,_n=5,yn=class df{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<dn)}set blend(e){!!(this.data&1<<dn)!==e&&(this.data^=1<<dn)}get offsets(){return!!(this.data&1<<fn)}set offsets(e){!!(this.data&1<<fn)!==e&&(this.data^=1<<fn)}set cullMode(e){if(e==="none"){this.culling=!1;return}this.culling=!0,this.clockwiseFrontFace=e==="front"}get cullMode(){return this.culling?this.clockwiseFrontFace?"front":"back":"none"}get culling(){return!!(this.data&1<<pn)}set culling(e){!!(this.data&1<<pn)!==e&&(this.data^=1<<pn)}get depthTest(){return!!(this.data&1<<mn)}set depthTest(e){!!(this.data&1<<mn)!==e&&(this.data^=1<<mn)}get depthMask(){return!!(this.data&1<<_n)}set depthMask(e){!!(this.data&1<<_n)!==e&&(this.data^=1<<_n)}get clockwiseFrontFace(){return!!(this.data&1<<gn)}set clockwiseFrontFace(e){!!(this.data&1<<gn)!==e&&(this.data^=1<<gn)}get blendMode(){return this._blendMode}set blendMode(e){this.blend=e!=="none",this._blendMode=e,this._blendModeId=am[e]||0}get polygonOffset(){return this._polygonOffset}set polygonOffset(e){this.offsets=!!e,this._polygonOffset=e}toString(){return`[pixi.js/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`}static for2d(){const e=new df;return e.depthTest=!1,e.blend=!0,e}};yn.default2d=yn.for2d();let It=yn;const El=class Qo extends wt{constructor(e){e={...Qo.defaultOptions,...e},super(e),this.enabled=!0,this._state=It.for2d(),this.blendMode=e.blendMode,this.padding=e.padding,typeof e.antialias=="boolean"?this.antialias=e.antialias?"on":"off":this.antialias=e.antialias,this.resolution=e.resolution,this.blendRequired=e.blendRequired,this.clipToViewport=e.clipToViewport,this.addResource("uTexture",0,1),e.blendRequired&&this.addResource("uBackTexture",0,3)}apply(e,t,s,r){e.applyFilter(this,t,s,r)}get blendMode(){return this._state.blendMode}set blendMode(e){this._state.blendMode=e}static from(e){const{gpu:t,gl:s,...r}=e;let n,o;return t&&(n=is.from(t)),s&&(o=Es.from(s)),new Qo({gpuProgram:n,glProgram:o,...r})}};El.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let Sl=El;const bn=[];Q.handleByNamedList(A.Environment,bn);async function lm(i){if(!i)for(let e=0;e<bn.length;e++){const t=bn[e];if(t.value.test()){await t.value.load();return}}}let ei;function Tl(){if(typeof ei=="boolean")return ei;try{ei=new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")===!0}catch{ei=!1}return ei}function Al(i,e,t=2){const s=e&&e.length,r=s?e[0]*t:i.length;let n=wl(i,0,r,t,!0);const o=[];if(!n||n.next===n.prev)return o;let a,l,c;if(s&&(n=fm(i,e,n,t)),i.length>80*t){a=i[0],l=i[1];let h=a,u=l;for(let p=t;p<r;p+=t){const d=i[p],g=i[p+1];d<a&&(a=d),g<l&&(l=g),d>h&&(h=d),g>u&&(u=g)}c=Math.max(h-a,u-l),c=c!==0?32767/c:0}return ti(n,o,t,a,l,c,0),o}function wl(i,e,t,s,r){let n;if(r===Sm(i,e,t,s)>0)for(let o=e;o<t;o+=s)n=Pl(o/s|0,i[o],i[o+1],n);else for(let o=t-s;o>=e;o-=s)n=Pl(o/s|0,i[o],i[o+1],n);return n&&Ss(n,n.next)&&(ri(n),n=n.next),n}function rs(i,e){if(!i)return i;e||(e=i);let t=i,s;do if(s=!1,!t.steiner&&(Ss(t,t.next)||Ae(t.prev,t,t.next)===0)){if(ri(t),t=e=t.prev,t===t.next)break;s=!0}else t=t.next;while(s||t!==e);return e}function ti(i,e,t,s,r,n,o){if(!i)return;!o&&n&&ym(i,s,r,n);let a=i;for(;i.prev!==i.next;){const l=i.prev,c=i.next;if(n?hm(i,s,r,n):cm(i)){e.push(l.i,i.i,c.i),ri(i),i=c.next,a=c.next;continue}if(i=c,i===a){o?o===1?(i=um(rs(i),e),ti(i,e,t,s,r,n,2)):o===2&&dm(i,e,t,s,r,n):ti(rs(i),e,t,s,r,n,1);break}}}function cm(i){const e=i.prev,t=i,s=i.next;if(Ae(e,t,s)>=0)return!1;const r=e.x,n=t.x,o=s.x,a=e.y,l=t.y,c=s.y,h=Math.min(r,n,o),u=Math.min(a,l,c),p=Math.max(r,n,o),d=Math.max(a,l,c);let g=s.next;for(;g!==e;){if(g.x>=h&&g.x<=p&&g.y>=u&&g.y<=d&&si(r,a,n,l,o,c,g.x,g.y)&&Ae(g.prev,g,g.next)>=0)return!1;g=g.next}return!0}function hm(i,e,t,s){const r=i.prev,n=i,o=i.next;if(Ae(r,n,o)>=0)return!1;const a=r.x,l=n.x,c=o.x,h=r.y,u=n.y,p=o.y,d=Math.min(a,l,c),g=Math.min(h,u,p),_=Math.max(a,l,c),b=Math.max(h,u,p),v=vn(d,g,e,t,s),C=vn(_,b,e,t,s);let E=i.prevZ,S=i.nextZ;for(;E&&E.z>=v&&S&&S.z<=C;){if(E.x>=d&&E.x<=_&&E.y>=g&&E.y<=b&&E!==r&&E!==o&&si(a,h,l,u,c,p,E.x,E.y)&&Ae(E.prev,E,E.next)>=0||(E=E.prevZ,S.x>=d&&S.x<=_&&S.y>=g&&S.y<=b&&S!==r&&S!==o&&si(a,h,l,u,c,p,S.x,S.y)&&Ae(S.prev,S,S.next)>=0))return!1;S=S.nextZ}for(;E&&E.z>=v;){if(E.x>=d&&E.x<=_&&E.y>=g&&E.y<=b&&E!==r&&E!==o&&si(a,h,l,u,c,p,E.x,E.y)&&Ae(E.prev,E,E.next)>=0)return!1;E=E.prevZ}for(;S&&S.z<=C;){if(S.x>=d&&S.x<=_&&S.y>=g&&S.y<=b&&S!==r&&S!==o&&si(a,h,l,u,c,p,S.x,S.y)&&Ae(S.prev,S,S.next)>=0)return!1;S=S.nextZ}return!0}function um(i,e){let t=i;do{const s=t.prev,r=t.next.next;!Ss(s,r)&&Rl(s,t,t.next,r)&&ii(s,r)&&ii(r,s)&&(e.push(s.i,t.i,r.i),ri(t),ri(t.next),t=i=r),t=t.next}while(t!==i);return rs(t)}function dm(i,e,t,s,r,n){let o=i;do{let a=o.next.next;for(;a!==o.prev;){if(o.i!==a.i&&xm(o,a)){let l=Ml(o,a);o=rs(o,o.next),l=rs(l,l.next),ti(o,e,t,s,r,n,0),ti(l,e,t,s,r,n,0);return}a=a.next}o=o.next}while(o!==i)}function fm(i,e,t,s){const r=[];for(let n=0,o=e.length;n<o;n++){const a=e[n]*s,l=n<o-1?e[n+1]*s:i.length,c=wl(i,a,l,s,!1);c===c.next&&(c.steiner=!0),r.push(vm(c))}r.sort(pm);for(let n=0;n<r.length;n++)t=mm(r[n],t);return t}function pm(i,e){let t=i.x-e.x;if(t===0&&(t=i.y-e.y,t===0)){const s=(i.next.y-i.y)/(i.next.x-i.x),r=(e.next.y-e.y)/(e.next.x-e.x);t=s-r}return t}function mm(i,e){const t=gm(i,e);if(!t)return e;const s=Ml(t,i);return rs(s,s.next),rs(t,t.next)}function gm(i,e){let t=e;const s=i.x,r=i.y;let n=-1/0,o;if(Ss(i,t))return t;do{if(Ss(i,t.next))return t.next;if(r<=t.y&&r>=t.next.y&&t.next.y!==t.y){const u=t.x+(r-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(u<=s&&u>n&&(n=u,o=t.x<t.next.x?t:t.next,u===s))return o}t=t.next}while(t!==e);if(!o)return null;const a=o,l=o.x,c=o.y;let h=1/0;t=o;do{if(s>=t.x&&t.x>=l&&s!==t.x&&Il(r<c?s:n,r,l,c,r<c?n:s,r,t.x,t.y)){const u=Math.abs(r-t.y)/(s-t.x);ii(t,i)&&(u<h||u===h&&(t.x>o.x||t.x===o.x&&_m(o,t)))&&(o=t,h=u)}t=t.next}while(t!==a);return o}function _m(i,e){return Ae(i.prev,i,e.prev)<0&&Ae(e.next,i,i.next)<0}function ym(i,e,t,s){let r=i;do r.z===0&&(r.z=vn(r.x,r.y,e,t,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next;while(r!==i);r.prevZ.nextZ=null,r.prevZ=null,bm(r)}function bm(i){let e,t=1;do{let s=i,r;i=null;let n=null;for(e=0;s;){e++;let o=s,a=0;for(let c=0;c<t&&(a++,o=o.nextZ,!!o);c++);let l=t;for(;a>0||l>0&&o;)a!==0&&(l===0||!o||s.z<=o.z)?(r=s,s=s.nextZ,a--):(r=o,o=o.nextZ,l--),n?n.nextZ=r:i=r,r.prevZ=n,n=r;s=o}n.nextZ=null,t*=2}while(e>1);return i}function vn(i,e,t,s,r){return i=(i-t)*r|0,e=(e-s)*r|0,i=(i|i<<8)&16711935,i=(i|i<<4)&252645135,i=(i|i<<2)&858993459,i=(i|i<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,i|e<<1}function vm(i){let e=i,t=i;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==i);return t}function Il(i,e,t,s,r,n,o,a){return(r-o)*(e-a)>=(i-o)*(n-a)&&(i-o)*(s-a)>=(t-o)*(e-a)&&(t-o)*(n-a)>=(r-o)*(s-a)}function si(i,e,t,s,r,n,o,a){return!(i===o&&e===a)&&Il(i,e,t,s,r,n,o,a)}function xm(i,e){return i.next.i!==e.i&&i.prev.i!==e.i&&!Cm(i,e)&&(ii(i,e)&&ii(e,i)&&Em(i,e)&&(Ae(i.prev,i,e.prev)||Ae(i,e.prev,e))||Ss(i,e)&&Ae(i.prev,i,i.next)>0&&Ae(e.prev,e,e.next)>0)}function Ae(i,e,t){return(e.y-i.y)*(t.x-e.x)-(e.x-i.x)*(t.y-e.y)}function Ss(i,e){return i.x===e.x&&i.y===e.y}function Rl(i,e,t,s){const r=Ki(Ae(i,e,t)),n=Ki(Ae(i,e,s)),o=Ki(Ae(t,s,i)),a=Ki(Ae(t,s,e));return!!(r!==n&&o!==a||r===0&&qi(i,t,e)||n===0&&qi(i,s,e)||o===0&&qi(t,i,s)||a===0&&qi(t,e,s))}function qi(i,e,t){return e.x<=Math.max(i.x,t.x)&&e.x>=Math.min(i.x,t.x)&&e.y<=Math.max(i.y,t.y)&&e.y>=Math.min(i.y,t.y)}function Ki(i){return i>0?1:i<0?-1:0}function Cm(i,e){let t=i;do{if(t.i!==i.i&&t.next.i!==i.i&&t.i!==e.i&&t.next.i!==e.i&&Rl(t,t.next,i,e))return!0;t=t.next}while(t!==i);return!1}function ii(i,e){return Ae(i.prev,i,i.next)<0?Ae(i,e,i.next)>=0&&Ae(i,i.prev,e)>=0:Ae(i,e,i.prev)<0||Ae(i,i.next,e)<0}function Em(i,e){let t=i,s=!1;const r=(i.x+e.x)/2,n=(i.y+e.y)/2;do t.y>n!=t.next.y>n&&t.next.y!==t.y&&r<(t.next.x-t.x)*(n-t.y)/(t.next.y-t.y)+t.x&&(s=!s),t=t.next;while(t!==i);return s}function Ml(i,e){const t=xn(i.i,i.x,i.y),s=xn(e.i,e.x,e.y),r=i.next,n=e.prev;return i.next=e,e.prev=i,t.next=r,r.prev=t,s.next=t,t.prev=s,n.next=s,s.prev=n,s}function Pl(i,e,t,s){const r=xn(i,e,t);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function ri(i){i.next.prev=i.prev,i.prev.next=i.next,i.prevZ&&(i.prevZ.nextZ=i.nextZ),i.nextZ&&(i.nextZ.prevZ=i.prevZ)}function xn(i,e,t){return{i,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function Sm(i,e,t,s){let r=0;for(let n=e,o=t-s;n<t;n+=s)r+=(i[o]-i[n])*(i[n+1]+i[o+1]),o=n;return r}const Tm=Al.default||Al;var st=(i=>(i[i.NONE=0]="NONE",i[i.COLOR=16384]="COLOR",i[i.STENCIL=1024]="STENCIL",i[i.DEPTH=256]="DEPTH",i[i.COLOR_DEPTH=16640]="COLOR_DEPTH",i[i.COLOR_STENCIL=17408]="COLOR_STENCIL",i[i.DEPTH_STENCIL=1280]="DEPTH_STENCIL",i[i.ALL=17664]="ALL",i))(st||{});class kl{constructor(e){this.items=[],this._name=e}emit(e,t,s,r,n,o,a,l){const{name:c,items:h}=this;for(let u=0,p=h.length;u<p;u++)h[u][c](e,t,s,r,n,o,a,l);return this}add(e){return e[this._name]&&(this.remove(e),this.items.push(e)),this}remove(e){const t=this.items.indexOf(e);return t!==-1&&this.items.splice(t,1),this}contains(e){return this.items.indexOf(e)!==-1}removeAll(){return this.items.length=0,this}destroy(){this.removeAll(),this.items=null,this._name=null}get empty(){return this.items.length===0}get name(){return this._name}}const Am=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],Ol=class ff extends lt{constructor(e){super(),this.tick=0,this.uid=be("renderer"),this.runners=Object.create(null),this.renderPipes=Object.create(null),this._initOptions={},this._systemsHash=Object.create(null),this.type=e.type,this.name=e.name,this.config=e;const t=[...Am,...this.config.runners??[]];this._addRunners(...t),this._unsafeEvalCheck()}async init(e={}){const t=e.skipExtensionImports===!0?!0:e.manageImports===!1;await lm(t),this._addSystems(this.config.systems),this._addPipes(this.config.renderPipes,this.config.renderPipeAdaptors);for(const s in this._systemsHash)e={...this._systemsHash[s].constructor.defaultOptions,...e};e={...ff.defaultOptions,...e},this._roundPixels=e.roundPixels?1:0;for(let s=0;s<this.runners.init.items.length;s++)await this.runners.init.items[s].init(e);this._initOptions=e}render(e,t){this.tick++;let s=e;if(s instanceof Ve&&(s={container:s},t&&(ee(Be,"passing a second argument is deprecated, please use render options instead"),s.target=t.renderTexture)),s.target||(s.target=this.view.renderTarget),s.target===this.view.renderTarget&&(this._lastObjectRendered=s.container,s.clearColor??(s.clearColor=this.background.colorRgba),s.clear??(s.clear=this.background.clearBeforeRender)),s.clearColor){const r=Array.isArray(s.clearColor)&&s.clearColor.length===4;s.clearColor=r?s.clearColor:Pe.shared.setValue(s.clearColor).toArray()}s.transform||(s.container.updateLocalTransform(),s.transform=s.container.localTransform),s.container.visible&&(s.container.enableRenderGroup(),this.runners.prerender.emit(s),this.runners.renderStart.emit(s),this.runners.render.emit(s),this.runners.renderEnd.emit(s),this.runners.postrender.emit(s))}resize(e,t,s){const r=this.view.resolution;this.view.resize(e,t,s),this.emit("resize",this.view.screen.width,this.view.screen.height,this.view.resolution),s!==void 0&&s!==r&&this.runners.resolutionChange.emit(s)}clear(e={}){const t=this;e.target||(e.target=t.renderTarget.renderTarget),e.clearColor||(e.clearColor=this.background.colorRgba),e.clear??(e.clear=st.ALL);const{clear:s,clearColor:r,target:n,mipLevel:o,layer:a}=e;Pe.shared.setValue(r??this.background.colorRgba),t.renderTarget.clear(n,s,Pe.shared.toArray(),o??0,a??0)}get resolution(){return this.view.resolution}set resolution(e){this.view.resolution=e,this.runners.resolutionChange.emit(e)}get width(){return this.view.texture.frame.width}get height(){return this.view.texture.frame.height}get canvas(){return this.view.canvas}get lastObjectRendered(){return this._lastObjectRendered}get renderingToScreen(){return this.renderTarget.renderingToScreen}get screen(){return this.view.screen}_addRunners(...e){e.forEach(t=>{this.runners[t]=new kl(t)})}_addSystems(e){let t;for(t in e){const s=e[t];this._addSystem(s.value,s.name)}}_addSystem(e,t){const s=new e(this);if(this[t])throw new Error(`Whoops! The name "${t}" is already in use`);this[t]=s,this._systemsHash[t]=s;for(const r in this.runners)this.runners[r].add(s);return this}_addPipes(e,t){const s=t.reduce((r,n)=>(r[n.name]=n.value,r),{});e.forEach(r=>{const n=r.value,o=r.name,a=s[o];this.renderPipes[o]=new n(this,a?new a:null),this.runners.destroy.add(this.renderPipes[o])})}destroy(e=!1){this.runners.destroy.items.reverse(),this.runners.destroy.emit(e),(e===!0||typeof e=="object"&&e.releaseGlobalResources)&&ms.release(),Object.values(this.runners).forEach(t=>{t.destroy()}),this._systemsHash=null,this.renderPipes=null,this.removeAllListeners()}generateTexture(e){return this.textureGenerator.generateTexture(e)}get roundPixels(){return!!this._roundPixels}_unsafeEvalCheck(){if(!Tl())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}resetState(){this.runners.resetState.emit()}};Ol.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let ni=Ol,Zi;function wm(i){return Zi!==void 0||(Zi=(()=>{var t;const e={stencil:!0,failIfMajorPerformanceCaveat:i??ni.defaultOptions.failIfMajorPerformanceCaveat};try{if(!pe.get().getWebGLRenderingContext())return!1;let r=pe.get().createCanvas().getContext("webgl",e);const n=!!((t=r==null?void 0:r.getContextAttributes())!=null&&t.stencil);if(r){const o=r.getExtension("WEBGL_lose_context");o&&o.loseContext()}return r=null,n}catch{return!1}})()),Zi}let Ji;async function Im(i={}){return Ji!==void 0||(Ji=await(async()=>{const e=pe.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(i)).requestDevice(),!0}catch{return!1}})()),Ji}const Bl=["webgl","webgpu","canvas"];async function Rm(i){let e=[];i.preference?(e.push(i.preference),Bl.forEach(n=>{n!==i.preference&&e.push(n)})):e=Bl.slice();let t,s={};for(let n=0;n<e.length;n++){const o=e[n];if(o==="webgpu"&&await Im()){const{WebGPURenderer:a}=await Promise.resolve().then(()=>Hb);t=a,s={...i,...i.webgpu};break}else if(o==="webgl"&&wm(i.failIfMajorPerformanceCaveat??ni.defaultOptions.failIfMajorPerformanceCaveat)){const{WebGLRenderer:a}=await Promise.resolve().then(()=>vb);t=a,s={...i,...i.webgl};break}else if(o==="canvas"){const{CanvasRenderer:a}=await Promise.resolve().then(()=>by);t=a,s={...i,...i.canvasOptions};break}}if(delete s.webgpu,delete s.webgl,delete s.canvasOptions,!t)throw new Error("No available renderer for the current environment");const r=new t;return await r.init(s),r}const Qi="8.17.1";class Dl{static init(){var e;(e=globalThis.__PIXI_APP_INIT__)==null||e.call(globalThis,this,Qi)}static destroy(){}}Dl.extension=A.Application;class Nl{constructor(e){this._renderer=e}init(){var e;(e=globalThis.__PIXI_RENDERER_INIT__)==null||e.call(globalThis,this._renderer,Qi)}destroy(){this._renderer=null}}Nl.extension={type:[A.WebGLSystem,A.WebGPUSystem],name:"initHook",priority:-10};class Ul{static init(e){Object.defineProperty(this,"resizeTo",{configurable:!0,set(t){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=t,t&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&(cancelAnimationFrame(this._resizeId),this._resizeId=null)},this.resize=()=>{if(!this._resizeTo)return;this._cancelResize();let t,s;if(this._resizeTo===globalThis.window)t=globalThis.innerWidth,s=globalThis.innerHeight;else{const{clientWidth:r,clientHeight:n}=this._resizeTo;t=r,s=n}this.renderer.resize(t,s),this.render()},this._resizeId=null,this._resizeTo=null,this.resizeTo=e.resizeTo||null}static destroy(){globalThis.removeEventListener("resize",this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}}Ul.extension=A.Application;class Gl{static init(e){e=Object.assign({autoStart:!0,sharedTicker:!1},e),Object.defineProperty(this,"ticker",{configurable:!0,set(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this,ys.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?at.shared:new at,e.autoStart&&this.start()}static destroy(){if(this._ticker){const e=this._ticker;this.ticker=null,e.destroy()}}}Gl.extension=A.Application,Q.add(Ul),Q.add(Gl);const Fl=class ea{constructor(...e){this.stage=new Ve,e[0]!==void 0&&ee(Be,"Application constructor options are deprecated, please use Application.init() instead.")}async init(e){e={...e},this.stage||(this.stage=new Ve),this.renderer=await Rm(e),ea._plugins.forEach(t=>{t.init.call(this,e)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return ee(Be,"Application.view is deprecated, please use Application.canvas instead."),this.renderer.canvas}get screen(){return this.renderer.screen}destroy(e=!1,t=!1){const s=ea._plugins.slice(0);s.reverse(),s.forEach(r=>{r.destroy.call(this)}),this.stage.destroy(t),this.stage=null,this.renderer.destroy(e),this.renderer=null}};Fl._plugins=[];let Ll=Fl;Q.handleByList(A.Application,Ll._plugins),Q.add(Dl);var Cn,Wl;function Mm(){if(Wl)return Cn;Wl=1,Cn=t;var i={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},e=/([astvzqmhlc])([^astvzqmhlc]*)/ig;function t(n){var o=[];return n.replace(e,function(a,l,c){var h=l.toLowerCase();for(c=r(c),h=="m"&&c.length>2&&(o.push([l].concat(c.splice(0,2))),h="l",l=l=="m"?"l":"L");;){if(c.length==i[h])return c.unshift(l),o.push(c);if(c.length<i[h])throw new Error("malformed path data");o.push([l].concat(c.splice(0,i[h])))}}),o}var s=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig;function r(n){var o=n.match(s);return o?o.map(Number):[]}return Cn}var Pm=Mm();const km=oa(Pm);function Om(i,e){const t=km(i),s=[];let r=null,n=0,o=0;for(let a=0;a<t.length;a++){const l=t[a],c=l[0],h=l;switch(c){case"M":n=h[1],o=h[2],e.moveTo(n,o);break;case"m":n+=h[1],o+=h[2],e.moveTo(n,o);break;case"H":n=h[1],e.lineTo(n,o);break;case"h":n+=h[1],e.lineTo(n,o);break;case"V":o=h[1],e.lineTo(n,o);break;case"v":o+=h[1],e.lineTo(n,o);break;case"L":n=h[1],o=h[2],e.lineTo(n,o);break;case"l":n+=h[1],o+=h[2],e.lineTo(n,o);break;case"C":n=h[5],o=h[6],e.bezierCurveTo(h[1],h[2],h[3],h[4],n,o);break;case"c":e.bezierCurveTo(n+h[1],o+h[2],n+h[3],o+h[4],n+h[5],o+h[6]),n+=h[5],o+=h[6];break;case"S":n=h[3],o=h[4],e.bezierCurveToShort(h[1],h[2],n,o);break;case"s":e.bezierCurveToShort(n+h[1],o+h[2],n+h[3],o+h[4]),n+=h[3],o+=h[4];break;case"Q":n=h[3],o=h[4],e.quadraticCurveTo(h[1],h[2],n,o);break;case"q":e.quadraticCurveTo(n+h[1],o+h[2],n+h[3],o+h[4]),n+=h[3],o+=h[4];break;case"T":n=h[1],o=h[2],e.quadraticCurveToShort(n,o);break;case"t":n+=h[1],o+=h[2],e.quadraticCurveToShort(n,o);break;case"A":n=h[6],o=h[7],e.arcToSvg(h[1],h[2],h[3],h[4],h[5],n,o);break;case"a":n+=h[6],o+=h[7],e.arcToSvg(h[1],h[2],h[3],h[4],h[5],n,o);break;case"Z":case"z":e.closePath(),s.length>0&&(r=s.pop(),r?(n=r.startX,o=r.startY):(n=0,o=0)),r=null;break;default:ie(`Unknown SVG path command: ${c}`)}c!=="Z"&&c!=="z"&&r===null&&(r={startX:n,startY:o},s.push(r))}return e}class En{constructor(e=0,t=0,s=0){this.type="circle",this.x=e,this.y=t,this.radius=s}clone(){return new En(this.x,this.y,this.radius)}contains(e,t){if(this.radius<=0)return!1;const s=this.radius*this.radius;let r=this.x-e,n=this.y-t;return r*=r,n*=n,r+n<=s}strokeContains(e,t,s,r=.5){if(this.radius===0)return!1;const n=this.x-e,o=this.y-t,a=this.radius,l=(1-r)*s,c=Math.sqrt(n*n+o*o);return c<=a+l&&c>a-(s-l)}getBounds(e){return e||(e=new Ce),e.x=this.x-this.radius,e.y=this.y-this.radius,e.width=this.radius*2,e.height=this.radius*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.radius=e.radius,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`}}class Sn{constructor(e=0,t=0,s=0,r=0){this.type="ellipse",this.x=e,this.y=t,this.halfWidth=s,this.halfHeight=r}clone(){return new Sn(this.x,this.y,this.halfWidth,this.halfHeight)}contains(e,t){if(this.halfWidth<=0||this.halfHeight<=0)return!1;let s=(e-this.x)/this.halfWidth,r=(t-this.y)/this.halfHeight;return s*=s,r*=r,s+r<=1}strokeContains(e,t,s,r=.5){const{halfWidth:n,halfHeight:o}=this;if(n<=0||o<=0)return!1;const a=s*(1-r),l=s-a,c=n-l,h=o-l,u=n+a,p=o+a,d=e-this.x,g=t-this.y,_=d*d/(c*c)+g*g/(h*h),b=d*d/(u*u)+g*g/(p*p);return _>1&&b<=1}getBounds(e){return e||(e=new Ce),e.x=this.x-this.halfWidth,e.y=this.y-this.halfHeight,e.width=this.halfWidth*2,e.height=this.halfHeight*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.halfWidth=e.halfWidth,this.halfHeight=e.halfHeight,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Ellipse x=${this.x} y=${this.y} halfWidth=${this.halfWidth} halfHeight=${this.halfHeight}]`}}function Bm(i,e,t,s,r,n){const o=i-t,a=e-s,l=r-t,c=n-s,h=o*l+a*c,u=l*l+c*c;let p=-1;u!==0&&(p=h/u);let d,g;p<0?(d=t,g=s):p>1?(d=r,g=n):(d=t+p*l,g=s+p*c);const _=i-d,b=e-g;return _*_+b*b}let Dm,Nm;class oi{constructor(...e){this.type="polygon";let t=Array.isArray(e[0])?e[0]:e;if(typeof t[0]!="number"){const s=[];for(let r=0,n=t.length;r<n;r++)s.push(t[r].x,t[r].y);t=s}this.points=t,this.closePath=!0}isClockwise(){let e=0;const t=this.points,s=t.length;for(let r=0;r<s;r+=2){const n=t[r],o=t[r+1],a=t[(r+2)%s],l=t[(r+3)%s];e+=(a-n)*(l+o)}return e<0}containsPolygon(e){const t=this.getBounds(Dm),s=e.getBounds(Nm);if(!t.containsRect(s))return!1;const r=e.points;for(let n=0;n<r.length;n+=2){const o=r[n],a=r[n+1];if(!this.contains(o,a))return!1}return!0}clone(){const e=this.points.slice(),t=new oi(e);return t.closePath=this.closePath,t}contains(e,t){let s=!1;const r=this.points.length/2;for(let n=0,o=r-1;n<r;o=n++){const a=this.points[n*2],l=this.points[n*2+1],c=this.points[o*2],h=this.points[o*2+1];l>t!=h>t&&e<(c-a)*((t-l)/(h-l))+a&&(s=!s)}return s}strokeContains(e,t,s,r=.5){const n=s*s,o=n*(1-r),a=n-o,{points:l}=this,c=l.length-(this.closePath?0:2);for(let h=0;h<c;h+=2){const u=l[h],p=l[h+1],d=l[(h+2)%l.length],g=l[(h+3)%l.length],_=Bm(e,t,u,p,d,g),b=Math.sign((d-u)*(t-p)-(g-p)*(e-u));if(_<=(b<0?a:o))return!0}return!1}getBounds(e){e||(e=new Ce);const t=this.points;let s=1/0,r=-1/0,n=1/0,o=-1/0;for(let a=0,l=t.length;a<l;a+=2){const c=t[a],h=t[a+1];s=c<s?c:s,r=c>r?c:r,n=h<n?h:n,o=h>o?h:o}return e.x=s,e.width=r-s,e.y=n,e.height=o-n,e}copyFrom(e){return this.points=e.points.slice(),this.closePath=e.closePath,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:PolygoncloseStroke=${this.closePath}points=${this.points.reduce((e,t)=>`${e}, ${t}`,"")}]`}get lastX(){return this.points[this.points.length-2]}get lastY(){return this.points[this.points.length-1]}get x(){return ee("8.11.0","Polygon.lastX is deprecated, please use Polygon.lastX instead."),this.points[this.points.length-2]}get y(){return ee("8.11.0","Polygon.y is deprecated, please use Polygon.lastY instead."),this.points[this.points.length-1]}get startX(){return this.points[0]}get startY(){return this.points[1]}}const er=(i,e,t,s,r,n,o)=>{const a=i-t,l=e-s,c=Math.sqrt(a*a+l*l);return c>=r-n&&c<=r+o};class Tn{constructor(e=0,t=0,s=0,r=0,n=20){this.type="roundedRectangle",this.x=e,this.y=t,this.width=s,this.height=r,this.radius=n}getBounds(e){return e||(e=new Ce),e.x=this.x,e.y=this.y,e.width=this.width,e.height=this.height,e}clone(){return new Tn(this.x,this.y,this.width,this.height,this.radius)}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){if(this.width<=0||this.height<=0)return!1;if(e>=this.x&&e<=this.x+this.width&&t>=this.y&&t<=this.y+this.height){const s=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(t>=this.y+s&&t<=this.y+this.height-s||e>=this.x+s&&e<=this.x+this.width-s)return!0;let r=e-(this.x+s),n=t-(this.y+s);const o=s*s;if(r*r+n*n<=o||(r=e-(this.x+this.width-s),r*r+n*n<=o)||(n=t-(this.y+this.height-s),r*r+n*n<=o)||(r=e-(this.x+s),r*r+n*n<=o))return!0}return!1}strokeContains(e,t,s,r=.5){const{x:n,y:o,width:a,height:l,radius:c}=this,h=s*(1-r),u=s-h,p=n+c,d=o+c,g=a-c*2,_=l-c*2,b=n+a,v=o+l;return(e>=n-h&&e<=n+u||e>=b-u&&e<=b+h)&&t>=d&&t<=d+_||(t>=o-h&&t<=o+u||t>=v-u&&t<=v+h)&&e>=p&&e<=p+g?!0:e<p&&t<d&&er(e,t,p,d,c,u,h)||e>b-c&&t<d&&er(e,t,b-c,d,c,u,h)||e>b-c&&t>v-c&&er(e,t,b-c,v-c,c,u,h)||e<p&&t>v-c&&er(e,t,p,v-c,c,u,h)}toString(){return`[pixi.js/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`}}const Hl={};function An(i,e,t){let s=2166136261;for(let r=0;r<e;r++)s^=i[r].uid,s=Math.imul(s,16777619),s>>>=0;return Hl[s]||Um(i,e,s,t)}function Um(i,e,t,s){const r={};let n=0;for(let a=0;a<s;a++){const l=a<e?i[a]:j.EMPTY.source;r[n++]=l.source,r[n++]=l.style}const o=new Nt(r);return Hl[t]=o,o}class Vl{constructor(e){typeof e=="number"?this.rawBinaryData=new ArrayBuffer(e):e instanceof Uint8Array?this.rawBinaryData=e.buffer:this.rawBinaryData=e,this.uint32View=new Uint32Array(this.rawBinaryData),this.float32View=new Float32Array(this.rawBinaryData),this.size=this.rawBinaryData.byteLength}get int8View(){return this._int8View||(this._int8View=new Int8Array(this.rawBinaryData)),this._int8View}get uint8View(){return this._uint8View||(this._uint8View=new Uint8Array(this.rawBinaryData)),this._uint8View}get int16View(){return this._int16View||(this._int16View=new Int16Array(this.rawBinaryData)),this._int16View}get int32View(){return this._int32View||(this._int32View=new Int32Array(this.rawBinaryData)),this._int32View}get float64View(){return this._float64Array||(this._float64Array=new Float64Array(this.rawBinaryData)),this._float64Array}get bigUint64View(){return this._bigUint64Array||(this._bigUint64Array=new BigUint64Array(this.rawBinaryData)),this._bigUint64Array}view(e){return this[`${e}View`]}destroy(){this.rawBinaryData=null,this.uint32View=null,this.float32View=null,this.uint16View=null,this._int8View=null,this._uint8View=null,this._int16View=null,this._int32View=null,this._float64Array=null,this._bigUint64Array=null}static sizeOf(e){switch(e){case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;default:throw new Error(`${e} isn't a valid view type`)}}}function wn(i,e,t,s){if(t??(t=0),s??(s=Math.min(i.byteLength-t,e.byteLength)),!(t&7)&&!(s&7)){const r=s/8;new Float64Array(e,0,r).set(new Float64Array(i,t,r))}else if(!(t&3)&&!(s&3)){const r=s/4;new Float32Array(e,0,r).set(new Float32Array(i,t,r))}else new Uint8Array(e).set(new Uint8Array(i,t,s))}const Gm={normal:"normal-npm",add:"add-npm",screen:"screen-npm"};var ke=(i=>(i[i.DISABLED=0]="DISABLED",i[i.RENDERING_MASK_ADD=1]="RENDERING_MASK_ADD",i[i.MASK_ACTIVE=2]="MASK_ACTIVE",i[i.INVERSE_MASK_ACTIVE=3]="INVERSE_MASK_ACTIVE",i[i.RENDERING_MASK_REMOVE=4]="RENDERING_MASK_REMOVE",i[i.NONE=5]="NONE",i))(ke||{});function zl(i,e){return e.alphaMode==="no-premultiply-alpha"&&Gm[i]||i}const Fm=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join(`
|
|
36
|
-
`);function
|
|
37
|
-
else `),t<i-1&&(e+=`if(test == ${t}.0){}`);return e}function $l(i,e){if(i===0)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const t=e.createShader(e.FRAGMENT_SHADER);try{for(;;){const s=Fm.replace(/%forloop%/gi,Lm(i));if(e.shaderSource(t,s),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS))i=i/2|0;else break}}finally{e.deleteShader(t)}return i}let Ts=null;function Wm(){var e;if(Ts)return Ts;const i=gl();return Ts=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),Ts=$l(Ts,i),(e=i.getExtension("WEBGL_lose_context"))==null||e.loseContext(),Ts}class Hm{constructor(){this.ids=Object.create(null),this.textures=[],this.count=0}clear(){for(let e=0;e<this.count;e++){const t=this.textures[e];this.textures[e]=null,this.ids[t.uid]=null}this.count=0}}class Vm{constructor(){this.renderPipeId="batch",this.action="startBatch",this.start=0,this.size=0,this.textures=new Hm,this.blendMode="normal",this.topology="triangle-strip",this.canBundle=!0}destroy(){this.textures=null,this.gpuBindGroup=null,this.bindGroup=null,this.batcher=null,this.elements=null}}const ai=[];let tr=0;ms.register({clear:()=>{if(ai.length>0)for(const i of ai)i&&i.destroy();ai.length=0,tr=0}});function jl(){return tr>0?ai[--tr]:new Vm}function Xl(i){i.elements=null,ai[tr++]=i}let li=0;const Yl=class pf{constructor(e){this.uid=be("batcher"),this.dirty=!0,this.batchIndex=0,this.batches=[],this._elements=[],e={...pf.defaultOptions,...e},e.maxTextures||(ee("v8.8.0","maxTextures is a required option for Batcher now, please pass it in the options"),e.maxTextures=Wm());const{maxTextures:t,attributesInitialSize:s,indicesInitialSize:r}=e;this.attributeBuffer=new Vl(s*4),this.indexBuffer=new Uint16Array(r),this.maxTextures=t}begin(){this.elementSize=0,this.elementStart=0,this.indexSize=0,this.attributeSize=0;for(let e=0;e<this.batchIndex;e++)Xl(this.batches[e]);this.batchIndex=0,this._batchIndexStart=0,this._batchIndexSize=0,this.dirty=!0}add(e){this._elements[this.elementSize++]=e,e._indexStart=this.indexSize,e._attributeStart=this.attributeSize,e._batcher=this,this.indexSize+=e.indexSize,this.attributeSize+=e.attributeSize*this.vertexSize}checkAndUpdateTexture(e,t){const s=e._batch.textures.ids[t._source.uid];return!s&&s!==0?!1:(e._textureId=s,e.texture=t,!0)}updateElement(e){this.dirty=!0;const t=this.attributeBuffer;e.packAsQuad?this.packQuadAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId):this.packAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId)}break(e){const t=this._elements;if(!t[this.elementStart])return;let s=jl(),r=s.textures;r.clear();const n=t[this.elementStart];let o=zl(n.blendMode,n.texture._source),a=n.topology;this.attributeSize*4>this.attributeBuffer.size&&this._resizeAttributeBuffer(this.attributeSize*4),this.indexSize>this.indexBuffer.length&&this._resizeIndexBuffer(this.indexSize);const l=this.attributeBuffer.float32View,c=this.attributeBuffer.uint32View,h=this.indexBuffer;let u=this._batchIndexSize,p=this._batchIndexStart,d="startBatch",g=[];const _=this.maxTextures;for(let b=this.elementStart;b<this.elementSize;++b){const v=t[b];t[b]=null;const E=v.texture._source,S=zl(v.blendMode,E),w=o!==S||a!==v.topology;if(E._batchTick===li&&!w){v._textureId=E._textureBindLocation,u+=v.indexSize,v.packAsQuad?(this.packQuadAttributes(v,l,c,v._attributeStart,v._textureId),this.packQuadIndex(h,v._indexStart,v._attributeStart/this.vertexSize)):(this.packAttributes(v,l,c,v._attributeStart,v._textureId),this.packIndex(v,h,v._indexStart,v._attributeStart/this.vertexSize)),v._batch=s,g.push(v);continue}E._batchTick=li,(r.count>=_||w)&&(this._finishBatch(s,p,u-p,r,o,a,e,d,g),d="renderBatch",p=u,o=S,a=v.topology,s=jl(),r=s.textures,r.clear(),g=[],++li),v._textureId=E._textureBindLocation=r.count,r.ids[E.uid]=r.count,r.textures[r.count++]=E,v._batch=s,g.push(v),u+=v.indexSize,v.packAsQuad?(this.packQuadAttributes(v,l,c,v._attributeStart,v._textureId),this.packQuadIndex(h,v._indexStart,v._attributeStart/this.vertexSize)):(this.packAttributes(v,l,c,v._attributeStart,v._textureId),this.packIndex(v,h,v._indexStart,v._attributeStart/this.vertexSize))}r.count>0&&(this._finishBatch(s,p,u-p,r,o,a,e,d,g),p=u,++li),this.elementStart=this.elementSize,this._batchIndexStart=p,this._batchIndexSize=u}_finishBatch(e,t,s,r,n,o,a,l,c){e.gpuBindGroup=null,e.bindGroup=null,e.action=l,e.batcher=this,e.textures=r,e.blendMode=n,e.topology=o,e.start=t,e.size=s,e.elements=c,++li,this.batches[this.batchIndex++]=e,a.add(e)}finish(e){this.break(e)}ensureAttributeBuffer(e){e*4<=this.attributeBuffer.size||this._resizeAttributeBuffer(e*4)}ensureIndexBuffer(e){e<=this.indexBuffer.length||this._resizeIndexBuffer(e)}_resizeAttributeBuffer(e){const t=Math.max(e,this.attributeBuffer.size*2),s=new Vl(t);wn(this.attributeBuffer.rawBinaryData,s.rawBinaryData),this.attributeBuffer=s}_resizeIndexBuffer(e){const t=this.indexBuffer;let s=Math.max(e,t.length*1.5);s+=s%2;const r=s>65535?new Uint32Array(s):new Uint16Array(s);if(r.BYTES_PER_ELEMENT!==t.BYTES_PER_ELEMENT)for(let n=0;n<t.length;n++)r[n]=t[n];else wn(t.buffer,r.buffer);this.indexBuffer=r}packQuadIndex(e,t,s){e[t]=s+0,e[t+1]=s+1,e[t+2]=s+2,e[t+3]=s+0,e[t+4]=s+2,e[t+5]=s+3}packIndex(e,t,s,r){const n=e.indices,o=e.indexSize,a=e.indexOffset,l=e.attributeOffset;for(let c=0;c<o;c++)t[s++]=r+n[c+a]-l}destroy(e={}){var t;if(this.batches!==null){for(let s=0;s<this.batchIndex;s++)Xl(this.batches[s]);this.batches=null,this.geometry.destroy(!0),this.geometry=null,e.shader&&((t=this.shader)==null||t.destroy(),this.shader=null);for(let s=0;s<this._elements.length;s++)this._elements[s]&&(this._elements[s]._batch=null);this._elements=null,this.indexBuffer=null,this.attributeBuffer.destroy(),this.attributeBuffer=null}}};Yl.defaultOptions={maxTextures:null,attributesInitialSize:4,indicesInitialSize:6};let zm=Yl;var Ee=(i=>(i[i.MAP_READ=1]="MAP_READ",i[i.MAP_WRITE=2]="MAP_WRITE",i[i.COPY_SRC=4]="COPY_SRC",i[i.COPY_DST=8]="COPY_DST",i[i.INDEX=16]="INDEX",i[i.VERTEX=32]="VERTEX",i[i.UNIFORM=64]="UNIFORM",i[i.STORAGE=128]="STORAGE",i[i.INDIRECT=256]="INDIRECT",i[i.QUERY_RESOLVE=512]="QUERY_RESOLVE",i[i.STATIC=1024]="STATIC",i))(Ee||{});let Ut=class extends lt{constructor(e){let{data:t,size:s}=e;const{usage:r,label:n,shrinkToFit:o}=e;super(),this._gpuData=Object.create(null),this._gcLastUsed=-1,this.autoGarbageCollect=!0,this.uid=be("buffer"),this._resourceType="buffer",this._resourceId=be("resource"),this._touched=0,this._updateID=1,this._dataInt32=null,this.shrinkToFit=!0,this.destroyed=!1,t instanceof Array&&(t=new Float32Array(t)),this._data=t,s??(s=t==null?void 0:t.byteLength);const a=!!t;this.descriptor={size:s,usage:r,mappedAtCreation:a,label:n},this.shrinkToFit=o??!0}get data(){return this._data}set data(e){this.setDataWithSize(e,e.length,!0)}get dataInt32(){return this._dataInt32||(this._dataInt32=new Int32Array(this.data.buffer)),this._dataInt32}get static(){return!!(this.descriptor.usage&Ee.STATIC)}set static(e){e?this.descriptor.usage|=Ee.STATIC:this.descriptor.usage&=~Ee.STATIC}setDataWithSize(e,t,s){if(this._updateID++,this._updateSize=t*e.BYTES_PER_ELEMENT,this._data===e){s&&this.emit("update",this);return}const r=this._data;if(this._data=e,this._dataInt32=null,!r||r.length!==e.length){!this.shrinkToFit&&r&&e.byteLength<r.byteLength?s&&this.emit("update",this):(this.descriptor.size=e.byteLength,this._resourceId=be("resource"),this.emit("change",this));return}s&&this.emit("update",this)}update(e){this._updateSize=e??this._updateSize,this._updateID++,this.emit("update",this)}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this.emit("change",this),this._data=null,this.descriptor=null,this.removeAllListeners()}};function ql(i,e){if(!(i instanceof Ut)){let t=e?Ee.INDEX:Ee.VERTEX;i instanceof Array&&(e?(i=new Uint32Array(i),t=Ee.INDEX|Ee.COPY_DST):(i=new Float32Array(i),t=Ee.VERTEX|Ee.COPY_DST)),i=new Ut({data:i,label:e?"index-mesh-buffer":"vertex-mesh-buffer",usage:t})}return i}function $m(i,e,t){const s=i.getAttribute(e);if(!s)return t.minX=0,t.minY=0,t.maxX=0,t.maxY=0,t;const r=s.buffer.data;let n=1/0,o=1/0,a=-1/0,l=-1/0;const c=r.BYTES_PER_ELEMENT,h=(s.offset||0)/c,u=(s.stride||8)/c;for(let p=h;p<r.length;p+=u){const d=r[p],g=r[p+1];d>a&&(a=d),g>l&&(l=g),d<n&&(n=d),g<o&&(o=g)}return t.minX=n,t.minY=o,t.maxX=a,t.maxY=l,t}function jm(i){return(i instanceof Ut||Array.isArray(i)||i.BYTES_PER_ELEMENT)&&(i={buffer:i}),i.buffer=ql(i.buffer,!1),i}class In extends lt{constructor(e={}){super(),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=be("geometry"),this._layoutKey=0,this.instanceCount=1,this._bounds=new Ye,this._boundsDirty=!0;const{attributes:t,indexBuffer:s,topology:r}=e;if(this.buffers=[],this.attributes={},t)for(const n in t)this.addAttribute(n,t[n]);this.instanceCount=e.instanceCount??1,s&&this.addIndex(s),this.topology=r||"triangle-list"}onBufferUpdate(){this._boundsDirty=!0,this.emit("update",this)}getAttribute(e){return this.attributes[e]}getIndex(){return this.indexBuffer}getBuffer(e){return this.getAttribute(e).buffer}getSize(){for(const e in this.attributes){const t=this.attributes[e];return t.buffer.data.length/(t.stride/4||t.size)}return 0}addAttribute(e,t){const s=jm(t);this.buffers.indexOf(s.buffer)===-1&&(this.buffers.push(s.buffer),s.buffer.on("update",this.onBufferUpdate,this),s.buffer.on("change",this.onBufferUpdate,this)),this.attributes[e]=s}addIndex(e){this.indexBuffer=ql(e,!0),this.buffers.push(this.indexBuffer)}get bounds(){return this._boundsDirty?(this._boundsDirty=!1,$m(this,"aPosition",this._bounds)):this._bounds}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(e=!1){var t;this.emit("destroy",this),this.removeAllListeners(),e&&this.buffers.forEach(s=>s.destroy()),this.unload(),(t=this.indexBuffer)==null||t.destroy(),this.attributes=null,this.buffers=null,this.indexBuffer=null,this._bounds=null}}const Xm=new Float32Array(1),Ym=new Uint32Array(1);class qm extends In{constructor(){const t=new Ut({data:Xm,label:"attribute-batch-buffer",usage:Ee.VERTEX|Ee.COPY_DST,shrinkToFit:!1}),s=new Ut({data:Ym,label:"index-batch-buffer",usage:Ee.INDEX|Ee.COPY_DST,shrinkToFit:!1}),r=24;super({attributes:{aPosition:{buffer:t,format:"float32x2",stride:r,offset:0},aUV:{buffer:t,format:"float32x2",stride:r,offset:8},aColor:{buffer:t,format:"unorm8x4",stride:r,offset:16},aTextureIdAndRound:{buffer:t,format:"uint16x2",stride:r,offset:20}},indexBuffer:s})}}function Kl(i,e,t){if(i)for(const s in i){const r=s.toLocaleLowerCase(),n=e[r];if(n){let o=i[s];s==="header"&&(o=o.replace(/@in\s+[^;]+;\s*/g,"").replace(/@out\s+[^;]+;\s*/g,"")),t&&n.push(`//----${t}----//`),n.push(o)}else ie(`${s} placement hook does not exist in shader`)}}const Km=/\{\{(.*?)\}\}/g;function Zl(i){var s;const e={};return(((s=i.match(Km))==null?void 0:s.map(r=>r.replace(/[{()}]/g,"")))??[]).forEach(r=>{e[r]=[]}),e}function Jl(i,e){let t;const s=/@in\s+([^;]+);/g;for(;(t=s.exec(i))!==null;)e.push(t[1])}function Ql(i,e,t=!1){const s=[];Jl(e,s),i.forEach(a=>{a.header&&Jl(a.header,s)});const r=s;t&&r.sort();const n=r.map((a,l)=>` @location(${l}) ${a},`).join(`
|
|
32
|
+
`}function Yp(i,e,t){const s=t?e.maxSupportedFragmentPrecision:e.maxSupportedVertexPrecision;if(i.substring(0,9)!=="precision"){let r=t?e.requestedFragmentPrecision:e.requestedVertexPrecision;return r==="highp"&&s!=="highp"&&(r="mediump"),`precision ${r} float;
|
|
33
|
+
${i}`}else if(s!=="highp"&&i.substring(0,15)==="precision highp")return i.replace("precision highp","precision mediump");return i}function qp(i,e){return e?`#version 300 es
|
|
34
|
+
${i}`:i}const Kp={},Zp={};function Jp(i,{name:e="pixi-program"},t=!0){e=e.replace(/\s+/g,"-"),e+=t?"-fragment":"-vertex";const s=t?Kp:Zp;return s[e]?(s[e]++,e+=`-${s[e]}`):s[e]=1,i.indexOf("#define SHADER_NAME")!==-1?i:`${`#define SHADER_NAME ${e}`}
|
|
35
|
+
${i}`}function Qp(i,e){return e?i.replace("#version 300 es",""):i}const hn={stripVersion:Qp,ensurePrecision:Yp,addProgramDefines:Xp,setProgramName:Jp,insertVersion:qp},Zs=Object.create(null),_l=class Jo{constructor(e){e={...Jo.defaultOptions,...e};const t=e.fragment.indexOf("#version 300 es")!==-1,s={stripVersion:t,ensurePrecision:{requestedFragmentPrecision:e.preferredFragmentPrecision,requestedVertexPrecision:e.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:jp()},setProgramName:{name:e.name},addProgramDefines:t,insertVersion:t};let r=e.fragment,n=e.vertex;Object.keys(hn).forEach(o=>{const a=s[o];r=hn[o](r,a,!0),n=hn[o](n,a,!1)}),this.fragment=r,this.vertex=n,this.transformFeedbackVaryings=e.transformFeedbackVaryings,this._key=Ks(`${this.vertex}:${this.fragment}`,"gl-program")}destroy(){this.fragment=null,this.vertex=null,this._attributeData=null,this._uniformData=null,this._uniformBlockData=null,this.transformFeedbackVaryings=null,Zs[this._cacheKey]=null}static from(e){const t=`${e.vertex}:${e.fragment}`;return Zs[t]||(Zs[t]=new Jo(e),Zs[t]._cacheKey=t),Zs[t]}};_l.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let Es=_l;const yl={uint8x2:{size:2,stride:2,normalised:!1},uint8x4:{size:4,stride:4,normalised:!1},sint8x2:{size:2,stride:2,normalised:!1},sint8x4:{size:4,stride:4,normalised:!1},unorm8x2:{size:2,stride:2,normalised:!0},unorm8x4:{size:4,stride:4,normalised:!0},snorm8x2:{size:2,stride:2,normalised:!0},snorm8x4:{size:4,stride:4,normalised:!0},uint16x2:{size:2,stride:4,normalised:!1},uint16x4:{size:4,stride:8,normalised:!1},sint16x2:{size:2,stride:4,normalised:!1},sint16x4:{size:4,stride:8,normalised:!1},unorm16x2:{size:2,stride:4,normalised:!0},unorm16x4:{size:4,stride:8,normalised:!0},snorm16x2:{size:2,stride:4,normalised:!0},snorm16x4:{size:4,stride:8,normalised:!0},float16x2:{size:2,stride:4,normalised:!1},float16x4:{size:4,stride:8,normalised:!1},float32:{size:1,stride:4,normalised:!1},float32x2:{size:2,stride:8,normalised:!1},float32x3:{size:3,stride:12,normalised:!1},float32x4:{size:4,stride:16,normalised:!1},uint32:{size:1,stride:4,normalised:!1},uint32x2:{size:2,stride:8,normalised:!1},uint32x3:{size:3,stride:12,normalised:!1},uint32x4:{size:4,stride:16,normalised:!1},sint32:{size:1,stride:4,normalised:!1},sint32x2:{size:2,stride:8,normalised:!1},sint32x3:{size:3,stride:12,normalised:!1},sint32x4:{size:4,stride:16,normalised:!1}};function Js(i){return yl[i]??yl.float32}const em={f32:"float32","vec2<f32>":"float32x2","vec3<f32>":"float32x3","vec4<f32>":"float32x4",vec2f:"float32x2",vec3f:"float32x3",vec4f:"float32x4",i32:"sint32","vec2<i32>":"sint32x2","vec3<i32>":"sint32x3","vec4<i32>":"sint32x4",vec2i:"sint32x2",vec3i:"sint32x3",vec4i:"sint32x4",u32:"uint32","vec2<u32>":"uint32x2","vec3<u32>":"uint32x3","vec4<u32>":"uint32x4",vec2u:"uint32x2",vec3u:"uint32x3",vec4u:"uint32x4",bool:"uint32","vec2<bool>":"uint32x2","vec3<bool>":"uint32x3","vec4<bool>":"uint32x4"},bl=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|\)|$)/g;function vl(i,e){let t;for(;(t=bl.exec(i))!==null;){const s=em[t[3]]??"float32";e[t[2]]={location:parseInt(t[1],10),format:s,stride:Js(s).stride,offset:0,instance:!1,start:0}}bl.lastIndex=0}function tm(i){return i.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"")}function sm({source:i,entryPoint:e}){const t={},s=tm(i),r=s.indexOf(`fn ${e}(`);if(r===-1)return t;const n=s.indexOf("->",r);if(n===-1)return t;const o=s.substring(r,n);if(vl(o,t),Object.keys(t).length===0){const a=o.match(/\(\s*\w+\s*:\s*(\w+)/);if(a){const l=a[1],c=new RegExp(`struct\\s+${l}\\s*\\{([^}]+)\\}`,"s"),h=s.match(c);h&&vl(h[1],t)}}return t}function un(i){var u,p;const e=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,t=/@group\((\d+)\)/,s=/@binding\((\d+)\)/,r=/var(<[^>]+>)? (\w+)/,n=/:\s*([\w<>]+)/,o=/struct\s+(\w+)\s*{([^}]+)}/g,a=/(\w+)\s*:\s*([\w\<\>]+)/g,l=/struct\s+(\w+)/,c=(u=i.match(e))==null?void 0:u.map(d=>({group:parseInt(d.match(t)[1],10),binding:parseInt(d.match(s)[1],10),name:d.match(r)[2],isUniform:d.match(r)[1]==="<uniform>",type:d.match(n)[1]}));if(!c)return{groups:[],structs:[]};const h=((p=i.match(o))==null?void 0:p.map(d=>{const g=d.match(l)[1],_=d.match(a).reduce((b,v)=>{const[C,E]=v.split(":");return b[C.trim()]=E.trim(),b},{});return _?{name:g,members:_}:null}).filter(({name:d})=>c.some(g=>g.type===d||g.type.includes(`<${d}>`))))??[];return{groups:c,structs:h}}var ss=(i=>(i[i.VERTEX=1]="VERTEX",i[i.FRAGMENT=2]="FRAGMENT",i[i.COMPUTE=4]="COMPUTE",i))(ss||{});function im({groups:i}){const e=[];for(let t=0;t<i.length;t++){const s=i[t];e[s.group]||(e[s.group]=[]),s.isUniform?e[s.group].push({binding:s.binding,visibility:ss.VERTEX|ss.FRAGMENT,buffer:{type:"uniform"}}):s.type==="sampler"?e[s.group].push({binding:s.binding,visibility:ss.FRAGMENT,sampler:{type:"filtering"}}):s.type==="texture_2d"||s.type.startsWith("texture_2d<")?e[s.group].push({binding:s.binding,visibility:ss.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d",multisampled:!1}}):s.type==="texture_2d_array"||s.type.startsWith("texture_2d_array<")?e[s.group].push({binding:s.binding,visibility:ss.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d-array",multisampled:!1}}):(s.type==="texture_cube"||s.type.startsWith("texture_cube<"))&&e[s.group].push({binding:s.binding,visibility:ss.FRAGMENT,texture:{sampleType:"float",viewDimension:"cube",multisampled:!1}})}for(let t=0;t<e.length;t++)e[t]||(e[t]=[]);return e}function rm({groups:i}){const e=[];for(let t=0;t<i.length;t++){const s=i[t];e[s.group]||(e[s.group]={}),e[s.group][s.name]=s.binding}return e}function nm(i,e){const t=new Set,s=new Set,r=[...i.structs,...e.structs].filter(o=>t.has(o.name)?!1:(t.add(o.name),!0)),n=[...i.groups,...e.groups].filter(o=>{const a=`${o.name}-${o.binding}`;return s.has(a)?!1:(s.add(a),!0)});return{structs:r,groups:n}}const Qs=Object.create(null);class is{constructor(e){var a,l;this._layoutKey=0,this._attributeLocationsKey=0;const{fragment:t,vertex:s,layout:r,gpuLayout:n,name:o}=e;if(this.name=o,this.fragment=t,this.vertex=s,t.source===s.source){const c=un(t.source);this.structsAndGroups=c}else{const c=un(s.source),h=un(t.source);this.structsAndGroups=nm(c,h)}this.layout=r??rm(this.structsAndGroups),this.gpuLayout=n??im(this.structsAndGroups),this.autoAssignGlobalUniforms=((a=this.layout[0])==null?void 0:a.globalUniforms)!==void 0,this.autoAssignLocalUniforms=((l=this.layout[1])==null?void 0:l.localUniforms)!==void 0,this._generateProgramKey()}_generateProgramKey(){const{vertex:e,fragment:t}=this,s=e.source+t.source+e.entryPoint+t.entryPoint;this._layoutKey=Ks(s,"program")}get attributeData(){return this._attributeData??(this._attributeData=sm(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null,Qs[this._cacheKey]=null}static from(e){const t=`${e.vertex.source}:${e.fragment.source}:${e.fragment.entryPoint}:${e.vertex.entryPoint}`;return Qs[t]||(Qs[t]=new is(e),Qs[t]._cacheKey=t),Qs[t]}}const xl=["f32","i32","vec2<f32>","vec3<f32>","vec4<f32>","mat2x2<f32>","mat3x3<f32>","mat4x4<f32>","mat3x2<f32>","mat4x2<f32>","mat2x3<f32>","mat4x3<f32>","mat2x4<f32>","mat3x4<f32>","vec2<i32>","vec3<i32>","vec4<i32>"],om=xl.reduce((i,e)=>(i[e]=!0,i),{});function am(i,e){switch(i){case"f32":return 0;case"vec2<f32>":return new Float32Array(2*e);case"vec3<f32>":return new Float32Array(3*e);case"vec4<f32>":return new Float32Array(4*e);case"mat2x2<f32>":return new Float32Array([1,0,0,1]);case"mat3x3<f32>":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4x4<f32>":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const Cl=class uf{constructor(e,t){this._touched=0,this.uid=be("uniform"),this._resourceType="uniformGroup",this._resourceId=be("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,t={...uf.defaultOptions,...t},this.uniformStructures=e;const s={};for(const r in e){const n=e[r];if(n.name=r,n.size=n.size??1,!om[n.type]){const o=n.type.match(/^array<(\w+(?:<\w+>)?),\s*(\d+)>$/);if(o){const[,a,l]=o;throw new Error(`Uniform type ${n.type} is not supported. Use type: '${a}', size: ${l} instead.`)}throw new Error(`Uniform type ${n.type} is not supported. Supported uniform types are: ${xl.join(", ")}`)}n.value??(n.value=am(n.type,n.size)),s[r]=n.value}this.uniforms=s,this._dirtyId=1,this.ubo=t.ubo,this.isStatic=t.isStatic,this._signature=Ks(Object.keys(s).map(r=>`${r}-${e[r].type}`).join("-"),"uniform-group")}update(){this._dirtyId++}};Cl.defaultOptions={ubo:!1,isStatic:!1};let gt=Cl;class Nt{constructor(e){this.resources=Object.create(null),this._dirty=!0;let t=0;for(const s in e){const r=e[s];this.setResource(r,t++)}this._updateKey()}_updateKey(){if(!this._dirty)return;this._dirty=!1;const e=[];let t=0;for(const s in this.resources)e[t++]=this.resources[s]._resourceId;this._key=e.join("|")}setResource(e,t){var r,n;const s=this.resources[t];e!==s&&((r=s==null?void 0:s.off)==null||r.call(s,"change",this.onResourceChange,this),(n=e.on)==null||n.call(e,"change",this.onResourceChange,this),this.resources[t]=e,this._dirty=!0)}getResource(e){return this.resources[e]}_touch(e,t){const s=this.resources;for(const r in s)s[r]._gcLastUsed=e,s[r]._touched=t}destroy(){var t;const e=this.resources;for(const s in e){const r=e[s];(t=r==null?void 0:r.off)==null||t.call(r,"change",this.onResourceChange,this)}this.resources=null}onResourceChange(e){this._dirty=!0,e.destroyed?this.destroy():this._updateKey()}}var _t=(i=>(i[i.WEBGL=1]="WEBGL",i[i.WEBGPU=2]="WEBGPU",i[i.CANVAS=4]="CANVAS",i[i.BOTH=3]="BOTH",i))(_t||{});class wt extends lt{constructor(e){super(),this.uid=be("shader"),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[],this._destroyed=!1;let{gpuProgram:t,glProgram:s,groups:r,resources:n,compatibleRenderers:o,groupMap:a}=e;this.gpuProgram=t,this.glProgram=s,o===void 0&&(o=0,t&&(o|=_t.WEBGPU),s&&(o|=_t.WEBGL)),this.compatibleRenderers=o;const l={};if(!n&&!r&&(n={}),n&&r)throw new Error("[Shader] Cannot have both resources and groups");if(!t&&r&&!a)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(!t&&r&&a)for(const c in a)for(const h in a[c]){const u=a[c][h];l[u]={group:c,binding:h,name:u}}else if(t&&r&&!a){const c=t.structsAndGroups.groups;a={},c.forEach(h=>{a[h.group]=a[h.group]||{},a[h.group][h.binding]=h.name,l[h.name]=h})}else if(n){r={},a={},t&&t.structsAndGroups.groups.forEach(u=>{a[u.group]=a[u.group]||{},a[u.group][u.binding]=u.name,l[u.name]=u});let c=0;for(const h in n)l[h]||(r[99]||(r[99]=new Nt,this._ownedBindGroups.push(r[99])),l[h]={group:99,binding:c,name:h},a[99]=a[99]||{},a[99][c]=h,c++);for(const h in n){const u=h;let p=n[h];!p.source&&!p._resourceType&&(p=new gt(p));const d=l[u];d&&(r[d.group]||(r[d.group]=new Nt,this._ownedBindGroups.push(r[d.group])),r[d.group].setResource(p,d.binding))}}this.groups=r,this._uniformBindMap=a,this.resources=this._buildResourceAccessor(r,l)}addResource(e,t,s){var r,n;(r=this._uniformBindMap)[t]||(r[t]={}),(n=this._uniformBindMap[t])[s]||(n[s]=e),this.groups[t]||(this.groups[t]=new Nt,this._ownedBindGroups.push(this.groups[t]))}_buildResourceAccessor(e,t){const s={};for(const r in t){const n=t[r];Object.defineProperty(s,n.name,{get(){return e[n.group].getResource(n.binding)},set(o){e[n.group].setResource(o,n.binding)}})}return s}destroy(e=!1){var t,s;this._destroyed||(this._destroyed=!0,this.emit("destroy",this),e&&((t=this.gpuProgram)==null||t.destroy(),(s=this.glProgram)==null||s.destroy()),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(r=>{r.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null)}static from(e){const{gpu:t,gl:s,...r}=e;let n,o;return t&&(n=is.from(t)),s&&(o=Es.from(s)),new wt({gpuProgram:n,glProgram:o,...r})}}const lm={normal:0,add:1,multiply:2,screen:3,overlay:4,erase:5,"normal-npm":6,"add-npm":7,"screen-npm":8,min:9,max:10},dn=0,fn=1,pn=2,mn=3,gn=4,_n=5,yn=class df{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<dn)}set blend(e){!!(this.data&1<<dn)!==e&&(this.data^=1<<dn)}get offsets(){return!!(this.data&1<<fn)}set offsets(e){!!(this.data&1<<fn)!==e&&(this.data^=1<<fn)}set cullMode(e){if(e==="none"){this.culling=!1;return}this.culling=!0,this.clockwiseFrontFace=e==="front"}get cullMode(){return this.culling?this.clockwiseFrontFace?"front":"back":"none"}get culling(){return!!(this.data&1<<pn)}set culling(e){!!(this.data&1<<pn)!==e&&(this.data^=1<<pn)}get depthTest(){return!!(this.data&1<<mn)}set depthTest(e){!!(this.data&1<<mn)!==e&&(this.data^=1<<mn)}get depthMask(){return!!(this.data&1<<_n)}set depthMask(e){!!(this.data&1<<_n)!==e&&(this.data^=1<<_n)}get clockwiseFrontFace(){return!!(this.data&1<<gn)}set clockwiseFrontFace(e){!!(this.data&1<<gn)!==e&&(this.data^=1<<gn)}get blendMode(){return this._blendMode}set blendMode(e){this.blend=e!=="none",this._blendMode=e,this._blendModeId=lm[e]||0}get polygonOffset(){return this._polygonOffset}set polygonOffset(e){this.offsets=!!e,this._polygonOffset=e}toString(){return`[pixi.js/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`}static for2d(){const e=new df;return e.depthTest=!1,e.blend=!0,e}};yn.default2d=yn.for2d();let It=yn;const El=class Qo extends wt{constructor(e){e={...Qo.defaultOptions,...e},super(e),this.enabled=!0,this._state=It.for2d(),this.blendMode=e.blendMode,this.padding=e.padding,typeof e.antialias=="boolean"?this.antialias=e.antialias?"on":"off":this.antialias=e.antialias,this.resolution=e.resolution,this.blendRequired=e.blendRequired,this.clipToViewport=e.clipToViewport,this.addResource("uTexture",0,1),e.blendRequired&&this.addResource("uBackTexture",0,3)}apply(e,t,s,r){e.applyFilter(this,t,s,r)}get blendMode(){return this._state.blendMode}set blendMode(e){this._state.blendMode=e}static from(e){const{gpu:t,gl:s,...r}=e;let n,o;return t&&(n=is.from(t)),s&&(o=Es.from(s)),new Qo({gpuProgram:n,glProgram:o,...r})}};El.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let Sl=El;const bn=[];Q.handleByNamedList(A.Environment,bn);async function cm(i){if(!i)for(let e=0;e<bn.length;e++){const t=bn[e];if(t.value.test()){await t.value.load();return}}}let ei;function Tl(){if(typeof ei=="boolean")return ei;try{ei=new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")===!0}catch{ei=!1}return ei}function Al(i,e,t=2){const s=e&&e.length,r=s?e[0]*t:i.length;let n=wl(i,0,r,t,!0);const o=[];if(!n||n.next===n.prev)return o;let a,l,c;if(s&&(n=pm(i,e,n,t)),i.length>80*t){a=i[0],l=i[1];let h=a,u=l;for(let p=t;p<r;p+=t){const d=i[p],g=i[p+1];d<a&&(a=d),g<l&&(l=g),d>h&&(h=d),g>u&&(u=g)}c=Math.max(h-a,u-l),c=c!==0?32767/c:0}return ti(n,o,t,a,l,c,0),o}function wl(i,e,t,s,r){let n;if(r===Tm(i,e,t,s)>0)for(let o=e;o<t;o+=s)n=Pl(o/s|0,i[o],i[o+1],n);else for(let o=t-s;o>=e;o-=s)n=Pl(o/s|0,i[o],i[o+1],n);return n&&Ss(n,n.next)&&(ri(n),n=n.next),n}function rs(i,e){if(!i)return i;e||(e=i);let t=i,s;do if(s=!1,!t.steiner&&(Ss(t,t.next)||Ae(t.prev,t,t.next)===0)){if(ri(t),t=e=t.prev,t===t.next)break;s=!0}else t=t.next;while(s||t!==e);return e}function ti(i,e,t,s,r,n,o){if(!i)return;!o&&n&&bm(i,s,r,n);let a=i;for(;i.prev!==i.next;){const l=i.prev,c=i.next;if(n?um(i,s,r,n):hm(i)){e.push(l.i,i.i,c.i),ri(i),i=c.next,a=c.next;continue}if(i=c,i===a){o?o===1?(i=dm(rs(i),e),ti(i,e,t,s,r,n,2)):o===2&&fm(i,e,t,s,r,n):ti(rs(i),e,t,s,r,n,1);break}}}function hm(i){const e=i.prev,t=i,s=i.next;if(Ae(e,t,s)>=0)return!1;const r=e.x,n=t.x,o=s.x,a=e.y,l=t.y,c=s.y,h=Math.min(r,n,o),u=Math.min(a,l,c),p=Math.max(r,n,o),d=Math.max(a,l,c);let g=s.next;for(;g!==e;){if(g.x>=h&&g.x<=p&&g.y>=u&&g.y<=d&&si(r,a,n,l,o,c,g.x,g.y)&&Ae(g.prev,g,g.next)>=0)return!1;g=g.next}return!0}function um(i,e,t,s){const r=i.prev,n=i,o=i.next;if(Ae(r,n,o)>=0)return!1;const a=r.x,l=n.x,c=o.x,h=r.y,u=n.y,p=o.y,d=Math.min(a,l,c),g=Math.min(h,u,p),_=Math.max(a,l,c),b=Math.max(h,u,p),v=vn(d,g,e,t,s),C=vn(_,b,e,t,s);let E=i.prevZ,S=i.nextZ;for(;E&&E.z>=v&&S&&S.z<=C;){if(E.x>=d&&E.x<=_&&E.y>=g&&E.y<=b&&E!==r&&E!==o&&si(a,h,l,u,c,p,E.x,E.y)&&Ae(E.prev,E,E.next)>=0||(E=E.prevZ,S.x>=d&&S.x<=_&&S.y>=g&&S.y<=b&&S!==r&&S!==o&&si(a,h,l,u,c,p,S.x,S.y)&&Ae(S.prev,S,S.next)>=0))return!1;S=S.nextZ}for(;E&&E.z>=v;){if(E.x>=d&&E.x<=_&&E.y>=g&&E.y<=b&&E!==r&&E!==o&&si(a,h,l,u,c,p,E.x,E.y)&&Ae(E.prev,E,E.next)>=0)return!1;E=E.prevZ}for(;S&&S.z<=C;){if(S.x>=d&&S.x<=_&&S.y>=g&&S.y<=b&&S!==r&&S!==o&&si(a,h,l,u,c,p,S.x,S.y)&&Ae(S.prev,S,S.next)>=0)return!1;S=S.nextZ}return!0}function dm(i,e){let t=i;do{const s=t.prev,r=t.next.next;!Ss(s,r)&&Rl(s,t,t.next,r)&&ii(s,r)&&ii(r,s)&&(e.push(s.i,t.i,r.i),ri(t),ri(t.next),t=i=r),t=t.next}while(t!==i);return rs(t)}function fm(i,e,t,s,r,n){let o=i;do{let a=o.next.next;for(;a!==o.prev;){if(o.i!==a.i&&Cm(o,a)){let l=Ml(o,a);o=rs(o,o.next),l=rs(l,l.next),ti(o,e,t,s,r,n,0),ti(l,e,t,s,r,n,0);return}a=a.next}o=o.next}while(o!==i)}function pm(i,e,t,s){const r=[];for(let n=0,o=e.length;n<o;n++){const a=e[n]*s,l=n<o-1?e[n+1]*s:i.length,c=wl(i,a,l,s,!1);c===c.next&&(c.steiner=!0),r.push(xm(c))}r.sort(mm);for(let n=0;n<r.length;n++)t=gm(r[n],t);return t}function mm(i,e){let t=i.x-e.x;if(t===0&&(t=i.y-e.y,t===0)){const s=(i.next.y-i.y)/(i.next.x-i.x),r=(e.next.y-e.y)/(e.next.x-e.x);t=s-r}return t}function gm(i,e){const t=_m(i,e);if(!t)return e;const s=Ml(t,i);return rs(s,s.next),rs(t,t.next)}function _m(i,e){let t=e;const s=i.x,r=i.y;let n=-1/0,o;if(Ss(i,t))return t;do{if(Ss(i,t.next))return t.next;if(r<=t.y&&r>=t.next.y&&t.next.y!==t.y){const u=t.x+(r-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(u<=s&&u>n&&(n=u,o=t.x<t.next.x?t:t.next,u===s))return o}t=t.next}while(t!==e);if(!o)return null;const a=o,l=o.x,c=o.y;let h=1/0;t=o;do{if(s>=t.x&&t.x>=l&&s!==t.x&&Il(r<c?s:n,r,l,c,r<c?n:s,r,t.x,t.y)){const u=Math.abs(r-t.y)/(s-t.x);ii(t,i)&&(u<h||u===h&&(t.x>o.x||t.x===o.x&&ym(o,t)))&&(o=t,h=u)}t=t.next}while(t!==a);return o}function ym(i,e){return Ae(i.prev,i,e.prev)<0&&Ae(e.next,i,i.next)<0}function bm(i,e,t,s){let r=i;do r.z===0&&(r.z=vn(r.x,r.y,e,t,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next;while(r!==i);r.prevZ.nextZ=null,r.prevZ=null,vm(r)}function vm(i){let e,t=1;do{let s=i,r;i=null;let n=null;for(e=0;s;){e++;let o=s,a=0;for(let c=0;c<t&&(a++,o=o.nextZ,!!o);c++);let l=t;for(;a>0||l>0&&o;)a!==0&&(l===0||!o||s.z<=o.z)?(r=s,s=s.nextZ,a--):(r=o,o=o.nextZ,l--),n?n.nextZ=r:i=r,r.prevZ=n,n=r;s=o}n.nextZ=null,t*=2}while(e>1);return i}function vn(i,e,t,s,r){return i=(i-t)*r|0,e=(e-s)*r|0,i=(i|i<<8)&16711935,i=(i|i<<4)&252645135,i=(i|i<<2)&858993459,i=(i|i<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,i|e<<1}function xm(i){let e=i,t=i;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==i);return t}function Il(i,e,t,s,r,n,o,a){return(r-o)*(e-a)>=(i-o)*(n-a)&&(i-o)*(s-a)>=(t-o)*(e-a)&&(t-o)*(n-a)>=(r-o)*(s-a)}function si(i,e,t,s,r,n,o,a){return!(i===o&&e===a)&&Il(i,e,t,s,r,n,o,a)}function Cm(i,e){return i.next.i!==e.i&&i.prev.i!==e.i&&!Em(i,e)&&(ii(i,e)&&ii(e,i)&&Sm(i,e)&&(Ae(i.prev,i,e.prev)||Ae(i,e.prev,e))||Ss(i,e)&&Ae(i.prev,i,i.next)>0&&Ae(e.prev,e,e.next)>0)}function Ae(i,e,t){return(e.y-i.y)*(t.x-e.x)-(e.x-i.x)*(t.y-e.y)}function Ss(i,e){return i.x===e.x&&i.y===e.y}function Rl(i,e,t,s){const r=Ki(Ae(i,e,t)),n=Ki(Ae(i,e,s)),o=Ki(Ae(t,s,i)),a=Ki(Ae(t,s,e));return!!(r!==n&&o!==a||r===0&&qi(i,t,e)||n===0&&qi(i,s,e)||o===0&&qi(t,i,s)||a===0&&qi(t,e,s))}function qi(i,e,t){return e.x<=Math.max(i.x,t.x)&&e.x>=Math.min(i.x,t.x)&&e.y<=Math.max(i.y,t.y)&&e.y>=Math.min(i.y,t.y)}function Ki(i){return i>0?1:i<0?-1:0}function Em(i,e){let t=i;do{if(t.i!==i.i&&t.next.i!==i.i&&t.i!==e.i&&t.next.i!==e.i&&Rl(t,t.next,i,e))return!0;t=t.next}while(t!==i);return!1}function ii(i,e){return Ae(i.prev,i,i.next)<0?Ae(i,e,i.next)>=0&&Ae(i,i.prev,e)>=0:Ae(i,e,i.prev)<0||Ae(i,i.next,e)<0}function Sm(i,e){let t=i,s=!1;const r=(i.x+e.x)/2,n=(i.y+e.y)/2;do t.y>n!=t.next.y>n&&t.next.y!==t.y&&r<(t.next.x-t.x)*(n-t.y)/(t.next.y-t.y)+t.x&&(s=!s),t=t.next;while(t!==i);return s}function Ml(i,e){const t=xn(i.i,i.x,i.y),s=xn(e.i,e.x,e.y),r=i.next,n=e.prev;return i.next=e,e.prev=i,t.next=r,r.prev=t,s.next=t,t.prev=s,n.next=s,s.prev=n,s}function Pl(i,e,t,s){const r=xn(i,e,t);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function ri(i){i.next.prev=i.prev,i.prev.next=i.next,i.prevZ&&(i.prevZ.nextZ=i.nextZ),i.nextZ&&(i.nextZ.prevZ=i.prevZ)}function xn(i,e,t){return{i,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function Tm(i,e,t,s){let r=0;for(let n=e,o=t-s;n<t;n+=s)r+=(i[o]-i[n])*(i[n+1]+i[o+1]),o=n;return r}const Am=Al.default||Al;var st=(i=>(i[i.NONE=0]="NONE",i[i.COLOR=16384]="COLOR",i[i.STENCIL=1024]="STENCIL",i[i.DEPTH=256]="DEPTH",i[i.COLOR_DEPTH=16640]="COLOR_DEPTH",i[i.COLOR_STENCIL=17408]="COLOR_STENCIL",i[i.DEPTH_STENCIL=1280]="DEPTH_STENCIL",i[i.ALL=17664]="ALL",i))(st||{});class kl{constructor(e){this.items=[],this._name=e}emit(e,t,s,r,n,o,a,l){const{name:c,items:h}=this;for(let u=0,p=h.length;u<p;u++)h[u][c](e,t,s,r,n,o,a,l);return this}add(e){return e[this._name]&&(this.remove(e),this.items.push(e)),this}remove(e){const t=this.items.indexOf(e);return t!==-1&&this.items.splice(t,1),this}contains(e){return this.items.indexOf(e)!==-1}removeAll(){return this.items.length=0,this}destroy(){this.removeAll(),this.items=null,this._name=null}get empty(){return this.items.length===0}get name(){return this._name}}const wm=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],Ol=class ff extends lt{constructor(e){super(),this.tick=0,this.uid=be("renderer"),this.runners=Object.create(null),this.renderPipes=Object.create(null),this._initOptions={},this._systemsHash=Object.create(null),this.type=e.type,this.name=e.name,this.config=e;const t=[...wm,...this.config.runners??[]];this._addRunners(...t),this._unsafeEvalCheck()}async init(e={}){const t=e.skipExtensionImports===!0?!0:e.manageImports===!1;await cm(t),this._addSystems(this.config.systems),this._addPipes(this.config.renderPipes,this.config.renderPipeAdaptors);for(const s in this._systemsHash)e={...this._systemsHash[s].constructor.defaultOptions,...e};e={...ff.defaultOptions,...e},this._roundPixels=e.roundPixels?1:0;for(let s=0;s<this.runners.init.items.length;s++)await this.runners.init.items[s].init(e);this._initOptions=e}render(e,t){this.tick++;let s=e;if(s instanceof Ve&&(s={container:s},t&&(ee(Be,"passing a second argument is deprecated, please use render options instead"),s.target=t.renderTexture)),s.target||(s.target=this.view.renderTarget),s.target===this.view.renderTarget&&(this._lastObjectRendered=s.container,s.clearColor??(s.clearColor=this.background.colorRgba),s.clear??(s.clear=this.background.clearBeforeRender)),s.clearColor){const r=Array.isArray(s.clearColor)&&s.clearColor.length===4;s.clearColor=r?s.clearColor:Pe.shared.setValue(s.clearColor).toArray()}s.transform||(s.container.updateLocalTransform(),s.transform=s.container.localTransform),s.container.visible&&(s.container.enableRenderGroup(),this.runners.prerender.emit(s),this.runners.renderStart.emit(s),this.runners.render.emit(s),this.runners.renderEnd.emit(s),this.runners.postrender.emit(s))}resize(e,t,s){const r=this.view.resolution;this.view.resize(e,t,s),this.emit("resize",this.view.screen.width,this.view.screen.height,this.view.resolution),s!==void 0&&s!==r&&this.runners.resolutionChange.emit(s)}clear(e={}){const t=this;e.target||(e.target=t.renderTarget.renderTarget),e.clearColor||(e.clearColor=this.background.colorRgba),e.clear??(e.clear=st.ALL);const{clear:s,clearColor:r,target:n,mipLevel:o,layer:a}=e;Pe.shared.setValue(r??this.background.colorRgba),t.renderTarget.clear(n,s,Pe.shared.toArray(),o??0,a??0)}get resolution(){return this.view.resolution}set resolution(e){this.view.resolution=e,this.runners.resolutionChange.emit(e)}get width(){return this.view.texture.frame.width}get height(){return this.view.texture.frame.height}get canvas(){return this.view.canvas}get lastObjectRendered(){return this._lastObjectRendered}get renderingToScreen(){return this.renderTarget.renderingToScreen}get screen(){return this.view.screen}_addRunners(...e){e.forEach(t=>{this.runners[t]=new kl(t)})}_addSystems(e){let t;for(t in e){const s=e[t];this._addSystem(s.value,s.name)}}_addSystem(e,t){const s=new e(this);if(this[t])throw new Error(`Whoops! The name "${t}" is already in use`);this[t]=s,this._systemsHash[t]=s;for(const r in this.runners)this.runners[r].add(s);return this}_addPipes(e,t){const s=t.reduce((r,n)=>(r[n.name]=n.value,r),{});e.forEach(r=>{const n=r.value,o=r.name,a=s[o];this.renderPipes[o]=new n(this,a?new a:null),this.runners.destroy.add(this.renderPipes[o])})}destroy(e=!1){this.runners.destroy.items.reverse(),this.runners.destroy.emit(e),(e===!0||typeof e=="object"&&e.releaseGlobalResources)&&ms.release(),Object.values(this.runners).forEach(t=>{t.destroy()}),this._systemsHash=null,this.renderPipes=null,this.removeAllListeners()}generateTexture(e){return this.textureGenerator.generateTexture(e)}get roundPixels(){return!!this._roundPixels}_unsafeEvalCheck(){if(!Tl())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}resetState(){this.runners.resetState.emit()}};Ol.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let ni=Ol,Zi;function Im(i){return Zi!==void 0||(Zi=(()=>{var t;const e={stencil:!0,failIfMajorPerformanceCaveat:i??ni.defaultOptions.failIfMajorPerformanceCaveat};try{if(!pe.get().getWebGLRenderingContext())return!1;let r=pe.get().createCanvas().getContext("webgl",e);const n=!!((t=r==null?void 0:r.getContextAttributes())!=null&&t.stencil);if(r){const o=r.getExtension("WEBGL_lose_context");o&&o.loseContext()}return r=null,n}catch{return!1}})()),Zi}let Ji;async function Rm(i={}){return Ji!==void 0||(Ji=await(async()=>{const e=pe.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(i)).requestDevice(),!0}catch{return!1}})()),Ji}const Bl=["webgl","webgpu","canvas"];async function Mm(i){let e=[];i.preference?(e.push(i.preference),Bl.forEach(n=>{n!==i.preference&&e.push(n)})):e=Bl.slice();let t,s={};for(let n=0;n<e.length;n++){const o=e[n];if(o==="webgpu"&&await Rm()){const{WebGPURenderer:a}=await Promise.resolve().then(()=>Vb);t=a,s={...i,...i.webgpu};break}else if(o==="webgl"&&Im(i.failIfMajorPerformanceCaveat??ni.defaultOptions.failIfMajorPerformanceCaveat)){const{WebGLRenderer:a}=await Promise.resolve().then(()=>xb);t=a,s={...i,...i.webgl};break}else if(o==="canvas"){const{CanvasRenderer:a}=await Promise.resolve().then(()=>vy);t=a,s={...i,...i.canvasOptions};break}}if(delete s.webgpu,delete s.webgl,delete s.canvasOptions,!t)throw new Error("No available renderer for the current environment");const r=new t;return await r.init(s),r}const Qi="8.17.1";class Dl{static init(){var e;(e=globalThis.__PIXI_APP_INIT__)==null||e.call(globalThis,this,Qi)}static destroy(){}}Dl.extension=A.Application;class Nl{constructor(e){this._renderer=e}init(){var e;(e=globalThis.__PIXI_RENDERER_INIT__)==null||e.call(globalThis,this._renderer,Qi)}destroy(){this._renderer=null}}Nl.extension={type:[A.WebGLSystem,A.WebGPUSystem],name:"initHook",priority:-10};class Ul{static init(e){Object.defineProperty(this,"resizeTo",{configurable:!0,set(t){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=t,t&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&(cancelAnimationFrame(this._resizeId),this._resizeId=null)},this.resize=()=>{if(!this._resizeTo)return;this._cancelResize();let t,s;if(this._resizeTo===globalThis.window)t=globalThis.innerWidth,s=globalThis.innerHeight;else{const{clientWidth:r,clientHeight:n}=this._resizeTo;t=r,s=n}this.renderer.resize(t,s),this.render()},this._resizeId=null,this._resizeTo=null,this.resizeTo=e.resizeTo||null}static destroy(){globalThis.removeEventListener("resize",this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}}Ul.extension=A.Application;class Gl{static init(e){e=Object.assign({autoStart:!0,sharedTicker:!1},e),Object.defineProperty(this,"ticker",{configurable:!0,set(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this,ys.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?at.shared:new at,e.autoStart&&this.start()}static destroy(){if(this._ticker){const e=this._ticker;this.ticker=null,e.destroy()}}}Gl.extension=A.Application,Q.add(Ul),Q.add(Gl);const Fl=class ea{constructor(...e){this.stage=new Ve,e[0]!==void 0&&ee(Be,"Application constructor options are deprecated, please use Application.init() instead.")}async init(e){e={...e},this.stage||(this.stage=new Ve),this.renderer=await Mm(e),ea._plugins.forEach(t=>{t.init.call(this,e)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return ee(Be,"Application.view is deprecated, please use Application.canvas instead."),this.renderer.canvas}get screen(){return this.renderer.screen}destroy(e=!1,t=!1){const s=ea._plugins.slice(0);s.reverse(),s.forEach(r=>{r.destroy.call(this)}),this.stage.destroy(t),this.stage=null,this.renderer.destroy(e),this.renderer=null}};Fl._plugins=[];let Ll=Fl;Q.handleByList(A.Application,Ll._plugins),Q.add(Dl);var Cn,Wl;function Pm(){if(Wl)return Cn;Wl=1,Cn=t;var i={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},e=/([astvzqmhlc])([^astvzqmhlc]*)/ig;function t(n){var o=[];return n.replace(e,function(a,l,c){var h=l.toLowerCase();for(c=r(c),h=="m"&&c.length>2&&(o.push([l].concat(c.splice(0,2))),h="l",l=l=="m"?"l":"L");;){if(c.length==i[h])return c.unshift(l),o.push(c);if(c.length<i[h])throw new Error("malformed path data");o.push([l].concat(c.splice(0,i[h])))}}),o}var s=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig;function r(n){var o=n.match(s);return o?o.map(Number):[]}return Cn}var km=Pm();const Om=oa(km);function Bm(i,e){const t=Om(i),s=[];let r=null,n=0,o=0;for(let a=0;a<t.length;a++){const l=t[a],c=l[0],h=l;switch(c){case"M":n=h[1],o=h[2],e.moveTo(n,o);break;case"m":n+=h[1],o+=h[2],e.moveTo(n,o);break;case"H":n=h[1],e.lineTo(n,o);break;case"h":n+=h[1],e.lineTo(n,o);break;case"V":o=h[1],e.lineTo(n,o);break;case"v":o+=h[1],e.lineTo(n,o);break;case"L":n=h[1],o=h[2],e.lineTo(n,o);break;case"l":n+=h[1],o+=h[2],e.lineTo(n,o);break;case"C":n=h[5],o=h[6],e.bezierCurveTo(h[1],h[2],h[3],h[4],n,o);break;case"c":e.bezierCurveTo(n+h[1],o+h[2],n+h[3],o+h[4],n+h[5],o+h[6]),n+=h[5],o+=h[6];break;case"S":n=h[3],o=h[4],e.bezierCurveToShort(h[1],h[2],n,o);break;case"s":e.bezierCurveToShort(n+h[1],o+h[2],n+h[3],o+h[4]),n+=h[3],o+=h[4];break;case"Q":n=h[3],o=h[4],e.quadraticCurveTo(h[1],h[2],n,o);break;case"q":e.quadraticCurveTo(n+h[1],o+h[2],n+h[3],o+h[4]),n+=h[3],o+=h[4];break;case"T":n=h[1],o=h[2],e.quadraticCurveToShort(n,o);break;case"t":n+=h[1],o+=h[2],e.quadraticCurveToShort(n,o);break;case"A":n=h[6],o=h[7],e.arcToSvg(h[1],h[2],h[3],h[4],h[5],n,o);break;case"a":n+=h[6],o+=h[7],e.arcToSvg(h[1],h[2],h[3],h[4],h[5],n,o);break;case"Z":case"z":e.closePath(),s.length>0&&(r=s.pop(),r?(n=r.startX,o=r.startY):(n=0,o=0)),r=null;break;default:ie(`Unknown SVG path command: ${c}`)}c!=="Z"&&c!=="z"&&r===null&&(r={startX:n,startY:o},s.push(r))}return e}class En{constructor(e=0,t=0,s=0){this.type="circle",this.x=e,this.y=t,this.radius=s}clone(){return new En(this.x,this.y,this.radius)}contains(e,t){if(this.radius<=0)return!1;const s=this.radius*this.radius;let r=this.x-e,n=this.y-t;return r*=r,n*=n,r+n<=s}strokeContains(e,t,s,r=.5){if(this.radius===0)return!1;const n=this.x-e,o=this.y-t,a=this.radius,l=(1-r)*s,c=Math.sqrt(n*n+o*o);return c<=a+l&&c>a-(s-l)}getBounds(e){return e||(e=new Ce),e.x=this.x-this.radius,e.y=this.y-this.radius,e.width=this.radius*2,e.height=this.radius*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.radius=e.radius,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`}}class Sn{constructor(e=0,t=0,s=0,r=0){this.type="ellipse",this.x=e,this.y=t,this.halfWidth=s,this.halfHeight=r}clone(){return new Sn(this.x,this.y,this.halfWidth,this.halfHeight)}contains(e,t){if(this.halfWidth<=0||this.halfHeight<=0)return!1;let s=(e-this.x)/this.halfWidth,r=(t-this.y)/this.halfHeight;return s*=s,r*=r,s+r<=1}strokeContains(e,t,s,r=.5){const{halfWidth:n,halfHeight:o}=this;if(n<=0||o<=0)return!1;const a=s*(1-r),l=s-a,c=n-l,h=o-l,u=n+a,p=o+a,d=e-this.x,g=t-this.y,_=d*d/(c*c)+g*g/(h*h),b=d*d/(u*u)+g*g/(p*p);return _>1&&b<=1}getBounds(e){return e||(e=new Ce),e.x=this.x-this.halfWidth,e.y=this.y-this.halfHeight,e.width=this.halfWidth*2,e.height=this.halfHeight*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.halfWidth=e.halfWidth,this.halfHeight=e.halfHeight,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Ellipse x=${this.x} y=${this.y} halfWidth=${this.halfWidth} halfHeight=${this.halfHeight}]`}}function Dm(i,e,t,s,r,n){const o=i-t,a=e-s,l=r-t,c=n-s,h=o*l+a*c,u=l*l+c*c;let p=-1;u!==0&&(p=h/u);let d,g;p<0?(d=t,g=s):p>1?(d=r,g=n):(d=t+p*l,g=s+p*c);const _=i-d,b=e-g;return _*_+b*b}let Nm,Um;class oi{constructor(...e){this.type="polygon";let t=Array.isArray(e[0])?e[0]:e;if(typeof t[0]!="number"){const s=[];for(let r=0,n=t.length;r<n;r++)s.push(t[r].x,t[r].y);t=s}this.points=t,this.closePath=!0}isClockwise(){let e=0;const t=this.points,s=t.length;for(let r=0;r<s;r+=2){const n=t[r],o=t[r+1],a=t[(r+2)%s],l=t[(r+3)%s];e+=(a-n)*(l+o)}return e<0}containsPolygon(e){const t=this.getBounds(Nm),s=e.getBounds(Um);if(!t.containsRect(s))return!1;const r=e.points;for(let n=0;n<r.length;n+=2){const o=r[n],a=r[n+1];if(!this.contains(o,a))return!1}return!0}clone(){const e=this.points.slice(),t=new oi(e);return t.closePath=this.closePath,t}contains(e,t){let s=!1;const r=this.points.length/2;for(let n=0,o=r-1;n<r;o=n++){const a=this.points[n*2],l=this.points[n*2+1],c=this.points[o*2],h=this.points[o*2+1];l>t!=h>t&&e<(c-a)*((t-l)/(h-l))+a&&(s=!s)}return s}strokeContains(e,t,s,r=.5){const n=s*s,o=n*(1-r),a=n-o,{points:l}=this,c=l.length-(this.closePath?0:2);for(let h=0;h<c;h+=2){const u=l[h],p=l[h+1],d=l[(h+2)%l.length],g=l[(h+3)%l.length],_=Dm(e,t,u,p,d,g),b=Math.sign((d-u)*(t-p)-(g-p)*(e-u));if(_<=(b<0?a:o))return!0}return!1}getBounds(e){e||(e=new Ce);const t=this.points;let s=1/0,r=-1/0,n=1/0,o=-1/0;for(let a=0,l=t.length;a<l;a+=2){const c=t[a],h=t[a+1];s=c<s?c:s,r=c>r?c:r,n=h<n?h:n,o=h>o?h:o}return e.x=s,e.width=r-s,e.y=n,e.height=o-n,e}copyFrom(e){return this.points=e.points.slice(),this.closePath=e.closePath,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:PolygoncloseStroke=${this.closePath}points=${this.points.reduce((e,t)=>`${e}, ${t}`,"")}]`}get lastX(){return this.points[this.points.length-2]}get lastY(){return this.points[this.points.length-1]}get x(){return ee("8.11.0","Polygon.lastX is deprecated, please use Polygon.lastX instead."),this.points[this.points.length-2]}get y(){return ee("8.11.0","Polygon.y is deprecated, please use Polygon.lastY instead."),this.points[this.points.length-1]}get startX(){return this.points[0]}get startY(){return this.points[1]}}const er=(i,e,t,s,r,n,o)=>{const a=i-t,l=e-s,c=Math.sqrt(a*a+l*l);return c>=r-n&&c<=r+o};class Tn{constructor(e=0,t=0,s=0,r=0,n=20){this.type="roundedRectangle",this.x=e,this.y=t,this.width=s,this.height=r,this.radius=n}getBounds(e){return e||(e=new Ce),e.x=this.x,e.y=this.y,e.width=this.width,e.height=this.height,e}clone(){return new Tn(this.x,this.y,this.width,this.height,this.radius)}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){if(this.width<=0||this.height<=0)return!1;if(e>=this.x&&e<=this.x+this.width&&t>=this.y&&t<=this.y+this.height){const s=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(t>=this.y+s&&t<=this.y+this.height-s||e>=this.x+s&&e<=this.x+this.width-s)return!0;let r=e-(this.x+s),n=t-(this.y+s);const o=s*s;if(r*r+n*n<=o||(r=e-(this.x+this.width-s),r*r+n*n<=o)||(n=t-(this.y+this.height-s),r*r+n*n<=o)||(r=e-(this.x+s),r*r+n*n<=o))return!0}return!1}strokeContains(e,t,s,r=.5){const{x:n,y:o,width:a,height:l,radius:c}=this,h=s*(1-r),u=s-h,p=n+c,d=o+c,g=a-c*2,_=l-c*2,b=n+a,v=o+l;return(e>=n-h&&e<=n+u||e>=b-u&&e<=b+h)&&t>=d&&t<=d+_||(t>=o-h&&t<=o+u||t>=v-u&&t<=v+h)&&e>=p&&e<=p+g?!0:e<p&&t<d&&er(e,t,p,d,c,u,h)||e>b-c&&t<d&&er(e,t,b-c,d,c,u,h)||e>b-c&&t>v-c&&er(e,t,b-c,v-c,c,u,h)||e<p&&t>v-c&&er(e,t,p,v-c,c,u,h)}toString(){return`[pixi.js/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`}}const Hl={};function An(i,e,t){let s=2166136261;for(let r=0;r<e;r++)s^=i[r].uid,s=Math.imul(s,16777619),s>>>=0;return Hl[s]||Gm(i,e,s,t)}function Gm(i,e,t,s){const r={};let n=0;for(let a=0;a<s;a++){const l=a<e?i[a]:j.EMPTY.source;r[n++]=l.source,r[n++]=l.style}const o=new Nt(r);return Hl[t]=o,o}class Vl{constructor(e){typeof e=="number"?this.rawBinaryData=new ArrayBuffer(e):e instanceof Uint8Array?this.rawBinaryData=e.buffer:this.rawBinaryData=e,this.uint32View=new Uint32Array(this.rawBinaryData),this.float32View=new Float32Array(this.rawBinaryData),this.size=this.rawBinaryData.byteLength}get int8View(){return this._int8View||(this._int8View=new Int8Array(this.rawBinaryData)),this._int8View}get uint8View(){return this._uint8View||(this._uint8View=new Uint8Array(this.rawBinaryData)),this._uint8View}get int16View(){return this._int16View||(this._int16View=new Int16Array(this.rawBinaryData)),this._int16View}get int32View(){return this._int32View||(this._int32View=new Int32Array(this.rawBinaryData)),this._int32View}get float64View(){return this._float64Array||(this._float64Array=new Float64Array(this.rawBinaryData)),this._float64Array}get bigUint64View(){return this._bigUint64Array||(this._bigUint64Array=new BigUint64Array(this.rawBinaryData)),this._bigUint64Array}view(e){return this[`${e}View`]}destroy(){this.rawBinaryData=null,this.uint32View=null,this.float32View=null,this.uint16View=null,this._int8View=null,this._uint8View=null,this._int16View=null,this._int32View=null,this._float64Array=null,this._bigUint64Array=null}static sizeOf(e){switch(e){case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;default:throw new Error(`${e} isn't a valid view type`)}}}function wn(i,e,t,s){if(t??(t=0),s??(s=Math.min(i.byteLength-t,e.byteLength)),!(t&7)&&!(s&7)){const r=s/8;new Float64Array(e,0,r).set(new Float64Array(i,t,r))}else if(!(t&3)&&!(s&3)){const r=s/4;new Float32Array(e,0,r).set(new Float32Array(i,t,r))}else new Uint8Array(e).set(new Uint8Array(i,t,s))}const Fm={normal:"normal-npm",add:"add-npm",screen:"screen-npm"};var ke=(i=>(i[i.DISABLED=0]="DISABLED",i[i.RENDERING_MASK_ADD=1]="RENDERING_MASK_ADD",i[i.MASK_ACTIVE=2]="MASK_ACTIVE",i[i.INVERSE_MASK_ACTIVE=3]="INVERSE_MASK_ACTIVE",i[i.RENDERING_MASK_REMOVE=4]="RENDERING_MASK_REMOVE",i[i.NONE=5]="NONE",i))(ke||{});function zl(i,e){return e.alphaMode==="no-premultiply-alpha"&&Fm[i]||i}const Lm=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join(`
|
|
36
|
+
`);function Wm(i){let e="";for(let t=0;t<i;++t)t>0&&(e+=`
|
|
37
|
+
else `),t<i-1&&(e+=`if(test == ${t}.0){}`);return e}function $l(i,e){if(i===0)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const t=e.createShader(e.FRAGMENT_SHADER);try{for(;;){const s=Lm.replace(/%forloop%/gi,Wm(i));if(e.shaderSource(t,s),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS))i=i/2|0;else break}}finally{e.deleteShader(t)}return i}let Ts=null;function Hm(){var e;if(Ts)return Ts;const i=gl();return Ts=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),Ts=$l(Ts,i),(e=i.getExtension("WEBGL_lose_context"))==null||e.loseContext(),Ts}class Vm{constructor(){this.ids=Object.create(null),this.textures=[],this.count=0}clear(){for(let e=0;e<this.count;e++){const t=this.textures[e];this.textures[e]=null,this.ids[t.uid]=null}this.count=0}}class zm{constructor(){this.renderPipeId="batch",this.action="startBatch",this.start=0,this.size=0,this.textures=new Vm,this.blendMode="normal",this.topology="triangle-strip",this.canBundle=!0}destroy(){this.textures=null,this.gpuBindGroup=null,this.bindGroup=null,this.batcher=null,this.elements=null}}const ai=[];let tr=0;ms.register({clear:()=>{if(ai.length>0)for(const i of ai)i&&i.destroy();ai.length=0,tr=0}});function jl(){return tr>0?ai[--tr]:new zm}function Xl(i){i.elements=null,ai[tr++]=i}let li=0;const Yl=class pf{constructor(e){this.uid=be("batcher"),this.dirty=!0,this.batchIndex=0,this.batches=[],this._elements=[],e={...pf.defaultOptions,...e},e.maxTextures||(ee("v8.8.0","maxTextures is a required option for Batcher now, please pass it in the options"),e.maxTextures=Hm());const{maxTextures:t,attributesInitialSize:s,indicesInitialSize:r}=e;this.attributeBuffer=new Vl(s*4),this.indexBuffer=new Uint16Array(r),this.maxTextures=t}begin(){this.elementSize=0,this.elementStart=0,this.indexSize=0,this.attributeSize=0;for(let e=0;e<this.batchIndex;e++)Xl(this.batches[e]);this.batchIndex=0,this._batchIndexStart=0,this._batchIndexSize=0,this.dirty=!0}add(e){this._elements[this.elementSize++]=e,e._indexStart=this.indexSize,e._attributeStart=this.attributeSize,e._batcher=this,this.indexSize+=e.indexSize,this.attributeSize+=e.attributeSize*this.vertexSize}checkAndUpdateTexture(e,t){const s=e._batch.textures.ids[t._source.uid];return!s&&s!==0?!1:(e._textureId=s,e.texture=t,!0)}updateElement(e){this.dirty=!0;const t=this.attributeBuffer;e.packAsQuad?this.packQuadAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId):this.packAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId)}break(e){const t=this._elements;if(!t[this.elementStart])return;let s=jl(),r=s.textures;r.clear();const n=t[this.elementStart];let o=zl(n.blendMode,n.texture._source),a=n.topology;this.attributeSize*4>this.attributeBuffer.size&&this._resizeAttributeBuffer(this.attributeSize*4),this.indexSize>this.indexBuffer.length&&this._resizeIndexBuffer(this.indexSize);const l=this.attributeBuffer.float32View,c=this.attributeBuffer.uint32View,h=this.indexBuffer;let u=this._batchIndexSize,p=this._batchIndexStart,d="startBatch",g=[];const _=this.maxTextures;for(let b=this.elementStart;b<this.elementSize;++b){const v=t[b];t[b]=null;const E=v.texture._source,S=zl(v.blendMode,E),w=o!==S||a!==v.topology;if(E._batchTick===li&&!w){v._textureId=E._textureBindLocation,u+=v.indexSize,v.packAsQuad?(this.packQuadAttributes(v,l,c,v._attributeStart,v._textureId),this.packQuadIndex(h,v._indexStart,v._attributeStart/this.vertexSize)):(this.packAttributes(v,l,c,v._attributeStart,v._textureId),this.packIndex(v,h,v._indexStart,v._attributeStart/this.vertexSize)),v._batch=s,g.push(v);continue}E._batchTick=li,(r.count>=_||w)&&(this._finishBatch(s,p,u-p,r,o,a,e,d,g),d="renderBatch",p=u,o=S,a=v.topology,s=jl(),r=s.textures,r.clear(),g=[],++li),v._textureId=E._textureBindLocation=r.count,r.ids[E.uid]=r.count,r.textures[r.count++]=E,v._batch=s,g.push(v),u+=v.indexSize,v.packAsQuad?(this.packQuadAttributes(v,l,c,v._attributeStart,v._textureId),this.packQuadIndex(h,v._indexStart,v._attributeStart/this.vertexSize)):(this.packAttributes(v,l,c,v._attributeStart,v._textureId),this.packIndex(v,h,v._indexStart,v._attributeStart/this.vertexSize))}r.count>0&&(this._finishBatch(s,p,u-p,r,o,a,e,d,g),p=u,++li),this.elementStart=this.elementSize,this._batchIndexStart=p,this._batchIndexSize=u}_finishBatch(e,t,s,r,n,o,a,l,c){e.gpuBindGroup=null,e.bindGroup=null,e.action=l,e.batcher=this,e.textures=r,e.blendMode=n,e.topology=o,e.start=t,e.size=s,e.elements=c,++li,this.batches[this.batchIndex++]=e,a.add(e)}finish(e){this.break(e)}ensureAttributeBuffer(e){e*4<=this.attributeBuffer.size||this._resizeAttributeBuffer(e*4)}ensureIndexBuffer(e){e<=this.indexBuffer.length||this._resizeIndexBuffer(e)}_resizeAttributeBuffer(e){const t=Math.max(e,this.attributeBuffer.size*2),s=new Vl(t);wn(this.attributeBuffer.rawBinaryData,s.rawBinaryData),this.attributeBuffer=s}_resizeIndexBuffer(e){const t=this.indexBuffer;let s=Math.max(e,t.length*1.5);s+=s%2;const r=s>65535?new Uint32Array(s):new Uint16Array(s);if(r.BYTES_PER_ELEMENT!==t.BYTES_PER_ELEMENT)for(let n=0;n<t.length;n++)r[n]=t[n];else wn(t.buffer,r.buffer);this.indexBuffer=r}packQuadIndex(e,t,s){e[t]=s+0,e[t+1]=s+1,e[t+2]=s+2,e[t+3]=s+0,e[t+4]=s+2,e[t+5]=s+3}packIndex(e,t,s,r){const n=e.indices,o=e.indexSize,a=e.indexOffset,l=e.attributeOffset;for(let c=0;c<o;c++)t[s++]=r+n[c+a]-l}destroy(e={}){var t;if(this.batches!==null){for(let s=0;s<this.batchIndex;s++)Xl(this.batches[s]);this.batches=null,this.geometry.destroy(!0),this.geometry=null,e.shader&&((t=this.shader)==null||t.destroy(),this.shader=null);for(let s=0;s<this._elements.length;s++)this._elements[s]&&(this._elements[s]._batch=null);this._elements=null,this.indexBuffer=null,this.attributeBuffer.destroy(),this.attributeBuffer=null}}};Yl.defaultOptions={maxTextures:null,attributesInitialSize:4,indicesInitialSize:6};let $m=Yl;var Ee=(i=>(i[i.MAP_READ=1]="MAP_READ",i[i.MAP_WRITE=2]="MAP_WRITE",i[i.COPY_SRC=4]="COPY_SRC",i[i.COPY_DST=8]="COPY_DST",i[i.INDEX=16]="INDEX",i[i.VERTEX=32]="VERTEX",i[i.UNIFORM=64]="UNIFORM",i[i.STORAGE=128]="STORAGE",i[i.INDIRECT=256]="INDIRECT",i[i.QUERY_RESOLVE=512]="QUERY_RESOLVE",i[i.STATIC=1024]="STATIC",i))(Ee||{});let Ut=class extends lt{constructor(e){let{data:t,size:s}=e;const{usage:r,label:n,shrinkToFit:o}=e;super(),this._gpuData=Object.create(null),this._gcLastUsed=-1,this.autoGarbageCollect=!0,this.uid=be("buffer"),this._resourceType="buffer",this._resourceId=be("resource"),this._touched=0,this._updateID=1,this._dataInt32=null,this.shrinkToFit=!0,this.destroyed=!1,t instanceof Array&&(t=new Float32Array(t)),this._data=t,s??(s=t==null?void 0:t.byteLength);const a=!!t;this.descriptor={size:s,usage:r,mappedAtCreation:a,label:n},this.shrinkToFit=o??!0}get data(){return this._data}set data(e){this.setDataWithSize(e,e.length,!0)}get dataInt32(){return this._dataInt32||(this._dataInt32=new Int32Array(this.data.buffer)),this._dataInt32}get static(){return!!(this.descriptor.usage&Ee.STATIC)}set static(e){e?this.descriptor.usage|=Ee.STATIC:this.descriptor.usage&=~Ee.STATIC}setDataWithSize(e,t,s){if(this._updateID++,this._updateSize=t*e.BYTES_PER_ELEMENT,this._data===e){s&&this.emit("update",this);return}const r=this._data;if(this._data=e,this._dataInt32=null,!r||r.length!==e.length){!this.shrinkToFit&&r&&e.byteLength<r.byteLength?s&&this.emit("update",this):(this.descriptor.size=e.byteLength,this._resourceId=be("resource"),this.emit("change",this));return}s&&this.emit("update",this)}update(e){this._updateSize=e??this._updateSize,this._updateID++,this.emit("update",this)}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this.emit("change",this),this._data=null,this.descriptor=null,this.removeAllListeners()}};function ql(i,e){if(!(i instanceof Ut)){let t=e?Ee.INDEX:Ee.VERTEX;i instanceof Array&&(e?(i=new Uint32Array(i),t=Ee.INDEX|Ee.COPY_DST):(i=new Float32Array(i),t=Ee.VERTEX|Ee.COPY_DST)),i=new Ut({data:i,label:e?"index-mesh-buffer":"vertex-mesh-buffer",usage:t})}return i}function jm(i,e,t){const s=i.getAttribute(e);if(!s)return t.minX=0,t.minY=0,t.maxX=0,t.maxY=0,t;const r=s.buffer.data;let n=1/0,o=1/0,a=-1/0,l=-1/0;const c=r.BYTES_PER_ELEMENT,h=(s.offset||0)/c,u=(s.stride||8)/c;for(let p=h;p<r.length;p+=u){const d=r[p],g=r[p+1];d>a&&(a=d),g>l&&(l=g),d<n&&(n=d),g<o&&(o=g)}return t.minX=n,t.minY=o,t.maxX=a,t.maxY=l,t}function Xm(i){return(i instanceof Ut||Array.isArray(i)||i.BYTES_PER_ELEMENT)&&(i={buffer:i}),i.buffer=ql(i.buffer,!1),i}class In extends lt{constructor(e={}){super(),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=be("geometry"),this._layoutKey=0,this.instanceCount=1,this._bounds=new Ye,this._boundsDirty=!0;const{attributes:t,indexBuffer:s,topology:r}=e;if(this.buffers=[],this.attributes={},t)for(const n in t)this.addAttribute(n,t[n]);this.instanceCount=e.instanceCount??1,s&&this.addIndex(s),this.topology=r||"triangle-list"}onBufferUpdate(){this._boundsDirty=!0,this.emit("update",this)}getAttribute(e){return this.attributes[e]}getIndex(){return this.indexBuffer}getBuffer(e){return this.getAttribute(e).buffer}getSize(){for(const e in this.attributes){const t=this.attributes[e];return t.buffer.data.length/(t.stride/4||t.size)}return 0}addAttribute(e,t){const s=Xm(t);this.buffers.indexOf(s.buffer)===-1&&(this.buffers.push(s.buffer),s.buffer.on("update",this.onBufferUpdate,this),s.buffer.on("change",this.onBufferUpdate,this)),this.attributes[e]=s}addIndex(e){this.indexBuffer=ql(e,!0),this.buffers.push(this.indexBuffer)}get bounds(){return this._boundsDirty?(this._boundsDirty=!1,jm(this,"aPosition",this._bounds)):this._bounds}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(e=!1){var t;this.emit("destroy",this),this.removeAllListeners(),e&&this.buffers.forEach(s=>s.destroy()),this.unload(),(t=this.indexBuffer)==null||t.destroy(),this.attributes=null,this.buffers=null,this.indexBuffer=null,this._bounds=null}}const Ym=new Float32Array(1),qm=new Uint32Array(1);class Km extends In{constructor(){const t=new Ut({data:Ym,label:"attribute-batch-buffer",usage:Ee.VERTEX|Ee.COPY_DST,shrinkToFit:!1}),s=new Ut({data:qm,label:"index-batch-buffer",usage:Ee.INDEX|Ee.COPY_DST,shrinkToFit:!1}),r=24;super({attributes:{aPosition:{buffer:t,format:"float32x2",stride:r,offset:0},aUV:{buffer:t,format:"float32x2",stride:r,offset:8},aColor:{buffer:t,format:"unorm8x4",stride:r,offset:16},aTextureIdAndRound:{buffer:t,format:"uint16x2",stride:r,offset:20}},indexBuffer:s})}}function Kl(i,e,t){if(i)for(const s in i){const r=s.toLocaleLowerCase(),n=e[r];if(n){let o=i[s];s==="header"&&(o=o.replace(/@in\s+[^;]+;\s*/g,"").replace(/@out\s+[^;]+;\s*/g,"")),t&&n.push(`//----${t}----//`),n.push(o)}else ie(`${s} placement hook does not exist in shader`)}}const Zm=/\{\{(.*?)\}\}/g;function Zl(i){var s;const e={};return(((s=i.match(Zm))==null?void 0:s.map(r=>r.replace(/[{()}]/g,"")))??[]).forEach(r=>{e[r]=[]}),e}function Jl(i,e){let t;const s=/@in\s+([^;]+);/g;for(;(t=s.exec(i))!==null;)e.push(t[1])}function Ql(i,e,t=!1){const s=[];Jl(e,s),i.forEach(a=>{a.header&&Jl(a.header,s)});const r=s;t&&r.sort();const n=r.map((a,l)=>` @location(${l}) ${a},`).join(`
|
|
38
38
|
`);let o=e.replace(/@in\s+[^;]+;\s*/g,"");return o=o.replace("{{in}}",`
|
|
39
39
|
${n}
|
|
40
|
-
`),o}function ec(i,e){let t;const s=/@out\s+([^;]+);/g;for(;(t=s.exec(i))!==null;)e.push(t[1])}function
|
|
41
|
-
`),n=t.sort().map(l=>` var ${
|
|
40
|
+
`),o}function ec(i,e){let t;const s=/@out\s+([^;]+);/g;for(;(t=s.exec(i))!==null;)e.push(t[1])}function Jm(i){const t=/\b(\w+)\s*:/g.exec(i);return t?t[1]:""}function Qm(i){const e=/@.*?\s+/g;return i.replace(e,"")}function eg(i,e){const t=[];ec(e,t),i.forEach(l=>{l.header&&ec(l.header,t)});let s=0;const r=t.sort().map(l=>l.indexOf("builtin")>-1?l:`@location(${s++}) ${l}`).join(`,
|
|
41
|
+
`),n=t.sort().map(l=>` var ${Qm(l)};`).join(`
|
|
42
42
|
`),o=`return VSOutput(
|
|
43
|
-
${t.sort().map(l=>` ${
|
|
43
|
+
${t.sort().map(l=>` ${Jm(l)}`).join(`,
|
|
44
44
|
`)});`;let a=e.replace(/@out\s+[^;]+;\s*/g,"");return a=a.replace("{{struct}}",`
|
|
45
45
|
${r}
|
|
46
46
|
`),a=a.replace("{{start}}",`
|
|
@@ -51,7 +51,7 @@ ${o}
|
|
|
51
51
|
`).length?t=t.replace(`{{${s}}}`,`//-----${s} START-----//
|
|
52
52
|
${r.join(`
|
|
53
53
|
`)}
|
|
54
|
-
//----${s} FINISH----//`):t=t.replace(`{{${s}}}`,"")}return t}const Gt=Object.create(null),Rn=new Map;let
|
|
54
|
+
//----${s} FINISH----//`):t=t.replace(`{{${s}}}`,"")}return t}const Gt=Object.create(null),Rn=new Map;let tg=0;function sg({template:i,bits:e}){const t=sc(i,e);if(Gt[t])return Gt[t];const{vertex:s,fragment:r}=rg(i,e);return Gt[t]=ic(s,r,e),Gt[t]}function ig({template:i,bits:e}){const t=sc(i,e);return Gt[t]||(Gt[t]=ic(i.vertex,i.fragment,e)),Gt[t]}function rg(i,e){const t=e.map(o=>o.vertex).filter(o=>!!o),s=e.map(o=>o.fragment).filter(o=>!!o);let r=Ql(t,i.vertex,!0);r=eg(t,r);const n=Ql(s,i.fragment,!0);return{vertex:r,fragment:n}}function sc(i,e){return e.map(t=>(Rn.has(t)||Rn.set(t,tg++),Rn.get(t))).sort((t,s)=>t-s).join("-")+i.vertex+i.fragment}function ic(i,e,t){const s=Zl(i),r=Zl(e);return t.forEach(n=>{Kl(n.vertex,s,n.name),Kl(n.fragment,r,n.name)}),{vertex:tc(i,s),fragment:tc(e,r)}}const ng=`
|
|
55
55
|
@in aPosition: vec2<f32>;
|
|
56
56
|
@in aUV: vec2<f32>;
|
|
57
57
|
|
|
@@ -95,7 +95,7 @@ ${r.join(`
|
|
|
95
95
|
|
|
96
96
|
{{return}}
|
|
97
97
|
};
|
|
98
|
-
`,
|
|
98
|
+
`,og=`
|
|
99
99
|
@in vUV : vec2<f32>;
|
|
100
100
|
@in vColor : vec4<f32>;
|
|
101
101
|
|
|
@@ -118,7 +118,7 @@ ${r.join(`
|
|
|
118
118
|
|
|
119
119
|
return finalColor;
|
|
120
120
|
};
|
|
121
|
-
`,
|
|
121
|
+
`,ag=`
|
|
122
122
|
in vec2 aPosition;
|
|
123
123
|
in vec2 aUV;
|
|
124
124
|
|
|
@@ -154,7 +154,7 @@ ${r.join(`
|
|
|
154
154
|
|
|
155
155
|
{{end}}
|
|
156
156
|
}
|
|
157
|
-
`,
|
|
157
|
+
`,lg=`
|
|
158
158
|
|
|
159
159
|
in vec4 vColor;
|
|
160
160
|
in vec2 vUV;
|
|
@@ -175,7 +175,7 @@ ${r.join(`
|
|
|
175
175
|
|
|
176
176
|
{{end}}
|
|
177
177
|
}
|
|
178
|
-
`,
|
|
178
|
+
`,cg={name:"global-uniforms-bit",vertex:{header:`
|
|
179
179
|
struct GlobalUniforms {
|
|
180
180
|
uProjectionMatrix:mat3x3<f32>,
|
|
181
181
|
uWorldTransformMatrix:mat3x3<f32>,
|
|
@@ -184,12 +184,12 @@ ${r.join(`
|
|
|
184
184
|
}
|
|
185
185
|
|
|
186
186
|
@group(0) @binding(0) var<uniform> globalUniforms : GlobalUniforms;
|
|
187
|
-
`}},
|
|
187
|
+
`}},hg={name:"global-uniforms-bit",vertex:{header:`
|
|
188
188
|
uniform mat3 uProjectionMatrix;
|
|
189
189
|
uniform mat3 uWorldTransformMatrix;
|
|
190
190
|
uniform vec4 uWorldColorAlpha;
|
|
191
191
|
uniform vec2 uResolution;
|
|
192
|
-
`}};function Mn({bits:i,name:e}){const t=
|
|
192
|
+
`}};function Mn({bits:i,name:e}){const t=sg({template:{fragment:og,vertex:ng},bits:[cg,...i]});return is.from({name:e,vertex:{source:t.vertex,entryPoint:"main"},fragment:{source:t.fragment,entryPoint:"main"}})}function Pn({bits:i,name:e}){return new Es({name:e,...ig({template:{vertex:ag,fragment:lg},bits:[hg,...i]})})}const rc={name:"color-bit",vertex:{header:`
|
|
193
193
|
@in aColor: vec4<f32>;
|
|
194
194
|
`,main:`
|
|
195
195
|
vColor *= vec4<f32>(aColor.rgb * aColor.a, aColor.a);
|
|
@@ -197,8 +197,8 @@ ${r.join(`
|
|
|
197
197
|
in vec4 aColor;
|
|
198
198
|
`,main:`
|
|
199
199
|
vColor *= vec4(aColor.rgb * aColor.a, aColor.a);
|
|
200
|
-
`}},kn={};function
|
|
201
|
-
`)}function
|
|
200
|
+
`}},kn={};function ug(i){const e=[];if(i===1)e.push("@group(1) @binding(0) var textureSource1: texture_2d<f32>;"),e.push("@group(1) @binding(1) var textureSampler1: sampler;");else{let t=0;for(let s=0;s<i;s++)e.push(`@group(1) @binding(${t++}) var textureSource${s+1}: texture_2d<f32>;`),e.push(`@group(1) @binding(${t++}) var textureSampler${s+1}: sampler;`)}return e.join(`
|
|
201
|
+
`)}function dg(i){const e=[];if(i===1)e.push("outColor = textureSampleGrad(textureSource1, textureSampler1, vUV, uvDx, uvDy);");else{e.push("switch vTextureId {");for(let t=0;t<i;t++)t===i-1?e.push(" default:{"):e.push(` case ${t}:{`),e.push(` outColor = textureSampleGrad(textureSource${t+1}, textureSampler${t+1}, vUV, uvDx, uvDy);`),e.push(" break;}");e.push("}")}return e.join(`
|
|
202
202
|
`)}function oc(i){return kn[i]||(kn[i]={name:"texture-batch-bit",vertex:{header:`
|
|
203
203
|
@in aTextureIdAndRound: vec2<u32>;
|
|
204
204
|
@out @interpolate(flat) vTextureId : u32;
|
|
@@ -212,13 +212,13 @@ ${r.join(`
|
|
|
212
212
|
`},fragment:{header:`
|
|
213
213
|
@in @interpolate(flat) vTextureId: u32;
|
|
214
214
|
|
|
215
|
-
${
|
|
215
|
+
${ug(i)}
|
|
216
216
|
`,main:`
|
|
217
217
|
var uvDx = dpdx(vUV);
|
|
218
218
|
var uvDy = dpdy(vUV);
|
|
219
219
|
|
|
220
|
-
${
|
|
221
|
-
`}}),kn[i]}const On={};function
|
|
220
|
+
${dg(i)}
|
|
221
|
+
`}}),kn[i]}const On={};function fg(i){const e=[];for(let t=0;t<i;t++)t>0&&e.push("else"),t<i-1&&e.push(`if(vTextureId < ${t}.5)`),e.push("{"),e.push(` outColor = texture(uTextures[${t}], vUV);`),e.push("}");return e.join(`
|
|
222
222
|
`)}function ac(i){return On[i]||(On[i]={name:"texture-batch-bit",vertex:{header:`
|
|
223
223
|
in vec2 aTextureIdAndRound;
|
|
224
224
|
out float vTextureId;
|
|
@@ -237,7 +237,7 @@ ${r.join(`
|
|
|
237
237
|
|
|
238
238
|
`,main:`
|
|
239
239
|
|
|
240
|
-
${
|
|
240
|
+
${fg(i)}
|
|
241
241
|
`}}),On[i]}const Bn={name:"round-pixels-bit",vertex:{header:`
|
|
242
242
|
fn roundPixels(position: vec2<f32>, targetSize: vec2<f32>) -> vec2<f32>
|
|
243
243
|
{
|
|
@@ -248,7 +248,7 @@ ${r.join(`
|
|
|
248
248
|
{
|
|
249
249
|
return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
|
|
250
250
|
}
|
|
251
|
-
`}},lc={};function cc(i){let e=lc[i];if(e)return e;const t=new Int32Array(i);for(let s=0;s<i;s++)t[s]=s;return e=lc[i]=new gt({uTextures:{value:t,type:"i32",size:i}},{isStatic:!0}),e}class hc extends wt{constructor(e){const t=Pn({name:"batch",bits:[nc,ac(e),Dn]}),s=Mn({name:"batch",bits:[rc,oc(e),Bn]});super({glProgram:t,gpuProgram:s,resources:{batchSamplers:cc(e)}}),this.maxTextures=e}}let ci=null;const uc=class mf extends zm{constructor(e){super(e),this.geometry=new qm,this.name=mf.extension.name,this.vertexSize=6,ci??(ci=new hc(e.maxTextures)),this.shader=ci}packAttributes(e,t,s,r,n){const o=n<<16|e.roundPixels&65535,a=e.transform,l=a.a,c=a.b,h=a.c,u=a.d,p=a.tx,d=a.ty,{positions:g,uvs:_}=e,b=e.color,v=e.attributeOffset,C=v+e.attributeSize;for(let E=v;E<C;E++){const S=E*2,w=g[S],R=g[S+1];t[r++]=l*w+h*R+p,t[r++]=u*R+c*w+d,t[r++]=_[S],t[r++]=_[S+1],s[r++]=b,s[r++]=o}}packQuadAttributes(e,t,s,r,n){const o=e.texture,a=e.transform,l=a.a,c=a.b,h=a.c,u=a.d,p=a.tx,d=a.ty,g=e.bounds,_=g.maxX,b=g.minX,v=g.maxY,C=g.minY,E=o.uvs,S=e.color,w=n<<16|e.roundPixels&65535;t[r+0]=l*b+h*C+p,t[r+1]=u*C+c*b+d,t[r+2]=E.x0,t[r+3]=E.y0,s[r+4]=S,s[r+5]=w,t[r+6]=l*_+h*C+p,t[r+7]=u*C+c*_+d,t[r+8]=E.x1,t[r+9]=E.y1,s[r+10]=S,s[r+11]=w,t[r+12]=l*_+h*v+p,t[r+13]=u*v+c*_+d,t[r+14]=E.x2,t[r+15]=E.y2,s[r+16]=S,s[r+17]=w,t[r+18]=l*b+h*v+p,t[r+19]=u*v+c*b+d,t[r+20]=E.x3,t[r+21]=E.y3,s[r+22]=S,s[r+23]=w}_updateMaxTextures(e){this.shader.maxTextures!==e&&(ci=new hc(e),this.shader=ci)}destroy(){this.shader=null,super.destroy()}};uc.extension={type:[A.Batcher],name:"default"};let Nn=uc;class Rt{constructor(e){this.items=Object.create(null);const{renderer:t,type:s,onUnload:r,priority:n,name:o}=e;this._renderer=t,t.gc.addResourceHash(this,"items",s,n??0),this._onUnload=r,this.name=o}add(e){return this.items[e.uid]?!1:(this.items[e.uid]=e,e.once("unload",this.remove,this),e._gcLastUsed=this._renderer.gc.now,!0)}remove(e,...t){var r;if(!this.items[e.uid])return;const s=e._gpuData[this._renderer.uid];s&&((r=this._onUnload)==null||r.call(this,e,...t),s.destroy(),e._gpuData[this._renderer.uid]=null,this.items[e.uid]=null)}removeAll(...e){Object.values(this.items).forEach(t=>t&&this.remove(t,...e))}destroy(...e){this.removeAll(...e),this.items=Object.create(null),this._renderer=null,this._onUnload=null}}function fg(i,e,t,s,r,n,o,a=null){let l=0;t*=e,r*=n;const c=a.a,h=a.b,u=a.c,p=a.d,d=a.tx,g=a.ty;for(;l<o;){const _=i[t],b=i[t+1];s[r]=c*_+u*b+d,s[r+1]=h*_+p*b+g,r+=n,t+=e,l++}}function pg(i,e,t,s){let r=0;for(e*=t;r<s;)i[e]=0,i[e+1]=0,e+=t,r++}function dc(i,e,t,s,r){const n=e.a,o=e.b,a=e.c,l=e.d,c=e.tx,h=e.ty;t||(t=0),s||(s=2),r||(r=i.length/s-t);let u=t*s;for(let p=0;p<r;p++){const d=i[u],g=i[u+1];i[u]=n*d+a*g+c,i[u+1]=o*d+l*g+h,u+=s}}const mg=new H;class Un{constructor(){this.packAsQuad=!1,this.batcherName="default",this.topology="triangle-list",this.applyTransform=!0,this.roundPixels=0,this._batcher=null,this._batch=null}get uvs(){return this.geometryData.uvs}get positions(){return this.geometryData.vertices}get indices(){return this.geometryData.indices}get blendMode(){return this.renderable&&this.applyTransform?this.renderable.groupBlendMode:"normal"}get color(){const e=this.baseColor,t=e>>16|e&65280|(e&255)<<16,s=this.renderable;return s?gs(t,s.groupColor)+(this.alpha*s.groupAlpha*255<<24):t+(this.alpha*255<<24)}get transform(){var e;return((e=this.renderable)==null?void 0:e.groupTransform)||mg}copyTo(e){e.indexOffset=this.indexOffset,e.indexSize=this.indexSize,e.attributeOffset=this.attributeOffset,e.attributeSize=this.attributeSize,e.baseColor=this.baseColor,e.alpha=this.alpha,e.texture=this.texture,e.geometryData=this.geometryData,e.topology=this.topology}reset(){this.applyTransform=!0,this.renderable=null,this.topology="triangle-list"}destroy(){this.renderable=null,this.texture=null,this.geometryData=null,this._batcher=null,this._batch=null}}const hi={extension:{type:A.ShapeBuilder,name:"circle"},build(i,e){let t,s,r,n,o,a;if(i.type==="circle"){const S=i;if(o=a=S.radius,o<=0)return!1;t=S.x,s=S.y,r=n=0}else if(i.type==="ellipse"){const S=i;if(o=S.halfWidth,a=S.halfHeight,o<=0||a<=0)return!1;t=S.x,s=S.y,r=n=0}else{const S=i,w=S.width/2,R=S.height/2;t=S.x+w,s=S.y+R,o=a=Math.max(0,Math.min(S.radius,Math.min(w,R))),r=w-o,n=R-a}if(r<0||n<0)return!1;const l=Math.ceil(2.3*Math.sqrt(o+a)),c=l*8+(r?4:0)+(n?4:0);if(c===0)return!1;if(l===0)return e[0]=e[6]=t+r,e[1]=e[3]=s+n,e[2]=e[4]=t-r,e[5]=e[7]=s-n,!0;let h=0,u=l*4+(r?2:0)+2,p=u,d=c,g=r+o,_=n,b=t+g,v=t-g,C=s+_;if(e[h++]=b,e[h++]=C,e[--u]=C,e[--u]=v,n){const S=s-_;e[p++]=v,e[p++]=S,e[--d]=S,e[--d]=b}for(let S=1;S<l;S++){const w=Math.PI/2*(S/l),R=r+Math.cos(w)*o,M=n+Math.sin(w)*a,D=t+R,G=t-R,k=s+M,O=s-M;e[h++]=D,e[h++]=k,e[--u]=k,e[--u]=G,e[p++]=G,e[p++]=O,e[--d]=O,e[--d]=D}g=r,_=n+a,b=t+g,v=t-g,C=s+_;const E=s-_;return e[h++]=b,e[h++]=C,e[--d]=E,e[--d]=b,r&&(e[h++]=v,e[h++]=C,e[--d]=E,e[--d]=v),!0},triangulate(i,e,t,s,r,n){if(i.length===0)return;let o=0,a=0;for(let h=0;h<i.length;h+=2)o+=i[h],a+=i[h+1];o/=i.length/2,a/=i.length/2;let l=s;e[l*t]=o,e[l*t+1]=a;const c=l++;for(let h=0;h<i.length;h+=2)e[l*t]=i[h],e[l*t+1]=i[h+1],h>0&&(r[n++]=l,r[n++]=c,r[n++]=l-1),l++;r[n++]=c+1,r[n++]=c,r[n++]=l-1}},gg={...hi,extension:{...hi.extension,name:"ellipse"}},_g={...hi,extension:{...hi.extension,name:"roundedRectangle"}},fc=1e-4,pc=1e-4;function yg(i){const e=i.length;if(e<6)return 1;let t=0;for(let s=0,r=i[e-2],n=i[e-1];s<e;s+=2){const o=i[s],a=i[s+1];t+=(o-r)*(a+n),r=o,n=a}return t<0?-1:1}function mc(i,e,t,s,r,n,o,a){const l=i-t*r,c=e-s*r,h=i+t*n,u=e+s*n;let p,d;o?(p=s,d=-t):(p=-s,d=t);const g=l+p,_=c+d,b=h+p,v=u+d;return a.push(g,_),a.push(b,v),2}function ns(i,e,t,s,r,n,o,a){const l=t-i,c=s-e;let h=Math.atan2(l,c),u=Math.atan2(r-i,n-e);a&&h<u?h+=Math.PI*2:!a&&h>u&&(u+=Math.PI*2);let p=h;const d=u-h,g=Math.abs(d),_=Math.sqrt(l*l+c*c),b=(15*g*Math.sqrt(_)/Math.PI>>0)+1,v=d/b;if(p+=v,a){o.push(i,e),o.push(t,s);for(let C=1,E=p;C<b;C++,E+=v)o.push(i,e),o.push(i+Math.sin(E)*_,e+Math.cos(E)*_);o.push(i,e),o.push(r,n)}else{o.push(t,s),o.push(i,e);for(let C=1,E=p;C<b;C++,E+=v)o.push(i+Math.sin(E)*_,e+Math.cos(E)*_),o.push(i,e);o.push(r,n),o.push(i,e)}return b*2}function gc(i,e,t,s,r,n){const o=fc;if(i.length===0)return;const a=e;let l=a.alignment;if(e.alignment!==.5){let N=yg(i);l=(l-.5)*N+.5}const c=new ye(i[0],i[1]),h=new ye(i[i.length-2],i[i.length-1]),u=s,p=Math.abs(c.x-h.x)<o&&Math.abs(c.y-h.y)<o;if(u){i=i.slice(),p&&(i.pop(),i.pop(),h.set(i[i.length-2],i[i.length-1]));const N=(c.x+h.x)*.5,K=(h.y+c.y)*.5;i.unshift(N,K),i.push(N,K)}const d=r,g=i.length/2;let _=i.length;const b=d.length/2,v=a.width/2,C=v*v,E=a.miterLimit*a.miterLimit;let S=i[0],w=i[1],R=i[2],M=i[3],D=0,G=0,k=-(w-M),O=S-R,V=0,X=0,z=Math.sqrt(k*k+O*O);k/=z,O/=z,k*=v,O*=v;const de=l,B=(1-de)*2,U=de*2;u||(a.cap==="round"?_+=ns(S-k*(B-U)*.5,w-O*(B-U)*.5,S-k*B,w-O*B,S+k*U,w+O*U,d,!0)+2:a.cap==="square"&&(_+=mc(S,w,k,O,B,U,!0,d))),d.push(S-k*B,w-O*B),d.push(S+k*U,w+O*U);for(let N=1;N<g-1;++N){S=i[(N-1)*2],w=i[(N-1)*2+1],R=i[N*2],M=i[N*2+1],D=i[(N+1)*2],G=i[(N+1)*2+1],k=-(w-M),O=S-R,z=Math.sqrt(k*k+O*O),k/=z,O/=z,k*=v,O*=v,V=-(M-G),X=R-D,z=Math.sqrt(V*V+X*X),V/=z,X/=z,V*=v,X*=v;const K=R-S,Z=w-M,$=R-D,ae=G-M,xe=K*$+Z*ae,Se=Z*$-ae*K,F=Se<0;if(Math.abs(Se)<.001*Math.abs(xe)){d.push(R-k*B,M-O*B),d.push(R+k*U,M+O*U),xe>=0&&(a.join==="round"?_+=ns(R,M,R-k*B,M-O*B,R-V*B,M-X*B,d,!1)+4:_+=2,d.push(R-V*U,M-X*U),d.push(R+V*B,M+X*B));continue}const fe=(-k+S)*(-O+M)-(-k+R)*(-O+w),le=(-V+D)*(-X+M)-(-V+R)*(-X+G),L=(K*le-$*fe)/Se,me=(ae*fe-Z*le)/Se,Y=(L-R)*(L-R)+(me-M)*(me-M),se=R+(L-R)*B,we=M+(me-M)*B,ce=R-(L-R)*U,He=M-(me-M)*U,Zt=Math.min(K*K+Z*Z,$*$+ae*ae),Ct=F?B:U,hs=Zt+Ct*Ct*C;Y<=hs?a.join==="bevel"||Y/C>E?(F?(d.push(se,we),d.push(R+k*U,M+O*U),d.push(se,we),d.push(R+V*U,M+X*U)):(d.push(R-k*B,M-O*B),d.push(ce,He),d.push(R-V*B,M-X*B),d.push(ce,He)),_+=2):a.join==="round"?F?(d.push(se,we),d.push(R+k*U,M+O*U),_+=ns(R,M,R+k*U,M+O*U,R+V*U,M+X*U,d,!0)+4,d.push(se,we),d.push(R+V*U,M+X*U)):(d.push(R-k*B,M-O*B),d.push(ce,He),_+=ns(R,M,R-k*B,M-O*B,R-V*B,M-X*B,d,!1)+4,d.push(R-V*B,M-X*B),d.push(ce,He)):(d.push(se,we),d.push(ce,He)):(d.push(R-k*B,M-O*B),d.push(R+k*U,M+O*U),a.join==="round"?F?_+=ns(R,M,R+k*U,M+O*U,R+V*U,M+X*U,d,!0)+2:_+=ns(R,M,R-k*B,M-O*B,R-V*B,M-X*B,d,!1)+2:a.join==="miter"&&Y/C<=E&&(F?(d.push(ce,He),d.push(ce,He)):(d.push(se,we),d.push(se,we)),_+=2),d.push(R-V*B,M-X*B),d.push(R+V*U,M+X*U),_+=2)}S=i[(g-2)*2],w=i[(g-2)*2+1],R=i[(g-1)*2],M=i[(g-1)*2+1],k=-(w-M),O=S-R,z=Math.sqrt(k*k+O*O),k/=z,O/=z,k*=v,O*=v,d.push(R-k*B,M-O*B),d.push(R+k*U,M+O*U),u||(a.cap==="round"?_+=ns(R-k*(B-U)*.5,M-O*(B-U)*.5,R-k*B,M-O*B,R+k*U,M+O*U,d,!1)+2:a.cap==="square"&&(_+=mc(R,M,k,O,B,U,!1,d)));const q=pc*pc;for(let N=b;N<_+b-2;++N)S=d[N*2],w=d[N*2+1],R=d[(N+1)*2],M=d[(N+1)*2+1],D=d[(N+2)*2],G=d[(N+2)*2+1],!(Math.abs(S*(M-G)+R*(G-w)+D*(w-M))<q)&&n.push(N,N+1,N+2)}function bg(i,e,t,s){const r=fc;if(i.length===0)return;const n=i[0],o=i[1],a=i[i.length-2],l=i[i.length-1],c=e||Math.abs(n-a)<r&&Math.abs(o-l)<r,h=t,u=i.length/2,p=h.length/2;for(let d=0;d<u;d++)h.push(i[d*2]),h.push(i[d*2+1]);for(let d=0;d<u-1;d++)s.push(p+d,p+d+1);c&&s.push(p+u-1,p)}function _c(i,e,t,s,r,n,o){const a=Tm(i,e,2);if(!a)return;for(let c=0;c<a.length;c+=3)n[o++]=a[c]+r,n[o++]=a[c+1]+r,n[o++]=a[c+2]+r;let l=r*s;for(let c=0;c<i.length;c+=2)t[l]=i[c],t[l+1]=i[c+1],l+=s}const vg=[],xg={extension:{type:A.ShapeBuilder,name:"polygon"},build(i,e){for(let t=0;t<i.points.length;t++)e[t]=i.points[t];return!0},triangulate(i,e,t,s,r,n){_c(i,vg,e,t,s,r,n)}},Cg={extension:{type:A.ShapeBuilder,name:"rectangle"},build(i,e){const t=i,s=t.x,r=t.y,n=t.width,o=t.height;return n>0&&o>0?(e[0]=s,e[1]=r,e[2]=s+n,e[3]=r,e[4]=s+n,e[5]=r+o,e[6]=s,e[7]=r+o,!0):!1},triangulate(i,e,t,s,r,n){let o=0;s*=t,e[s+o]=i[0],e[s+o+1]=i[1],o+=t,e[s+o]=i[2],e[s+o+1]=i[3],o+=t,e[s+o]=i[6],e[s+o+1]=i[7],o+=t,e[s+o]=i[4],e[s+o+1]=i[5],o+=t;const a=s/t;r[n++]=a,r[n++]=a+1,r[n++]=a+2,r[n++]=a+1,r[n++]=a+3,r[n++]=a+2}},Eg={extension:{type:A.ShapeBuilder,name:"triangle"},build(i,e){return e[0]=i.x,e[1]=i.y,e[2]=i.x2,e[3]=i.y2,e[4]=i.x3,e[5]=i.y3,!0},triangulate(i,e,t,s,r,n){let o=0;s*=t,e[s+o]=i[0],e[s+o+1]=i[1],o+=t,e[s+o]=i[2],e[s+o+1]=i[3],o+=t,e[s+o]=i[4],e[s+o+1]=i[5];const a=s/t;r[n++]=a,r[n++]=a+1,r[n++]=a+2}},yc=[{offset:0,color:"white"},{offset:1,color:"black"}],Gn=class ta{constructor(...e){this.uid=be("fillGradient"),this._tick=0,this.type="linear",this.colorStops=[];let t=Sg(e);t={...t.type==="radial"?ta.defaultRadialOptions:ta.defaultLinearOptions,...da(t)},this._textureSize=t.textureSize,this._wrapMode=t.wrapMode,t.type==="radial"?(this.center=t.center,this.outerCenter=t.outerCenter??this.center,this.innerRadius=t.innerRadius,this.outerRadius=t.outerRadius,this.scale=t.scale,this.rotation=t.rotation):(this.start=t.start,this.end=t.end),this.textureSpace=t.textureSpace,this.type=t.type,t.colorStops.forEach(r=>{this.addColorStop(r.offset,r.color)})}addColorStop(e,t){return this.colorStops.push({offset:e,color:Pe.shared.setValue(t).toHexa()}),this}buildLinearGradient(){if(this.texture)return;let{x:e,y:t}=this.start,{x:s,y:r}=this.end,n=s-e,o=r-t;const a=n<0||o<0;if(this._wrapMode==="clamp-to-edge"){if(n<0){const b=e;e=s,s=b,n*=-1}if(o<0){const b=t;t=r,r=b,o*=-1}}const l=this.colorStops.length?this.colorStops:yc,c=this._textureSize,{canvas:h,context:u}=vc(c,1),p=a?u.createLinearGradient(this._textureSize,0,0,0):u.createLinearGradient(0,0,this._textureSize,0);bc(p,l),u.fillStyle=p,u.fillRect(0,0,c,1),this.texture=new j({source:new $i({resource:h,addressMode:this._wrapMode})});const d=Math.sqrt(n*n+o*o),g=Math.atan2(o,n),_=new H;_.scale(d/c,1),_.rotate(g),_.translate(e,t),this.textureSpace==="local"&&_.scale(c,c),this.transform=_}buildGradient(){this.texture||this._tick++,this.type==="linear"?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){if(this.texture)return;const e=this.colorStops.length?this.colorStops:yc,t=this._textureSize,{canvas:s,context:r}=vc(t,t),{x:n,y:o}=this.center,{x:a,y:l}=this.outerCenter,c=this.innerRadius,h=this.outerRadius,u=a-h,p=l-h,d=t/(h*2),g=(n-u)*d,_=(o-p)*d,b=r.createRadialGradient(g,_,c*d,(a-u)*d,(l-p)*d,h*d);bc(b,e),r.fillStyle=e[e.length-1].color,r.fillRect(0,0,t,t),r.fillStyle=b,r.translate(g,_),r.rotate(this.rotation),r.scale(1,this.scale),r.translate(-g,-_),r.fillRect(0,0,t,t),this.texture=new j({source:new $i({resource:s,addressMode:this._wrapMode})});const v=new H;v.scale(1/d,1/d),v.translate(u,p),this.textureSpace==="local"&&v.scale(t,t),this.transform=v}destroy(){var e;(e=this.texture)==null||e.destroy(!0),this.texture=null,this.transform=null,this.colorStops=[],this.start=null,this.end=null,this.center=null,this.outerCenter=null}get styleKey(){return`fill-gradient-${this.uid}-${this._tick}`}};Gn.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:"local",type:"linear",textureSize:256,wrapMode:"clamp-to-edge"},Gn.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,textureSpace:"local",type:"radial",textureSize:256,wrapMode:"clamp-to-edge"};let As=Gn;function bc(i,e){for(let t=0;t<e.length;t++){const s=e[t];i.addColorStop(s.offset,s.color)}}function vc(i,e){const t=pe.get().createCanvas(i,e),s=t.getContext("2d");return{canvas:t,context:s}}function Sg(i){let e=i[0]??{};return(typeof e=="number"||i[1])&&(ee("8.5.2","use options object instead"),e={type:"linear",start:{x:i[0],y:i[1]},end:{x:i[2],y:i[3]},textureSpace:i[4],textureSize:i[5]??As.defaultLinearOptions.textureSize}),e}const Tg=new H,Ag=new Ce;function xc(i,e,t,s){const r=e.matrix?i.copyFrom(e.matrix).invert():i.identity();if(e.textureSpace==="local"){const o=t.getBounds(Ag);e.width&&o.pad(e.width);const{x:a,y:l}=o,c=1/o.width,h=1/o.height,u=-a*c,p=-l*h,d=r.a,g=r.b,_=r.c,b=r.d;r.a*=c,r.b*=c,r.c*=h,r.d*=h,r.tx=u*d+p*_+r.tx,r.ty=u*g+p*b+r.ty}else r.translate(e.texture.frame.x,e.texture.frame.y),r.scale(1/e.texture.source.width,1/e.texture.source.height);const n=e.texture.source.style;return!(e.fill instanceof As)&&n.addressMode==="clamp-to-edge"&&(n.addressMode="repeat",n.update()),s&&r.append(Tg.copyFrom(s).invert()),r}const ui={};Q.handleByMap(A.ShapeBuilder,ui),Q.add(Cg,xg,Eg,hi,gg,_g);const wg=new Ce,Ig=new H;function Rg(i,e){const{geometryData:t,batches:s}=e;s.length=0,t.indices.length=0,t.vertices.length=0,t.uvs.length=0;for(let r=0;r<i.instructions.length;r++){const n=i.instructions[r];if(n.action==="texture")Mg(n.data,s,t);else if(n.action==="fill"||n.action==="stroke"){const o=n.action==="stroke",a=n.data.path.shapePath,l=n.data.style,c=n.data.hole;o&&c&&Cc(c.shapePath,l,!0,s,t),c&&(a.shapePrimitives[a.shapePrimitives.length-1].holes=c.shapePath.shapePrimitives),Cc(a,l,o,s,t)}}}function Mg(i,e,t){const s=[],r=ui.rectangle,n=wg;n.x=i.dx,n.y=i.dy,n.width=i.dw,n.height=i.dh;const o=i.transform;if(!r.build(n,s))return;const{vertices:a,uvs:l,indices:c}=t,h=c.length,u=a.length/2;o&&dc(s,o),r.triangulate(s,a,2,u,c,h);const p=i.image,d=p.uvs;l.push(d.x0,d.y0,d.x1,d.y1,d.x3,d.y3,d.x2,d.y2);const g=Le.get(Un);g.indexOffset=h,g.indexSize=c.length-h,g.attributeOffset=u,g.attributeSize=a.length/2-u,g.baseColor=i.style,g.alpha=i.alpha,g.texture=p,g.geometryData=t,e.push(g)}function Cc(i,e,t,s,r){const{vertices:n,uvs:o,indices:a}=r;i.shapePrimitives.forEach(({shape:l,transform:c,holes:h})=>{const u=[],p=ui[l.type];if(!p.build(l,u))return;const d=a.length,g=n.length/2;let _="triangle-list";if(c&&dc(u,c),t){const E=l.closePath??!0,S=e;S.pixelLine?(bg(u,E,n,a),_="line-list"):gc(u,S,!1,E,n,a)}else if(h){const E=[],S=u.slice();Pg(h).forEach(R=>{E.push(S.length/2),S.push(...R)}),_c(S,E,n,2,g,a,d)}else p.triangulate(u,n,2,g,a,d);const b=o.length/2,v=e.texture;if(v!==j.WHITE){const E=xc(Ig,e,l,c);fg(n,2,g,o,b,2,n.length/2-g,E)}else pg(o,b,2,n.length/2-g);const C=Le.get(Un);C.indexOffset=d,C.indexSize=a.length-d,C.attributeOffset=g,C.attributeSize=n.length/2-g,C.baseColor=e.color,C.alpha=e.alpha,C.texture=v,C.geometryData=r,C.topology=_,s.push(C)})}function Pg(i){const e=[];for(let t=0;t<i.length;t++){const s=i[t].shape,r=[];ui[s.type].build(s,r)&&e.push(r)}return e}class kg{constructor(){this.batches=[],this.geometryData={vertices:[],uvs:[],indices:[]}}reset(){this.batches&&this.batches.forEach(e=>{Le.return(e)}),this.graphicsData&&Le.return(this.graphicsData),this.isBatchable=!1,this.context=null,this.batches.length=0,this.geometryData.indices.length=0,this.geometryData.vertices.length=0,this.geometryData.uvs.length=0,this.graphicsData=null}destroy(){this.reset(),this.batches=null,this.geometryData=null}}class Og{constructor(){this.instructions=new Zr}init(e){const t=e.maxTextures;this.batcher?this.batcher._updateMaxTextures(t):this.batcher=new Nn({maxTextures:t}),this.instructions.reset()}get geometry(){return ee(Vf,"GraphicsContextRenderData#geometry is deprecated, please use batcher.geometry instead."),this.batcher.geometry}destroy(){this.batcher.destroy(),this.instructions.destroy(),this.batcher=null,this.instructions=null}}const Fn=class sa{constructor(e){this._renderer=e,this._managedContexts=new Rt({renderer:e,type:"resource",name:"graphicsContext"})}init(e){sa.defaultOptions.bezierSmoothness=(e==null?void 0:e.bezierSmoothness)??sa.defaultOptions.bezierSmoothness}getContextRenderData(e){return e._gpuData[this._renderer.uid].graphicsData||this._initContextRenderData(e)}updateGpuContext(e){const t=!!e._gpuData[this._renderer.uid],s=e._gpuData[this._renderer.uid]||this._initContext(e);if(e.dirty||!t){t&&s.reset(),Rg(e,s);const r=e.batchMode;e.customShader||r==="no-batch"?s.isBatchable=!1:r==="auto"?s.isBatchable=s.geometryData.vertices.length<400:s.isBatchable=!0,e.dirty=!1}return s}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){const t=Le.get(Og,{maxTextures:this._renderer.limits.maxBatchableTextures}),s=e._gpuData[this._renderer.uid],{batches:r,geometryData:n}=s;s.graphicsData=t;const o=n.vertices.length,a=n.indices.length;for(let u=0;u<r.length;u++)r[u].applyTransform=!1;const l=t.batcher;l.ensureAttributeBuffer(o),l.ensureIndexBuffer(a),l.begin();for(let u=0;u<r.length;u++){const p=r[u];l.add(p)}l.finish(t.instructions);const c=l.geometry;c.indexBuffer.setDataWithSize(l.indexBuffer,l.indexSize,!0),c.buffers[0].setDataWithSize(l.attributeBuffer.float32View,l.attributeSize,!0);const h=l.batches;for(let u=0;u<h.length;u++){const p=h[u];p.bindGroup=An(p.textures.textures,p.textures.count,this._renderer.limits.maxBatchableTextures)}return t}_initContext(e){const t=new kg;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}};Fn.extension={type:[A.WebGLSystem,A.WebGPUSystem],name:"graphicsContext"},Fn.defaultOptions={bezierSmoothness:.5};let Ln=Fn;const Bg=8,sr=11920929e-14,Dg=1;function Ec(i,e,t,s,r,n,o,a,l,c){const u=Math.min(.99,Math.max(0,c??Ln.defaultOptions.bezierSmoothness));let p=(Dg-u)/1;return p*=p,Ng(e,t,s,r,n,o,a,l,i,p),i}function Ng(i,e,t,s,r,n,o,a,l,c){Wn(i,e,t,s,r,n,o,a,l,c,0),l.push(o,a)}function Wn(i,e,t,s,r,n,o,a,l,c,h){if(h>Bg)return;const u=(i+t)/2,p=(e+s)/2,d=(t+r)/2,g=(s+n)/2,_=(r+o)/2,b=(n+a)/2,v=(u+d)/2,C=(p+g)/2,E=(d+_)/2,S=(g+b)/2,w=(v+E)/2,R=(C+S)/2;if(h>0){let M=o-i,D=a-e;const G=Math.abs((t-o)*D-(s-a)*M),k=Math.abs((r-o)*D-(n-a)*M);if(G>sr&&k>sr){if((G+k)*(G+k)<=c*(M*M+D*D)){l.push(w,R);return}}else if(G>sr){if(G*G<=c*(M*M+D*D)){l.push(w,R);return}}else if(k>sr){if(k*k<=c*(M*M+D*D)){l.push(w,R);return}}else if(M=w-(i+o)/2,D=R-(e+a)/2,M*M+D*D<=c){l.push(w,R);return}}Wn(i,e,u,p,v,C,w,R,l,c,h+1),Wn(w,R,E,S,_,b,o,a,l,c,h+1)}const Ug=8,Gg=11920929e-14,Fg=1;function Lg(i,e,t,s,r,n,o,a){const c=Math.min(.99,Math.max(0,a??Ln.defaultOptions.bezierSmoothness));let h=(Fg-c)/1;return h*=h,Wg(e,t,s,r,n,o,i,h),i}function Wg(i,e,t,s,r,n,o,a){Hn(o,i,e,t,s,r,n,a,0),o.push(r,n)}function Hn(i,e,t,s,r,n,o,a,l){if(l>Ug)return;const c=(e+s)/2,h=(t+r)/2,u=(s+n)/2,p=(r+o)/2,d=(c+u)/2,g=(h+p)/2;let _=n-e,b=o-t;const v=Math.abs((s-n)*b-(r-o)*_);if(v>Gg){if(v*v<=a*(_*_+b*b)){i.push(d,g);return}}else if(_=d-(e+n)/2,b=g-(t+o)/2,_*_+b*b<=a){i.push(d,g);return}Hn(i,e,t,c,h,d,g,a,l+1),Hn(i,d,g,u,p,n,o,a,l+1)}function Sc(i,e,t,s,r,n,o,a){let l=Math.abs(r-n);(!o&&r>n||o&&n>r)&&(l=2*Math.PI-l),a||(a=Math.max(6,Math.floor(6*Math.pow(s,1/3)*(l/Math.PI)))),a=Math.max(a,3);let c=l/a,h=r;c*=o?-1:1;for(let u=0;u<a+1;u++){const p=Math.cos(h),d=Math.sin(h),g=e+p*s,_=t+d*s;i.push(g,_),h+=c}}function Hg(i,e,t,s,r,n){const o=i[i.length-2],l=i[i.length-1]-t,c=o-e,h=r-t,u=s-e,p=Math.abs(l*u-c*h);if(p<1e-8||n===0){(i[i.length-2]!==e||i[i.length-1]!==t)&&i.push(e,t);return}const d=l*l+c*c,g=h*h+u*u,_=l*h+c*u,b=n*Math.sqrt(d)/p,v=n*Math.sqrt(g)/p,C=b*_/d,E=v*_/g,S=b*u+v*c,w=b*h+v*l,R=c*(v+C),M=l*(v+C),D=u*(b+E),G=h*(b+E),k=Math.atan2(M-w,R-S),O=Math.atan2(G-w,D-S);Sc(i,S+e,w+t,n,k,O,c*h>u*l)}const di=Math.PI*2,Vn={centerX:0,centerY:0,ang1:0,ang2:0},zn=({x:i,y:e},t,s,r,n,o,a,l)=>{i*=t,e*=s;const c=r*i-n*e,h=n*i+r*e;return l.x=c+o,l.y=h+a,l};function Vg(i,e){const t=e===-1.5707963267948966?-.551915024494:1.3333333333333333*Math.tan(e/4),s=e===1.5707963267948966?.551915024494:t,r=Math.cos(i),n=Math.sin(i),o=Math.cos(i+e),a=Math.sin(i+e);return[{x:r-n*s,y:n+r*s},{x:o+a*s,y:a-o*s},{x:o,y:a}]}const Tc=(i,e,t,s)=>{const r=i*s-e*t<0?-1:1;let n=i*t+e*s;return n>1&&(n=1),n<-1&&(n=-1),r*Math.acos(n)},zg=(i,e,t,s,r,n,o,a,l,c,h,u,p)=>{const d=Math.pow(r,2),g=Math.pow(n,2),_=Math.pow(h,2),b=Math.pow(u,2);let v=d*g-d*b-g*_;v<0&&(v=0),v/=d*b+g*_,v=Math.sqrt(v)*(o===a?-1:1);const C=v*r/n*u,E=v*-n/r*h,S=c*C-l*E+(i+t)/2,w=l*C+c*E+(e+s)/2,R=(h-C)/r,M=(u-E)/n,D=(-h-C)/r,G=(-u-E)/n,k=Tc(1,0,R,M);let O=Tc(R,M,D,G);a===0&&O>0&&(O-=di),a===1&&O<0&&(O+=di),p.centerX=S,p.centerY=w,p.ang1=k,p.ang2=O};function $g(i,e,t,s,r,n,o,a=0,l=0,c=0){if(n===0||o===0)return;const h=Math.sin(a*di/360),u=Math.cos(a*di/360),p=u*(e-s)/2+h*(t-r)/2,d=-h*(e-s)/2+u*(t-r)/2;if(p===0&&d===0)return;n=Math.abs(n),o=Math.abs(o);const g=Math.pow(p,2)/Math.pow(n,2)+Math.pow(d,2)/Math.pow(o,2);g>1&&(n*=Math.sqrt(g),o*=Math.sqrt(g)),zg(e,t,s,r,n,o,l,c,h,u,p,d,Vn);let{ang1:_,ang2:b}=Vn;const{centerX:v,centerY:C}=Vn;let E=Math.abs(b)/(di/4);Math.abs(1-E)<1e-7&&(E=1);const S=Math.max(Math.ceil(E),1);b/=S;let w=i[i.length-2],R=i[i.length-1];const M={x:0,y:0};for(let D=0;D<S;D++){const G=Vg(_,b),{x:k,y:O}=zn(G[0],n,o,u,h,v,C,M),{x:V,y:X}=zn(G[1],n,o,u,h,v,C,M),{x:z,y:de}=zn(G[2],n,o,u,h,v,C,M);Ec(i,w,R,k,O,V,X,z,de),w=z,R=de,_+=b}}function jg(i,e,t){const s=(o,a)=>{const l=a.x-o.x,c=a.y-o.y,h=Math.sqrt(l*l+c*c),u=l/h,p=c/h;return{len:h,nx:u,ny:p}},r=(o,a)=>{o===0?i.moveTo(a.x,a.y):i.lineTo(a.x,a.y)};let n=e[e.length-1];for(let o=0;o<e.length;o++){const a=e[o%e.length],l=a.radius??t;if(l<=0){r(o,a),n=a;continue}const c=e[(o+1)%e.length],h=s(a,n),u=s(a,c);if(h.len<1e-4||u.len<1e-4){r(o,a),n=a;continue}let p=Math.asin(h.nx*u.ny-h.ny*u.nx),d=1,g=!1;h.nx*u.nx-h.ny*-u.ny<0?p<0?p=Math.PI+p:(p=Math.PI-p,d=-1,g=!0):p>0&&(d=-1,g=!0);const _=p/2;let b,v=Math.abs(Math.cos(_)*l/Math.sin(_));v>Math.min(h.len/2,u.len/2)?(v=Math.min(h.len/2,u.len/2),b=Math.abs(v*Math.sin(_)/Math.cos(_))):b=l;const C=a.x+u.nx*v+-u.ny*b*d,E=a.y+u.ny*v+u.nx*b*d,S=Math.atan2(h.ny,h.nx)+Math.PI/2*d,w=Math.atan2(u.ny,u.nx)-Math.PI/2*d;o===0&&i.moveTo(C+Math.cos(S)*b,E+Math.sin(S)*b),i.arc(C,E,b,S,w,g),n=a}}function Xg(i,e,t,s){const r=(a,l)=>Math.sqrt((a.x-l.x)**2+(a.y-l.y)**2),n=(a,l,c)=>({x:a.x+(l.x-a.x)*c,y:a.y+(l.y-a.y)*c}),o=e.length;for(let a=0;a<o;a++){const l=e[(a+1)%o],c=l.radius??t;if(c<=0){a===0?i.moveTo(l.x,l.y):i.lineTo(l.x,l.y);continue}const h=e[a],u=e[(a+2)%o],p=r(h,l);let d;if(p<1e-4)d=l;else{const b=Math.min(p/2,c);d=n(l,h,b/p)}const g=r(u,l);let _;if(g<1e-4)_=l;else{const b=Math.min(g/2,c);_=n(l,u,b/g)}a===0?i.moveTo(d.x,d.y):i.lineTo(d.x,d.y),i.quadraticCurveTo(l.x,l.y,_.x,_.y,s)}}const Yg=new Ce;class qg{constructor(e){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new Ye,this._graphicsPath2D=e,this.signed=e.checkForHoles}moveTo(e,t){return this.startPoly(e,t),this}lineTo(e,t){this._ensurePoly();const s=this._currentPoly.points,r=s[s.length-2],n=s[s.length-1];return(r!==e||n!==t)&&s.push(e,t),this}arc(e,t,s,r,n,o){this._ensurePoly(!1);const a=this._currentPoly.points;return Sc(a,e,t,s,r,n,o),this}arcTo(e,t,s,r,n){this._ensurePoly();const o=this._currentPoly.points;return Hg(o,e,t,s,r,n),this}arcToSvg(e,t,s,r,n,o,a){const l=this._currentPoly.points;return $g(l,this._currentPoly.lastX,this._currentPoly.lastY,o,a,e,t,s,r,n),this}bezierCurveTo(e,t,s,r,n,o,a){this._ensurePoly();const l=this._currentPoly;return Ec(this._currentPoly.points,l.lastX,l.lastY,e,t,s,r,n,o,a),this}quadraticCurveTo(e,t,s,r,n){this._ensurePoly();const o=this._currentPoly;return Lg(this._currentPoly.points,o.lastX,o.lastY,e,t,s,r,n),this}closePath(){return this.endPoly(!0),this}addPath(e,t){this.endPoly(),t&&!t.isIdentity()&&(e=e.clone(!0),e.transform(t));const s=this.shapePrimitives,r=s.length;for(let n=0;n<e.instructions.length;n++){const o=e.instructions[n];this[o.action](...o.data)}if(e.checkForHoles&&s.length-r>1){let n=null;for(let o=r;o<s.length;o++){const a=s[o];if(a.shape.type==="polygon"){const l=a.shape,c=n==null?void 0:n.shape;c&&c.containsPolygon(l)?(n.holes||(n.holes=[]),n.holes.push(a),s.copyWithin(o,o+1),s.length--,o--):n=a}}}return this}finish(e=!1){this.endPoly(e)}rect(e,t,s,r,n){return this.drawShape(new Ce(e,t,s,r),n),this}circle(e,t,s,r){return this.drawShape(new En(e,t,s),r),this}poly(e,t,s){const r=new oi(e);return r.closePath=t,this.drawShape(r,s),this}regularPoly(e,t,s,r,n=0,o){r=Math.max(r|0,3);const a=-1*Math.PI/2+n,l=Math.PI*2/r,c=[];for(let h=0;h<r;h++){const u=a-h*l;c.push(e+s*Math.cos(u),t+s*Math.sin(u))}return this.poly(c,!0,o),this}roundPoly(e,t,s,r,n,o=0,a){if(r=Math.max(r|0,3),n<=0)return this.regularPoly(e,t,s,r,o);const l=s*Math.sin(Math.PI/r)-.001;n=Math.min(n,l);const c=-1*Math.PI/2+o,h=Math.PI*2/r,u=(r-2)*Math.PI/r/2;for(let p=0;p<r;p++){const d=p*h+c,g=e+s*Math.cos(d),_=t+s*Math.sin(d),b=d+Math.PI+u,v=d-Math.PI-u,C=g+n*Math.cos(b),E=_+n*Math.sin(b),S=g+n*Math.cos(v),w=_+n*Math.sin(v);p===0?this.moveTo(C,E):this.lineTo(C,E),this.quadraticCurveTo(g,_,S,w,a)}return this.closePath()}roundShape(e,t,s=!1,r){return e.length<3?this:(s?Xg(this,e,t,r):jg(this,e,t),this.closePath())}filletRect(e,t,s,r,n){if(n===0)return this.rect(e,t,s,r);const o=Math.min(s,r)/2,a=Math.min(o,Math.max(-o,n)),l=e+s,c=t+r,h=a<0?-a:0,u=Math.abs(a);return this.moveTo(e,t+u).arcTo(e+h,t+h,e+u,t,u).lineTo(l-u,t).arcTo(l-h,t+h,l,t+u,u).lineTo(l,c-u).arcTo(l-h,c-h,e+s-u,c,u).lineTo(e+u,c).arcTo(e+h,c-h,e,c-u,u).closePath()}chamferRect(e,t,s,r,n,o){if(n<=0)return this.rect(e,t,s,r);const a=Math.min(n,Math.min(s,r)/2),l=e+s,c=t+r,h=[e+a,t,l-a,t,l,t+a,l,c-a,l-a,c,e+a,c,e,c-a,e,t+a];for(let u=h.length-1;u>=2;u-=2)h[u]===h[u-2]&&h[u-1]===h[u-3]&&h.splice(u-1,2);return this.poly(h,!0,o)}ellipse(e,t,s,r,n){return this.drawShape(new Sn(e,t,s,r),n),this}roundRect(e,t,s,r,n,o){return this.drawShape(new Tn(e,t,s,r,n),o),this}drawShape(e,t){return this.endPoly(),this.shapePrimitives.push({shape:e,transform:t}),this}startPoly(e,t){let s=this._currentPoly;return s&&this.endPoly(),s=new oi,s.points.push(e,t),this._currentPoly=s,this}endPoly(e=!1){const t=this._currentPoly;return t&&t.points.length>2&&(t.closePath=e,this.shapePrimitives.push({shape:t})),this._currentPoly=null,this}_ensurePoly(e=!0){if(!this._currentPoly&&(this._currentPoly=new oi,e)){const t=this.shapePrimitives[this.shapePrimitives.length-1];if(t){let s=t.shape.x,r=t.shape.y;if(t.transform&&!t.transform.isIdentity()){const n=t.transform,o=s;s=n.a*s+n.c*r+n.tx,r=n.b*o+n.d*r+n.ty}this._currentPoly.points.push(s,r)}else this._currentPoly.points.push(0,0)}}buildPath(){const e=this._graphicsPath2D;this.shapePrimitives.length=0,this._currentPoly=null;for(let t=0;t<e.instructions.length;t++){const s=e.instructions[t];this[s.action](...s.data)}this.finish()}get bounds(){const e=this._bounds;e.clear();const t=this.shapePrimitives;for(let s=0;s<t.length;s++){const r=t[s],n=r.shape.getBounds(Yg);r.transform?e.addRect(n,r.transform):e.addRect(n)}return e}}class Mt{constructor(e,t=!1){this.instructions=[],this.uid=be("graphicsPath"),this._dirty=!0,this.checkForHoles=t,typeof e=="string"?Om(e,this):this.instructions=(e==null?void 0:e.slice())??[]}get shapePath(){return this._shapePath||(this._shapePath=new qg(this)),this._dirty&&(this._dirty=!1,this._shapePath.buildPath()),this._shapePath}addPath(e,t){return e=e.clone(),this.instructions.push({action:"addPath",data:[e,t]}),this._dirty=!0,this}arc(...e){return this.instructions.push({action:"arc",data:e}),this._dirty=!0,this}arcTo(...e){return this.instructions.push({action:"arcTo",data:e}),this._dirty=!0,this}arcToSvg(...e){return this.instructions.push({action:"arcToSvg",data:e}),this._dirty=!0,this}bezierCurveTo(...e){return this.instructions.push({action:"bezierCurveTo",data:e}),this._dirty=!0,this}bezierCurveToShort(e,t,s,r,n){const o=this.instructions[this.instructions.length-1],a=this.getLastPoint(ye.shared);let l=0,c=0;if(!o||o.action!=="bezierCurveTo")l=a.x,c=a.y;else{l=o.data[2],c=o.data[3];const h=a.x,u=a.y;l=h+(h-l),c=u+(u-c)}return this.instructions.push({action:"bezierCurveTo",data:[l,c,e,t,s,r,n]}),this._dirty=!0,this}closePath(){return this.instructions.push({action:"closePath",data:[]}),this._dirty=!0,this}ellipse(...e){return this.instructions.push({action:"ellipse",data:e}),this._dirty=!0,this}lineTo(...e){return this.instructions.push({action:"lineTo",data:e}),this._dirty=!0,this}moveTo(...e){return this.instructions.push({action:"moveTo",data:e}),this}quadraticCurveTo(...e){return this.instructions.push({action:"quadraticCurveTo",data:e}),this._dirty=!0,this}quadraticCurveToShort(e,t,s){const r=this.instructions[this.instructions.length-1],n=this.getLastPoint(ye.shared);let o=0,a=0;if(!r||r.action!=="quadraticCurveTo")o=n.x,a=n.y;else{o=r.data[0],a=r.data[1];const l=n.x,c=n.y;o=l+(l-o),a=c+(c-a)}return this.instructions.push({action:"quadraticCurveTo",data:[o,a,e,t,s]}),this._dirty=!0,this}rect(e,t,s,r,n){return this.instructions.push({action:"rect",data:[e,t,s,r,n]}),this._dirty=!0,this}circle(e,t,s,r){return this.instructions.push({action:"circle",data:[e,t,s,r]}),this._dirty=!0,this}roundRect(...e){return this.instructions.push({action:"roundRect",data:e}),this._dirty=!0,this}poly(...e){return this.instructions.push({action:"poly",data:e}),this._dirty=!0,this}regularPoly(...e){return this.instructions.push({action:"regularPoly",data:e}),this._dirty=!0,this}roundPoly(...e){return this.instructions.push({action:"roundPoly",data:e}),this._dirty=!0,this}roundShape(...e){return this.instructions.push({action:"roundShape",data:e}),this._dirty=!0,this}filletRect(...e){return this.instructions.push({action:"filletRect",data:e}),this._dirty=!0,this}chamferRect(...e){return this.instructions.push({action:"chamferRect",data:e}),this._dirty=!0,this}star(e,t,s,r,n,o,a){n||(n=r/2);const l=-1*Math.PI/2+o,c=s*2,h=Math.PI*2/c,u=[];for(let p=0;p<c;p++){const d=p%2?n:r,g=p*h+l;u.push(e+d*Math.cos(g),t+d*Math.sin(g))}return this.poly(u,!0,a),this}clone(e=!1){const t=new Mt;if(t.checkForHoles=this.checkForHoles,!e)t.instructions=this.instructions.slice();else for(let s=0;s<this.instructions.length;s++){const r=this.instructions[s];t.instructions.push({action:r.action,data:r.data.slice()})}return t}clear(){return this.instructions.length=0,this._dirty=!0,this}transform(e){if(e.isIdentity())return this;const t=e.a,s=e.b,r=e.c,n=e.d,o=e.tx,a=e.ty;let l=0,c=0,h=0,u=0,p=0,d=0,g=0,_=0;for(let b=0;b<this.instructions.length;b++){const v=this.instructions[b],C=v.data;switch(v.action){case"moveTo":case"lineTo":l=C[0],c=C[1],C[0]=t*l+r*c+o,C[1]=s*l+n*c+a;break;case"bezierCurveTo":h=C[0],u=C[1],p=C[2],d=C[3],l=C[4],c=C[5],C[0]=t*h+r*u+o,C[1]=s*h+n*u+a,C[2]=t*p+r*d+o,C[3]=s*p+n*d+a,C[4]=t*l+r*c+o,C[5]=s*l+n*c+a;break;case"quadraticCurveTo":h=C[0],u=C[1],l=C[2],c=C[3],C[0]=t*h+r*u+o,C[1]=s*h+n*u+a,C[2]=t*l+r*c+o,C[3]=s*l+n*c+a;break;case"arcToSvg":l=C[5],c=C[6],g=C[0],_=C[1],C[0]=t*g+r*_,C[1]=s*g+n*_,C[5]=t*l+r*c+o,C[6]=s*l+n*c+a;break;case"circle":C[4]=fi(C[3],e);break;case"rect":C[4]=fi(C[4],e);break;case"ellipse":C[8]=fi(C[8],e);break;case"roundRect":C[5]=fi(C[5],e);break;case"addPath":C[0].transform(e);break;case"poly":C[2]=fi(C[2],e);break;default:ie("unknown transform action",v.action);break}}return this._dirty=!0,this}get bounds(){return this.shapePath.bounds}getLastPoint(e){let t=this.instructions.length-1,s=this.instructions[t];if(!s)return e.x=0,e.y=0,e;for(;s.action==="closePath";){if(t--,t<0)return e.x=0,e.y=0,e;s=this.instructions[t]}switch(s.action){case"moveTo":case"lineTo":e.x=s.data[0],e.y=s.data[1];break;case"quadraticCurveTo":e.x=s.data[2],e.y=s.data[3];break;case"bezierCurveTo":e.x=s.data[4],e.y=s.data[5];break;case"arc":case"arcToSvg":e.x=s.data[5],e.y=s.data[6];break;case"addPath":s.data[0].getLastPoint(e);break}return e}}function fi(i,e){return i?i.prepend(e):e.clone()}function Ie(i,e,t){const s=i.getAttribute(e);return s?Number(s):t}function Kg(i,e){const t=i.querySelectorAll("defs");for(let s=0;s<t.length;s++){const r=t[s];for(let n=0;n<r.children.length;n++){const o=r.children[n];switch(o.nodeName.toLowerCase()){case"lineargradient":e.defs[o.id]=Zg(o);break;case"radialgradient":e.defs[o.id]=Jg();break}}}}function Zg(i){const e=Ie(i,"x1",0),t=Ie(i,"y1",0),s=Ie(i,"x2",1),r=Ie(i,"y2",0),n=i.getAttribute("gradientUnits")||"objectBoundingBox",o=new As(e,t,s,r,n==="objectBoundingBox"?"local":"global");for(let a=0;a<i.children.length;a++){const l=i.children[a],c=Ie(l,"offset",0),h=Pe.shared.setValue(l.getAttribute("stop-color")).toNumber();o.addColorStop(c,h)}return o}function Jg(i){return ie("[SVG Parser] Radial gradients are not yet supported"),new As(0,0,1,0)}function Ac(i){const e=i.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return e?e[1]:""}const wc={fill:{type:"paint",default:0},"fill-opacity":{type:"number",default:1},stroke:{type:"paint",default:0},"stroke-width":{type:"number",default:1},"stroke-opacity":{type:"number",default:1},"stroke-linecap":{type:"string",default:"butt"},"stroke-linejoin":{type:"string",default:"miter"},"stroke-miterlimit":{type:"number",default:10},"stroke-dasharray":{type:"string",default:"none"},"stroke-dashoffset":{type:"number",default:0},opacity:{type:"number",default:1}};function Ic(i,e){const t=i.getAttribute("style"),s={},r={},n={strokeStyle:s,fillStyle:r,useFill:!1,useStroke:!1};for(const o in wc){const a=i.getAttribute(o);a&&Rc(e,n,o,a.trim())}if(t){const o=t.split(";");for(let a=0;a<o.length;a++){const l=o[a].trim(),[c,h]=l.split(":");wc[c]&&Rc(e,n,c,h.trim())}}return{strokeStyle:n.useStroke?s:null,fillStyle:n.useFill?r:null,useFill:n.useFill,useStroke:n.useStroke}}function Rc(i,e,t,s){switch(t){case"stroke":if(s!=="none"){if(s.startsWith("url(")){const r=Ac(s);e.strokeStyle.fill=i.defs[r]}else e.strokeStyle.color=Pe.shared.setValue(s).toNumber();e.useStroke=!0}break;case"stroke-width":e.strokeStyle.width=Number(s);break;case"fill":if(s!=="none"){if(s.startsWith("url(")){const r=Ac(s);e.fillStyle.fill=i.defs[r]}else e.fillStyle.color=Pe.shared.setValue(s).toNumber();e.useFill=!0}break;case"fill-opacity":e.fillStyle.alpha=Number(s);break;case"stroke-opacity":e.strokeStyle.alpha=Number(s);break;case"opacity":e.fillStyle.alpha=Number(s),e.strokeStyle.alpha=Number(s);break}}function Qg(i){if(i.length<=2)return!0;const e=i.map(a=>a.area).sort((a,l)=>l-a),[t,s]=e,r=e[e.length-1],n=t/s,o=s/r;return!(n>3&&o<2)}function e_(i){return i.split(/(?=[Mm])/).filter(s=>s.trim().length>0)}function t_(i){const e=i.match(/[-+]?[0-9]*\.?[0-9]+/g);if(!e||e.length<4)return 0;const t=e.map(Number),s=[],r=[];for(let h=0;h<t.length;h+=2)h+1<t.length&&(s.push(t[h]),r.push(t[h+1]));if(s.length===0||r.length===0)return 0;const n=Math.min(...s),o=Math.max(...s),a=Math.min(...r),l=Math.max(...r);return(o-n)*(l-a)}function Mc(i,e){const t=new Mt(i,!1);for(const s of t.instructions)e.instructions.push(s)}function s_(i,e){if(typeof i=="string"){const o=document.createElement("div");o.innerHTML=i.trim(),i=o.querySelector("svg")}const t={context:e,defs:{},path:new Mt};Kg(i,t);const s=i.children,{fillStyle:r,strokeStyle:n}=Ic(i,t);for(let o=0;o<s.length;o++){const a=s[o];a.nodeName.toLowerCase()!=="defs"&&Pc(a,t,r,n)}return e}function Pc(i,e,t,s){const r=i.children,{fillStyle:n,strokeStyle:o}=Ic(i,e);n&&t?t={...t,...n}:n&&(t=n),o&&s?s={...s,...o}:o&&(s=o);const a=!t&&!s;a&&(t={color:0});let l,c,h,u,p,d,g,_,b,v,C,E,S,w,R,M,D;switch(i.nodeName.toLowerCase()){case"path":{w=i.getAttribute("d");const G=i.getAttribute("fill-rule"),k=e_(w),O=G==="evenodd",V=k.length>1;if(O&&V){const z=k.map(B=>({path:B,area:t_(B)}));if(z.sort((B,U)=>U.area-B.area),k.length>3||!Qg(z))for(let B=0;B<z.length;B++){const U=z[B],q=B===0;e.context.beginPath();const N=new Mt(void 0,!0);Mc(U.path,N),e.context.path(N),q?(t&&e.context.fill(t),s&&e.context.stroke(s)):e.context.cut()}else for(let B=0;B<z.length;B++){const U=z[B],q=B%2===1;e.context.beginPath();const N=new Mt(void 0,!0);Mc(U.path,N),e.context.path(N),q?e.context.cut():(t&&e.context.fill(t),s&&e.context.stroke(s))}}else{const z=G?G==="evenodd":!0;R=new Mt(w,z),e.context.path(R),t&&e.context.fill(t),s&&e.context.stroke(s)}break}case"circle":g=Ie(i,"cx",0),_=Ie(i,"cy",0),b=Ie(i,"r",0),e.context.ellipse(g,_,b,b),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"rect":l=Ie(i,"x",0),c=Ie(i,"y",0),M=Ie(i,"width",0),D=Ie(i,"height",0),v=Ie(i,"rx",0),C=Ie(i,"ry",0),v||C?e.context.roundRect(l,c,M,D,v||C):e.context.rect(l,c,M,D),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"ellipse":g=Ie(i,"cx",0),_=Ie(i,"cy",0),v=Ie(i,"rx",0),C=Ie(i,"ry",0),e.context.beginPath(),e.context.ellipse(g,_,v,C),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"line":h=Ie(i,"x1",0),u=Ie(i,"y1",0),p=Ie(i,"x2",0),d=Ie(i,"y2",0),e.context.beginPath(),e.context.moveTo(h,u),e.context.lineTo(p,d),s&&e.context.stroke(s);break;case"polygon":S=i.getAttribute("points"),E=S.match(/-?\d+/g).map(G=>parseInt(G,10)),e.context.poly(E,!0),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"polyline":S=i.getAttribute("points"),E=S.match(/-?\d+/g).map(G=>parseInt(G,10)),e.context.poly(E,!1),s&&e.context.stroke(s);break;case"g":case"svg":break;default:{ie(`[SVG parser] <${i.nodeName}> elements unsupported`);break}}a&&(t=null);for(let G=0;G<r.length;G++)Pc(r[G],e,t,s)}const kc={repeat:{addressModeU:"repeat",addressModeV:"repeat"},"repeat-x":{addressModeU:"repeat",addressModeV:"clamp-to-edge"},"repeat-y":{addressModeU:"clamp-to-edge",addressModeV:"repeat"},"no-repeat":{addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}};class Oc{constructor(e,t){this.uid=be("fillPattern"),this._tick=0,this.transform=new H,this.texture=e,this.transform.scale(1/e.frame.width,1/e.frame.height),t&&(e.source.style.addressModeU=kc[t].addressModeU,e.source.style.addressModeV=kc[t].addressModeV)}setTransform(e){const t=this.texture;this.transform.copyFrom(e),this.transform.invert(),this.transform.scale(1/t.frame.width,1/t.frame.height),this._tick++}get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._tick++)}get styleKey(){return`fill-pattern-${this.uid}-${this._tick}`}destroy(){this.texture.destroy(!0),this.texture=null}}function i_(i){return Pe.isColorLike(i)}function Bc(i){return i instanceof Oc}function Dc(i){return i instanceof As}function r_(i){return i instanceof j}function n_(i,e,t){const s=Pe.shared.setValue(e??0);return i.color=s.toNumber(),i.alpha=s.alpha===1?t.alpha:s.alpha,i.texture=j.WHITE,{...t,...i}}function o_(i,e,t){return i.texture=e,{...t,...i}}function Nc(i,e,t){return i.fill=e,i.color=16777215,i.texture=e.texture,i.matrix=e.transform,{...t,...i}}function Uc(i,e,t){return e.buildGradient(),i.fill=e,i.color=16777215,i.texture=e.texture,i.matrix=e.transform,i.textureSpace=e.textureSpace,{...t,...i}}function a_(i,e){const t={...e,...i},s=Pe.shared.setValue(t.color);return t.alpha*=s.alpha,t.color=s.toNumber(),t}function pi(i,e){if(i==null)return null;const t={},s=i;return i_(i)?n_(t,i,e):r_(i)?o_(t,i,e):Bc(i)?Nc(t,i,e):Dc(i)?Uc(t,i,e):s.fill&&Bc(s.fill)?Nc(s,s.fill,e):s.fill&&Dc(s.fill)?Uc(s,s.fill,e):a_(s,e)}function Gc(i,e){const{width:t,alignment:s,miterLimit:r,cap:n,join:o,pixelLine:a,...l}=e,c=pi(i,l);return c?{width:t,alignment:s,miterLimit:r,cap:n,join:o,pixelLine:a,...c}:null}function l_(i,e){let t=1;const s=i.shapePath.shapePrimitives;for(let r=0;r<s.length;r++){const n=s[r].shape;if(n.type!=="polygon")continue;const o=n.points,a=o.length;if(a<6)continue;const l=n.closePath;for(let c=0;c<a;c+=2){if(!l&&(c===0||c===a-2))continue;const h=(c-2+a)%a,u=(c+2)%a,p=o[h],d=o[h+1],g=o[c],_=o[c+1],b=o[u],v=o[u+1],C=p-g,E=d-_,S=b-g,w=v-_,R=C*C+E*E,M=S*S+w*w;if(R<1e-12||M<1e-12)continue;let k=(C*S+E*w)/Math.sqrt(R*M);k<-1?k=-1:k>1&&(k=1);const O=Math.sqrt((1-k)*.5);if(O<1e-6)continue;const V=Math.min(1/O,e);V>t&&(t=V)}}return t}const c_=new ye,Fc=new H,$n=class Et extends lt{constructor(){super(...arguments),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=be("graphicsContext"),this.dirty=!0,this.batchMode="auto",this.instructions=[],this.destroyed=!1,this._activePath=new Mt,this._transform=new H,this._fillStyle={...Et.defaultFillStyle},this._strokeStyle={...Et.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new Ye,this._boundsDirty=!0}clone(){const e=new Et;return e.batchMode=this.batchMode,e.instructions=this.instructions.slice(),e._activePath=this._activePath.clone(),e._transform=this._transform.clone(),e._fillStyle={...this._fillStyle},e._strokeStyle={...this._strokeStyle},e._stateStack=this._stateStack.slice(),e._bounds=this._bounds.clone(),e._boundsDirty=!0,e}get fillStyle(){return this._fillStyle}set fillStyle(e){this._fillStyle=pi(e,Et.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(e){this._strokeStyle=Gc(e,Et.defaultStrokeStyle)}setFillStyle(e){return this._fillStyle=pi(e,Et.defaultFillStyle),this}setStrokeStyle(e){return this._strokeStyle=pi(e,Et.defaultStrokeStyle),this}texture(e,t,s,r,n,o){return this.instructions.push({action:"texture",data:{image:e,dx:s||0,dy:r||0,dw:n||e.frame.width,dh:o||e.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:t||t===0?Pe.shared.setValue(t).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new Mt,this}fill(e,t){let s;const r=this.instructions[this.instructions.length-1];return this._tick===0&&(r==null?void 0:r.action)==="stroke"?s=r.data.path:s=this._activePath.clone(),s?(e!=null&&(t!==void 0&&typeof e=="number"&&(ee(Be,"GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead"),e={color:e,alpha:t}),this._fillStyle=pi(e,Et.defaultFillStyle)),this.instructions.push({action:"fill",data:{style:this.fillStyle,path:s}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}_initNextPathLocation(){const{x:e,y:t}=this._activePath.getLastPoint(ye.shared);this._activePath.clear(),this._activePath.moveTo(e,t)}stroke(e){let t;const s=this.instructions[this.instructions.length-1];return this._tick===0&&(s==null?void 0:s.action)==="fill"?t=s.data.path:t=this._activePath.clone(),t?(e!=null&&(this._strokeStyle=Gc(e,Et.defaultStrokeStyle)),this.instructions.push({action:"stroke",data:{style:this.strokeStyle,path:t}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}cut(){for(let e=0;e<2;e++){const t=this.instructions[this.instructions.length-1-e],s=this._activePath.clone();if(t&&(t.action==="stroke"||t.action==="fill"))if(t.data.hole)t.data.hole.addPath(s);else{t.data.hole=s;break}}return this._initNextPathLocation(),this}arc(e,t,s,r,n,o){this._tick++;const a=this._transform;return this._activePath.arc(a.a*e+a.c*t+a.tx,a.b*e+a.d*t+a.ty,s,r,n,o),this}arcTo(e,t,s,r,n){this._tick++;const o=this._transform;return this._activePath.arcTo(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,o.a*s+o.c*r+o.tx,o.b*s+o.d*r+o.ty,n),this}arcToSvg(e,t,s,r,n,o,a){this._tick++;const l=this._transform;return this._activePath.arcToSvg(e,t,s,r,n,l.a*o+l.c*a+l.tx,l.b*o+l.d*a+l.ty),this}bezierCurveTo(e,t,s,r,n,o,a){this._tick++;const l=this._transform;return this._activePath.bezierCurveTo(l.a*e+l.c*t+l.tx,l.b*e+l.d*t+l.ty,l.a*s+l.c*r+l.tx,l.b*s+l.d*r+l.ty,l.a*n+l.c*o+l.tx,l.b*n+l.d*o+l.ty,a),this}closePath(){var e;return this._tick++,(e=this._activePath)==null||e.closePath(),this}ellipse(e,t,s,r){return this._tick++,this._activePath.ellipse(e,t,s,r,this._transform.clone()),this}circle(e,t,s){return this._tick++,this._activePath.circle(e,t,s,this._transform.clone()),this}path(e){return this._tick++,this._activePath.addPath(e,this._transform.clone()),this}lineTo(e,t){this._tick++;const s=this._transform;return this._activePath.lineTo(s.a*e+s.c*t+s.tx,s.b*e+s.d*t+s.ty),this}moveTo(e,t){this._tick++;const s=this._transform,r=this._activePath.instructions,n=s.a*e+s.c*t+s.tx,o=s.b*e+s.d*t+s.ty;return r.length===1&&r[0].action==="moveTo"?(r[0].data[0]=n,r[0].data[1]=o,this):(this._activePath.moveTo(n,o),this)}quadraticCurveTo(e,t,s,r,n){this._tick++;const o=this._transform;return this._activePath.quadraticCurveTo(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,o.a*s+o.c*r+o.tx,o.b*s+o.d*r+o.ty,n),this}rect(e,t,s,r){return this._tick++,this._activePath.rect(e,t,s,r,this._transform.clone()),this}roundRect(e,t,s,r,n){return this._tick++,this._activePath.roundRect(e,t,s,r,n,this._transform.clone()),this}poly(e,t){return this._tick++,this._activePath.poly(e,t,this._transform.clone()),this}regularPoly(e,t,s,r,n=0,o){return this._tick++,this._activePath.regularPoly(e,t,s,r,n,o),this}roundPoly(e,t,s,r,n,o){return this._tick++,this._activePath.roundPoly(e,t,s,r,n,o),this}roundShape(e,t,s,r){return this._tick++,this._activePath.roundShape(e,t,s,r),this}filletRect(e,t,s,r,n){return this._tick++,this._activePath.filletRect(e,t,s,r,n),this}chamferRect(e,t,s,r,n,o){return this._tick++,this._activePath.chamferRect(e,t,s,r,n,o),this}star(e,t,s,r,n=0,o=0){return this._tick++,this._activePath.star(e,t,s,r,n,o,this._transform.clone()),this}svg(e){return this._tick++,s_(e,this),this}restore(){const e=this._stateStack.pop();return e&&(this._transform=e.transform,this._fillStyle=e.fillStyle,this._strokeStyle=e.strokeStyle),this}save(){return this._stateStack.push({transform:this._transform.clone(),fillStyle:{...this._fillStyle},strokeStyle:{...this._strokeStyle}}),this}getTransform(){return this._transform}resetTransform(){return this._transform.identity(),this}rotate(e){return this._transform.rotate(e),this}scale(e,t=e){return this._transform.scale(e,t),this}setTransform(e,t,s,r,n,o){return e instanceof H?(this._transform.set(e.a,e.b,e.c,e.d,e.tx,e.ty),this):(this._transform.set(e,t,s,r,n,o),this)}transform(e,t,s,r,n,o){return e instanceof H?(this._transform.append(e),this):(Fc.set(e,t,s,r,n,o),this._transform.append(Fc),this)}translate(e,t=e){return this._transform.translate(e,t),this}clear(){return this._activePath.clear(),this.instructions.length=0,this.resetTransform(),this.onUpdate(),this}onUpdate(){this._boundsDirty=!0,this.dirty=!0,this.emit("update",this,16)}get bounds(){if(!this._boundsDirty)return this._bounds;this._boundsDirty=!1;const e=this._bounds;e.clear();for(let t=0;t<this.instructions.length;t++){const s=this.instructions[t],r=s.action;if(r==="fill"){const n=s.data;e.addBounds(n.path.bounds)}else if(r==="texture"){const n=s.data;e.addFrame(n.dx,n.dy,n.dx+n.dw,n.dy+n.dh,n.transform)}if(r==="stroke"){const n=s.data,o=n.style.alignment;let a=n.style.width*(1-o);n.style.join==="miter"&&(a*=l_(n.path,n.style.miterLimit));const l=n.path.bounds;e.addFrame(l.minX-a,l.minY-a,l.maxX+a,l.maxY+a)}}return e.isValid||e.set(0,0,0,0),e}containsPoint(e){var r;if(!this.bounds.containsPoint(e.x,e.y))return!1;const t=this.instructions;let s=!1;for(let n=0;n<t.length;n++){const o=t[n],a=o.data,l=a.path;if(!o.action||!l)continue;const c=a.style,h=l.shapePath.shapePrimitives;for(let u=0;u<h.length;u++){const p=h[u].shape;if(!c||!p)continue;const d=h[u].transform,g=d?d.applyInverse(e,c_):e;if(o.action==="fill")s=p.contains(g.x,g.y);else{const b=c;s=p.strokeContains(g.x,g.y,b.width,b.alignment)}const _=a.hole;if(_){const b=(r=_.shapePath)==null?void 0:r.shapePrimitives;if(b)for(let v=0;v<b.length;v++)b[v].shape.contains(g.x,g.y)&&(s=!1)}if(s)return!0}}return s}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(e=!1){if(this.destroyed)return;if(this.destroyed=!0,this._stateStack.length=0,this._transform=null,this.unload(),this.emit("destroy",this),this.removeAllListeners(),typeof e=="boolean"?e:e==null?void 0:e.texture){const s=typeof e=="boolean"?e:e==null?void 0:e.textureSource;this._fillStyle.texture&&(this._fillStyle.fill&&"uid"in this._fillStyle.fill?this._fillStyle.fill.destroy():this._fillStyle.texture.destroy(s)),this._strokeStyle.texture&&(this._strokeStyle.fill&&"uid"in this._strokeStyle.fill?this._strokeStyle.fill.destroy():this._strokeStyle.texture.destroy(s))}this._fillStyle=null,this._strokeStyle=null,this.instructions=null,this._activePath=null,this._bounds=null,this._stateStack=null,this.customShader=null,this._transform=null}};$n.defaultFillStyle={color:16777215,alpha:1,texture:j.WHITE,matrix:null,fill:null,textureSpace:"local"},$n.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:"butt",join:"miter",texture:j.WHITE,matrix:null,fill:null,textureSpace:"local",pixelLine:!1};let mi=$n;class Lc{constructor(e){this._attachedDomElements=[],this._renderer=e,this._renderer.runners.postrender.add(this),this._renderer.runners.init.add(this),this._domElement=document.createElement("div"),this._domElement.style.position="absolute",this._domElement.style.top="0",this._domElement.style.left="0",this._domElement.style.pointerEvents="none",this._domElement.style.zIndex="1000"}init(){this._canvasObserver=new Qa({domElement:this._domElement,renderer:this._renderer})}addRenderable(e,t){this._attachedDomElements.includes(e)||this._attachedDomElements.push(e)}updateRenderable(e){}validateRenderable(e){return!0}postrender(){const e=this._attachedDomElements;if(e.length===0){this._domElement.remove();return}this._canvasObserver.ensureAttached();for(let t=0;t<e.length;t++){const s=e[t],r=s.element;if(!s.parent||s.globalDisplayStatus<7)r==null||r.remove(),e.splice(t,1),t--;else{this._domElement.contains(r)||(r.style.position="absolute",r.style.pointerEvents="auto",this._domElement.appendChild(r));const n=s.worldTransform,o=s._anchor,a=s.width*o.x,l=s.height*o.y;r.style.transformOrigin=`${a}px ${l}px`,r.style.transform=`matrix(${n.a}, ${n.b}, ${n.c}, ${n.d}, ${n.tx-a}, ${n.ty-l})`,r.style.opacity=s.groupAlpha.toString()}}}destroy(){var e;this._renderer.runners.postrender.remove(this);for(let t=0;t<this._attachedDomElements.length;t++)(e=this._attachedDomElements[t].element)==null||e.remove();this._attachedDomElements.length=0,this._domElement.remove(),this._canvasObserver.destroy(),this._renderer=null}}Lc.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"dom"};class h_{constructor(){this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}init(e){this.removeTickerListener(),this.events=e,this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}get pauseUpdate(){return this._pauseUpdate}set pauseUpdate(e){this._pauseUpdate=e}addTickerListener(){this._tickerAdded||!this.domElement||(at.system.add(this._tickerUpdate,this,ys.INTERACTION),this._tickerAdded=!0)}removeTickerListener(){this._tickerAdded&&(at.system.remove(this._tickerUpdate,this),this._tickerAdded=!1)}pointerMoved(){this._didMove=!0}_update(){if(!this.domElement||this._pauseUpdate)return;if(this._didMove){this._didMove=!1;return}const e=this.events._rootPointerEvent;this.events.supportsTouchEvents&&e.pointerType==="touch"||globalThis.document.dispatchEvent(this.events.supportsPointerEvents?new PointerEvent("pointermove",{clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,pointerId:e.pointerId}):new MouseEvent("mousemove",{clientX:e.clientX,clientY:e.clientY}))}_tickerUpdate(e){this._deltaTime+=e.deltaTime,!(this._deltaTime<this.interactionFrequency)&&(this._deltaTime=0,this._update())}destroy(){this.removeTickerListener(),this.events=null,this.domElement=null,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}}const Pt=new h_;class ir extends qs{constructor(){super(...arguments),this.client=new ye,this.movement=new ye,this.offset=new ye,this.global=new ye,this.screen=new ye}get clientX(){return this.client.x}get clientY(){return this.client.y}get x(){return this.clientX}get y(){return this.clientY}get movementX(){return this.movement.x}get movementY(){return this.movement.y}get offsetX(){return this.offset.x}get offsetY(){return this.offset.y}get globalX(){return this.global.x}get globalY(){return this.global.y}get screenX(){return this.screen.x}get screenY(){return this.screen.y}getLocalPosition(e,t,s){return e.worldTransform.applyInverse(s||this.global,t)}getModifierState(e){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(e)}initMouseEvent(e,t,s,r,n,o,a,l,c,h,u,p,d,g,_){throw new Error("Method not implemented.")}}class ht extends ir{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1}getCoalescedEvents(){return this.type==="pointermove"||this.type==="mousemove"||this.type==="touchmove"?[this]:[]}getPredictedEvents(){throw new Error("getPredictedEvents is not supported!")}}class ws extends ir{constructor(){super(...arguments),this.DOM_DELTA_PIXEL=0,this.DOM_DELTA_LINE=1,this.DOM_DELTA_PAGE=2}}ws.DOM_DELTA_PIXEL=0,ws.DOM_DELTA_LINE=1,ws.DOM_DELTA_PAGE=2;const u_=2048,d_=new ye,gi=new ye;class f_{constructor(e){this.dispatch=new lt,this.moveOnAll=!1,this.enableGlobalMoveEvents=!0,this.mappingState={trackingData:{}},this.eventPool=new Map,this._allInteractiveElements=[],this._hitElements=[],this._isPointerMoveEvent=!1,this.rootTarget=e,this.hitPruneFn=this.hitPruneFn.bind(this),this.hitTestFn=this.hitTestFn.bind(this),this.mapPointerDown=this.mapPointerDown.bind(this),this.mapPointerMove=this.mapPointerMove.bind(this),this.mapPointerOut=this.mapPointerOut.bind(this),this.mapPointerOver=this.mapPointerOver.bind(this),this.mapPointerUp=this.mapPointerUp.bind(this),this.mapPointerUpOutside=this.mapPointerUpOutside.bind(this),this.mapWheel=this.mapWheel.bind(this),this.mappingTable={},this.addEventMapping("pointerdown",this.mapPointerDown),this.addEventMapping("pointermove",this.mapPointerMove),this.addEventMapping("pointerout",this.mapPointerOut),this.addEventMapping("pointerleave",this.mapPointerOut),this.addEventMapping("pointerover",this.mapPointerOver),this.addEventMapping("pointerup",this.mapPointerUp),this.addEventMapping("pointerupoutside",this.mapPointerUpOutside),this.addEventMapping("wheel",this.mapWheel)}addEventMapping(e,t){this.mappingTable[e]||(this.mappingTable[e]=[]),this.mappingTable[e].push({fn:t,priority:0}),this.mappingTable[e].sort((s,r)=>s.priority-r.priority)}dispatchEvent(e,t){e.propagationStopped=!1,e.propagationImmediatelyStopped=!1,this.propagate(e,t),this.dispatch.emit(t||e.type,e)}mapEvent(e){if(!this.rootTarget)return;const t=this.mappingTable[e.type];if(t)for(let s=0,r=t.length;s<r;s++)t[s].fn(e);else ie(`[EventBoundary]: Event mapping not defined for ${e.type}`)}hitTest(e,t){Pt.pauseUpdate=!0;const r=this._isPointerMoveEvent&&this.enableGlobalMoveEvents?"hitTestMoveRecursive":"hitTestRecursive",n=this[r](this.rootTarget,this.rootTarget.eventMode,d_.set(e,t),this.hitTestFn,this.hitPruneFn);return n&&n[0]}propagate(e,t){if(!e.target)return;const s=e.composedPath();e.eventPhase=e.CAPTURING_PHASE;for(let r=0,n=s.length-1;r<n;r++)if(e.currentTarget=s[r],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return;if(e.eventPhase=e.AT_TARGET,e.currentTarget=e.target,this.notifyTarget(e,t),!(e.propagationStopped||e.propagationImmediatelyStopped)){e.eventPhase=e.BUBBLING_PHASE;for(let r=s.length-2;r>=0;r--)if(e.currentTarget=s[r],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return}}all(e,t,s=this._allInteractiveElements){if(s.length===0)return;e.eventPhase=e.BUBBLING_PHASE;const r=Array.isArray(t)?t:[t];for(let n=s.length-1;n>=0;n--)r.forEach(o=>{e.currentTarget=s[n],this.notifyTarget(e,o)})}propagationPath(e){const t=[e];for(let s=0;s<u_&&e!==this.rootTarget&&e.parent;s++){if(!e.parent)throw new Error("Cannot find propagation path to disconnected target");t.push(e.parent),e=e.parent}return t.reverse(),t}hitTestMoveRecursive(e,t,s,r,n,o=!1){let a=!1;if(this._interactivePrune(e))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(Pt.pauseUpdate=!1),e.interactiveChildren&&e.children){const h=e.children;for(let u=h.length-1;u>=0;u--){const p=h[u],d=this.hitTestMoveRecursive(p,this._isInteractive(t)?t:p.eventMode,s,r,n,o||n(e,s));if(d){if(d.length>0&&!d[d.length-1].parent)continue;const g=e.isInteractive();(d.length>0||g)&&(g&&this._allInteractiveElements.push(e),d.push(e)),this._hitElements.length===0&&(this._hitElements=d),a=!0}}}const l=this._isInteractive(t),c=e.isInteractive();return c&&c&&this._allInteractiveElements.push(e),o||this._hitElements.length>0?null:a?this._hitElements:l&&!n(e,s)&&r(e,s)?c?[e]:[]:null}hitTestRecursive(e,t,s,r,n){if(this._interactivePrune(e)||n(e,s))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(Pt.pauseUpdate=!1),e.interactiveChildren&&e.children){const l=e.children,c=s;for(let h=l.length-1;h>=0;h--){const u=l[h],p=this.hitTestRecursive(u,this._isInteractive(t)?t:u.eventMode,c,r,n);if(p){if(p.length>0&&!p[p.length-1].parent)continue;const d=e.isInteractive();return(p.length>0||d)&&p.push(e),p}}}const o=this._isInteractive(t),a=e.isInteractive();return o&&r(e,s)?a?[e]:[]:null}_isInteractive(e){return e==="static"||e==="dynamic"}_interactivePrune(e){return!e||!e.visible||!e.renderable||!e.measurable||e.eventMode==="none"||e.eventMode==="passive"&&!e.interactiveChildren}hitPruneFn(e,t){if(e.hitArea&&(e.worldTransform.applyInverse(t,gi),!e.hitArea.contains(gi.x,gi.y)))return!0;if(e.effects&&e.effects.length)for(let s=0;s<e.effects.length;s++){const r=e.effects[s];if(r.containsPoint&&!r.containsPoint(t,this.hitTestFn))return!0}return!1}hitTestFn(e,t){return e.hitArea?!0:e!=null&&e.containsPoint?(e.worldTransform.applyInverse(t,gi),e.containsPoint(gi)):!1}notifyTarget(e,t){var n,o;if(!e.currentTarget.isInteractive())return;t??(t=e.type);const s=`on${t}`;(o=(n=e.currentTarget)[s])==null||o.call(n,e);const r=e.eventPhase===e.CAPTURING_PHASE||e.eventPhase===e.AT_TARGET?`${t}capture`:t;this._notifyListeners(e,r),e.eventPhase===e.AT_TARGET&&this._notifyListeners(e,t)}mapPointerDown(e){if(!(e instanceof ht)){ie("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.createPointerEvent(e);if(this.dispatchEvent(t,"pointerdown"),t.pointerType==="touch")this.dispatchEvent(t,"touchstart");else if(t.pointerType==="mouse"||t.pointerType==="pen"){const r=t.button===2;this.dispatchEvent(t,r?"rightdown":"mousedown")}const s=this.trackingData(e.pointerId);s.pressTargetsByButton[e.button]=t.composedPath(),this.freeEvent(t)}mapPointerMove(e){var l,c;if(!(e instanceof ht)){ie("EventBoundary cannot map a non-pointer event as a pointer event");return}this._allInteractiveElements.length=0,this._hitElements.length=0,this._isPointerMoveEvent=!0;const t=this.createPointerEvent(e);this._isPointerMoveEvent=!1;const s=t.pointerType==="mouse"||t.pointerType==="pen",r=this.trackingData(e.pointerId),n=this.findMountedTarget(r.overTargets);if(((l=r.overTargets)==null?void 0:l.length)>0&&n!==t.target){const h=e.type==="mousemove"?"mouseout":"pointerout",u=this.createPointerEvent(e,h,n);if(this.dispatchEvent(u,"pointerout"),s&&this.dispatchEvent(u,"mouseout"),!t.composedPath().includes(n)){const p=this.createPointerEvent(e,"pointerleave",n);for(p.eventPhase=p.AT_TARGET;p.target&&!t.composedPath().includes(p.target);)p.currentTarget=p.target,this.notifyTarget(p),s&&this.notifyTarget(p,"mouseleave"),p.target=p.target.parent;this.freeEvent(p)}this.freeEvent(u)}if(n!==t.target){const h=e.type==="mousemove"?"mouseover":"pointerover",u=this.clonePointerEvent(t,h);this.dispatchEvent(u,"pointerover"),s&&this.dispatchEvent(u,"mouseover");let p=n==null?void 0:n.parent;for(;p&&p!==this.rootTarget.parent&&p!==t.target;)p=p.parent;if(!p||p===this.rootTarget.parent){const g=this.clonePointerEvent(t,"pointerenter");for(g.eventPhase=g.AT_TARGET;g.target&&g.target!==n&&g.target!==this.rootTarget.parent;)g.currentTarget=g.target,this.notifyTarget(g),s&&this.notifyTarget(g,"mouseenter"),g.target=g.target.parent;this.freeEvent(g)}this.freeEvent(u)}const o=[],a=this.enableGlobalMoveEvents??!0;this.moveOnAll?o.push("pointermove"):this.dispatchEvent(t,"pointermove"),a&&o.push("globalpointermove"),t.pointerType==="touch"&&(this.moveOnAll?o.splice(1,0,"touchmove"):this.dispatchEvent(t,"touchmove"),a&&o.push("globaltouchmove")),s&&(this.moveOnAll?o.splice(1,0,"mousemove"):this.dispatchEvent(t,"mousemove"),a&&o.push("globalmousemove"),this.cursor=(c=t.target)==null?void 0:c.cursor),o.length>0&&this.all(t,o),this._allInteractiveElements.length=0,this._hitElements.length=0,r.overTargets=t.composedPath(),this.freeEvent(t)}mapPointerOver(e){var o;if(!(e instanceof ht)){ie("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),s=this.createPointerEvent(e),r=s.pointerType==="mouse"||s.pointerType==="pen";this.dispatchEvent(s,"pointerover"),r&&this.dispatchEvent(s,"mouseover"),s.pointerType==="mouse"&&(this.cursor=(o=s.target)==null?void 0:o.cursor);const n=this.clonePointerEvent(s,"pointerenter");for(n.eventPhase=n.AT_TARGET;n.target&&n.target!==this.rootTarget.parent;)n.currentTarget=n.target,this.notifyTarget(n),r&&this.notifyTarget(n,"mouseenter"),n.target=n.target.parent;t.overTargets=s.composedPath(),this.freeEvent(s),this.freeEvent(n)}mapPointerOut(e){if(!(e instanceof ht)){ie("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId);if(t.overTargets){const s=e.pointerType==="mouse"||e.pointerType==="pen",r=this.findMountedTarget(t.overTargets),n=this.createPointerEvent(e,"pointerout",r);this.dispatchEvent(n),s&&this.dispatchEvent(n,"mouseout");const o=this.createPointerEvent(e,"pointerleave",r);for(o.eventPhase=o.AT_TARGET;o.target&&o.target!==this.rootTarget.parent;)o.currentTarget=o.target,this.notifyTarget(o),s&&this.notifyTarget(o,"mouseleave"),o.target=o.target.parent;t.overTargets=null,this.freeEvent(n),this.freeEvent(o)}this.cursor=null}mapPointerUp(e){if(!(e instanceof ht)){ie("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=performance.now(),s=this.createPointerEvent(e);if(this.dispatchEvent(s,"pointerup"),s.pointerType==="touch")this.dispatchEvent(s,"touchend");else if(s.pointerType==="mouse"||s.pointerType==="pen"){const a=s.button===2;this.dispatchEvent(s,a?"rightup":"mouseup")}const r=this.trackingData(e.pointerId),n=this.findMountedTarget(r.pressTargetsByButton[e.button]);let o=n;if(n&&!s.composedPath().includes(n)){let a=n;for(;a&&!s.composedPath().includes(a);){if(s.currentTarget=a,this.notifyTarget(s,"pointerupoutside"),s.pointerType==="touch")this.notifyTarget(s,"touchendoutside");else if(s.pointerType==="mouse"||s.pointerType==="pen"){const l=s.button===2;this.notifyTarget(s,l?"rightupoutside":"mouseupoutside")}a=a.parent}delete r.pressTargetsByButton[e.button],o=a}if(o){const a=this.clonePointerEvent(s,"click");a.target=o,a.path=null,r.clicksByButton[e.button]||(r.clicksByButton[e.button]={clickCount:0,target:a.target,timeStamp:t});const l=r.clicksByButton[e.button];if(l.target===a.target&&t-l.timeStamp<200?++l.clickCount:l.clickCount=1,l.target=a.target,l.timeStamp=t,a.detail=l.clickCount,a.pointerType==="mouse"){const c=a.button===2;this.dispatchEvent(a,c?"rightclick":"click")}else a.pointerType==="touch"&&this.dispatchEvent(a,"tap");this.dispatchEvent(a,"pointertap"),this.freeEvent(a)}this.freeEvent(s)}mapPointerUpOutside(e){if(!(e instanceof ht)){ie("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),s=this.findMountedTarget(t.pressTargetsByButton[e.button]),r=this.createPointerEvent(e);if(s){let n=s;for(;n;)r.currentTarget=n,this.notifyTarget(r,"pointerupoutside"),r.pointerType==="touch"?this.notifyTarget(r,"touchendoutside"):(r.pointerType==="mouse"||r.pointerType==="pen")&&this.notifyTarget(r,r.button===2?"rightupoutside":"mouseupoutside"),n=n.parent;delete t.pressTargetsByButton[e.button]}this.freeEvent(r)}mapWheel(e){if(!(e instanceof ws)){ie("EventBoundary cannot map a non-wheel event as a wheel event");return}const t=this.createWheelEvent(e);this.dispatchEvent(t),this.freeEvent(t)}findMountedTarget(e){if(!e)return null;let t=e[0];for(let s=1;s<e.length&&e[s].parent===t;s++)t=e[s];return t}createPointerEvent(e,t,s){const r=this.allocateEvent(ht);return this.copyPointerData(e,r),this.copyMouseData(e,r),this.copyData(e,r),r.nativeEvent=e.nativeEvent,r.originalEvent=e,r.target=s??this.hitTest(r.global.x,r.global.y)??this._hitElements[0],typeof t=="string"&&(r.type=t),r}createWheelEvent(e){const t=this.allocateEvent(ws);return this.copyWheelData(e,t),this.copyMouseData(e,t),this.copyData(e,t),t.nativeEvent=e.nativeEvent,t.originalEvent=e,t.target=this.hitTest(t.global.x,t.global.y),t}clonePointerEvent(e,t){const s=this.allocateEvent(ht);return s.nativeEvent=e.nativeEvent,s.originalEvent=e.originalEvent,this.copyPointerData(e,s),this.copyMouseData(e,s),this.copyData(e,s),s.target=e.target,s.path=e.composedPath().slice(),s.type=t??s.type,s}copyWheelData(e,t){t.deltaMode=e.deltaMode,t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ}copyPointerData(e,t){e instanceof ht&&t instanceof ht&&(t.pointerId=e.pointerId,t.width=e.width,t.height=e.height,t.isPrimary=e.isPrimary,t.pointerType=e.pointerType,t.pressure=e.pressure,t.tangentialPressure=e.tangentialPressure,t.tiltX=e.tiltX,t.tiltY=e.tiltY,t.twist=e.twist)}copyMouseData(e,t){e instanceof ir&&t instanceof ir&&(t.altKey=e.altKey,t.button=e.button,t.buttons=e.buttons,t.client.copyFrom(e.client),t.ctrlKey=e.ctrlKey,t.metaKey=e.metaKey,t.movement.copyFrom(e.movement),t.screen.copyFrom(e.screen),t.shiftKey=e.shiftKey,t.global.copyFrom(e.global))}copyData(e,t){t.isTrusted=e.isTrusted,t.srcElement=e.srcElement,t.timeStamp=performance.now(),t.type=e.type,t.detail=e.detail,t.view=e.view,t.which=e.which,t.layer.copyFrom(e.layer),t.page.copyFrom(e.page)}trackingData(e){return this.mappingState.trackingData[e]||(this.mappingState.trackingData[e]={pressTargetsByButton:{},clicksByButton:{},overTarget:null}),this.mappingState.trackingData[e]}allocateEvent(e){this.eventPool.has(e)||this.eventPool.set(e,[]);const t=this.eventPool.get(e).pop()||new e(this);return t.eventPhase=t.NONE,t.currentTarget=null,t.defaultPrevented=!1,t.path=null,t.target=null,t}freeEvent(e){if(e.manager!==this)throw new Error("It is illegal to free an event not managed by this EventBoundary!");const t=e.constructor;this.eventPool.has(t)||this.eventPool.set(t,[]),this.eventPool.get(t).push(e)}_notifyListeners(e,t){const s=e.currentTarget._events[t];if(s)if("fn"in s)s.once&&e.currentTarget.removeListener(t,s.fn,void 0,!0),s.fn.call(s.context,e);else for(let r=0,n=s.length;r<n&&!e.propagationImmediatelyStopped;r++)s[r].once&&e.currentTarget.removeListener(t,s[r].fn,void 0,!0),s[r].fn.call(s[r].context,e)}}const p_=1,m_={touchstart:"pointerdown",touchend:"pointerup",touchendoutside:"pointerupoutside",touchmove:"pointermove",touchcancel:"pointercancel"},jn=class ia{constructor(e){this.supportsTouchEvents="ontouchstart"in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=e,this.rootBoundary=new f_(null),Pt.init(this),this.autoPreventDefault=!0,this._eventsAdded=!1,this._rootPointerEvent=new ht(null),this._rootWheelEvent=new ws(null),this.cursorStyles={default:"inherit",pointer:"pointer"},this.features=new Proxy({...ia.defaultEventFeatures},{set:(t,s,r)=>(s==="globalMove"&&(this.rootBoundary.enableGlobalMoveEvents=r),t[s]=r,!0)}),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onPointerOverOut=this._onPointerOverOut.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(e){const{canvas:t,resolution:s}=this.renderer;this.setTargetElement(t),this.resolution=s,ia._defaultEventMode=e.eventMode??"passive",Object.assign(this.features,e.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(e){this.resolution=e}destroy(){Pt.destroy(),this.setTargetElement(null),this.renderer=null,this._currentCursor=null}setCursor(e){e||(e="default");let t=!0;if(globalThis.OffscreenCanvas&&this.domElement instanceof OffscreenCanvas&&(t=!1),this._currentCursor===e)return;this._currentCursor=e;const s=this.cursorStyles[e];if(s)switch(typeof s){case"string":t&&(this.domElement.style.cursor=s);break;case"function":s(e);break;case"object":t&&Object.assign(this.domElement.style,s);break}else t&&typeof e=="string"&&!Object.prototype.hasOwnProperty.call(this.cursorStyles,e)&&(this.domElement.style.cursor=e)}get pointer(){return this._rootPointerEvent}_onPointerDown(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const t=this._normalizeToPointerData(e);this.autoPreventDefault&&t[0].isNormalized&&(e.cancelable||!("cancelable"in e))&&e.preventDefault();for(let s=0,r=t.length;s<r;s++){const n=t[s],o=this._bootstrapEvent(this._rootPointerEvent,n);this.rootBoundary.mapEvent(o)}this.setCursor(this.rootBoundary.cursor)}_onPointerMove(e){if(!this.features.move)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,Pt.pointerMoved();const t=this._normalizeToPointerData(e);for(let s=0,r=t.length;s<r;s++){const n=this._bootstrapEvent(this._rootPointerEvent,t[s]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}_onPointerUp(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let t=e.target;e.composedPath&&e.composedPath().length>0&&(t=e.composedPath()[0]);const s=t!==this.domElement?"outside":"",r=this._normalizeToPointerData(e);for(let n=0,o=r.length;n<o;n++){const a=this._bootstrapEvent(this._rootPointerEvent,r[n]);a.type+=s,this.rootBoundary.mapEvent(a)}this.setCursor(this.rootBoundary.cursor)}_onPointerOverOut(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const t=this._normalizeToPointerData(e);for(let s=0,r=t.length;s<r;s++){const n=this._bootstrapEvent(this._rootPointerEvent,t[s]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}onWheel(e){if(!this.features.wheel)return;const t=this.normalizeWheelEvent(e);this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,this.rootBoundary.mapEvent(t)}setTargetElement(e){this._removeEvents(),this.domElement=e,Pt.domElement=e,this._addEvents()}_addEvents(){if(this._eventsAdded||!this.domElement)return;Pt.addTickerListener();const e=this.domElement.style;e&&(globalThis.navigator.msPointerEnabled?(e.msContentZooming="none",e.msTouchAction="none"):this.supportsPointerEvents&&(e.touchAction="none")),this.supportsPointerEvents?(globalThis.document.addEventListener("pointermove",this._onPointerMove,!0),this.domElement.addEventListener("pointerdown",this._onPointerDown,!0),this.domElement.addEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.addEventListener("pointerover",this._onPointerOverOut,!0),globalThis.addEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.addEventListener("mousemove",this._onPointerMove,!0),this.domElement.addEventListener("mousedown",this._onPointerDown,!0),this.domElement.addEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.addEventListener("mouseover",this._onPointerOverOut,!0),globalThis.addEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.addEventListener("touchstart",this._onPointerDown,!0),this.domElement.addEventListener("touchend",this._onPointerUp,!0),this.domElement.addEventListener("touchmove",this._onPointerMove,!0))),this.domElement.addEventListener("wheel",this.onWheel,{passive:!0,capture:!0}),this._eventsAdded=!0}_removeEvents(){if(!this._eventsAdded||!this.domElement)return;Pt.removeTickerListener();const e=this.domElement.style;e&&(globalThis.navigator.msPointerEnabled?(e.msContentZooming="",e.msTouchAction=""):this.supportsPointerEvents&&(e.touchAction="")),this.supportsPointerEvents?(globalThis.document.removeEventListener("pointermove",this._onPointerMove,!0),this.domElement.removeEventListener("pointerdown",this._onPointerDown,!0),this.domElement.removeEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.removeEventListener("pointerover",this._onPointerOverOut,!0),globalThis.removeEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.removeEventListener("mousemove",this._onPointerMove,!0),this.domElement.removeEventListener("mousedown",this._onPointerDown,!0),this.domElement.removeEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.removeEventListener("mouseover",this._onPointerOverOut,!0),globalThis.removeEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.removeEventListener("touchstart",this._onPointerDown,!0),this.domElement.removeEventListener("touchend",this._onPointerUp,!0),this.domElement.removeEventListener("touchmove",this._onPointerMove,!0))),this.domElement.removeEventListener("wheel",this.onWheel,!0),this.domElement=null,this._eventsAdded=!1}mapPositionToPoint(e,t,s){const r=this.domElement.isConnected?this.domElement.getBoundingClientRect():{width:this.domElement.width,height:this.domElement.height,left:0,top:0},n=1/this.resolution;e.x=(t-r.left)*(this.domElement.width/r.width)*n,e.y=(s-r.top)*(this.domElement.height/r.height)*n}_normalizeToPointerData(e){const t=[];if(this.supportsTouchEvents&&e instanceof TouchEvent)for(let s=0,r=e.changedTouches.length;s<r;s++){const n=e.changedTouches[s];typeof n.button>"u"&&(n.button=0),typeof n.buttons>"u"&&(n.buttons=1),typeof n.isPrimary>"u"&&(n.isPrimary=e.touches.length===1&&e.type==="touchstart"),typeof n.width>"u"&&(n.width=n.radiusX||1),typeof n.height>"u"&&(n.height=n.radiusY||1),typeof n.tiltX>"u"&&(n.tiltX=0),typeof n.tiltY>"u"&&(n.tiltY=0),typeof n.pointerType>"u"&&(n.pointerType="touch"),typeof n.pointerId>"u"&&(n.pointerId=n.identifier||0),typeof n.pressure>"u"&&(n.pressure=n.force||.5),typeof n.twist>"u"&&(n.twist=0),typeof n.tangentialPressure>"u"&&(n.tangentialPressure=0),typeof n.layerX>"u"&&(n.layerX=n.offsetX=n.clientX),typeof n.layerY>"u"&&(n.layerY=n.offsetY=n.clientY),n.isNormalized=!0,n.type=e.type,n.altKey??(n.altKey=e.altKey),n.ctrlKey??(n.ctrlKey=e.ctrlKey),n.metaKey??(n.metaKey=e.metaKey),n.shiftKey??(n.shiftKey=e.shiftKey),t.push(n)}else if(!globalThis.MouseEvent||e instanceof MouseEvent&&(!this.supportsPointerEvents||!(e instanceof globalThis.PointerEvent))){const s=e;typeof s.isPrimary>"u"&&(s.isPrimary=!0),typeof s.width>"u"&&(s.width=1),typeof s.height>"u"&&(s.height=1),typeof s.tiltX>"u"&&(s.tiltX=0),typeof s.tiltY>"u"&&(s.tiltY=0),typeof s.pointerType>"u"&&(s.pointerType="mouse"),typeof s.pointerId>"u"&&(s.pointerId=p_),typeof s.pressure>"u"&&(s.pressure=.5),typeof s.twist>"u"&&(s.twist=0),typeof s.tangentialPressure>"u"&&(s.tangentialPressure=0),s.isNormalized=!0,t.push(s)}else t.push(e);return t}normalizeWheelEvent(e){const t=this._rootWheelEvent;return this._transferMouseData(t,e),t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ,t.deltaMode=e.deltaMode,this.mapPositionToPoint(t.screen,e.clientX,e.clientY),t.global.copyFrom(t.screen),t.offset.copyFrom(t.screen),t.nativeEvent=e,t.type=e.type,t}_bootstrapEvent(e,t){return e.originalEvent=null,e.nativeEvent=t,e.pointerId=t.pointerId,e.width=t.width,e.height=t.height,e.isPrimary=t.isPrimary,e.pointerType=t.pointerType,e.pressure=t.pressure,e.tangentialPressure=t.tangentialPressure,e.tiltX=t.tiltX,e.tiltY=t.tiltY,e.twist=t.twist,this._transferMouseData(e,t),this.mapPositionToPoint(e.screen,t.clientX,t.clientY),e.global.copyFrom(e.screen),e.offset.copyFrom(e.screen),e.isTrusted=t.isTrusted,e.type==="pointerleave"&&(e.type="pointerout"),e.type.startsWith("mouse")&&(e.type=e.type.replace("mouse","pointer")),e.type.startsWith("touch")&&(e.type=m_[e.type]||e.type),e}_transferMouseData(e,t){e.isTrusted=t.isTrusted,e.srcElement=t.srcElement,e.timeStamp=performance.now(),e.type=t.type,e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.client.x=t.clientX,e.client.y=t.clientY,e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.movement.x=t.movementX,e.movement.y=t.movementY,e.page.x=t.pageX,e.page.y=t.pageY,e.relatedTarget=null,e.shiftKey=t.shiftKey}};jn.extension={name:"events",type:[A.WebGLSystem,A.CanvasSystem,A.WebGPUSystem],priority:-1},jn.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0};let Wc=jn;const g_={onclick:null,onmousedown:null,onmouseenter:null,onmouseleave:null,onmousemove:null,onglobalmousemove:null,onmouseout:null,onmouseover:null,onmouseup:null,onmouseupoutside:null,onpointercancel:null,onpointerdown:null,onpointerenter:null,onpointerleave:null,onpointermove:null,onglobalpointermove:null,onpointerout:null,onpointerover:null,onpointertap:null,onpointerup:null,onpointerupoutside:null,onrightclick:null,onrightdown:null,onrightup:null,onrightupoutside:null,ontap:null,ontouchcancel:null,ontouchend:null,ontouchendoutside:null,ontouchmove:null,onglobaltouchmove:null,ontouchstart:null,onwheel:null,get interactive(){return this.eventMode==="dynamic"||this.eventMode==="static"},set interactive(i){this.eventMode=i?"static":"passive"},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??Wc.defaultEventMode},set eventMode(i){this._internalEventMode=i},isInteractive(){return this.eventMode==="static"||this.eventMode==="dynamic"},interactiveChildren:!0,hitArea:null,addEventListener(i,e,t){const s=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,r=typeof t=="object"?t.signal:void 0,n=typeof t=="object"?t.once===!0:!1,o=typeof e=="function"?void 0:e;i=s?`${i}capture`:i;const a=typeof e=="function"?e:e.handleEvent,l=this;r&&r.addEventListener("abort",()=>{l.off(i,a,o)}),n?l.once(i,a,o):l.on(i,a,o)},removeEventListener(i,e,t){const s=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,r=typeof e=="function"?void 0:e;i=s?`${i}capture`:i,e=typeof e=="function"?e:e.handleEvent,this.off(i,e,r)},dispatchEvent(i){if(!(i instanceof qs))throw new Error("Container cannot propagate events outside of the Federated Events API");return i.defaultPrevented=!1,i.path=null,i.target=this,i.manager.dispatchEvent(i),!i.defaultPrevented}};var __=`in vec2 aPosition;
|
|
251
|
+
`}},lc={};function cc(i){let e=lc[i];if(e)return e;const t=new Int32Array(i);for(let s=0;s<i;s++)t[s]=s;return e=lc[i]=new gt({uTextures:{value:t,type:"i32",size:i}},{isStatic:!0}),e}class hc extends wt{constructor(e){const t=Pn({name:"batch",bits:[nc,ac(e),Dn]}),s=Mn({name:"batch",bits:[rc,oc(e),Bn]});super({glProgram:t,gpuProgram:s,resources:{batchSamplers:cc(e)}}),this.maxTextures=e}}let ci=null;const uc=class mf extends $m{constructor(e){super(e),this.geometry=new Km,this.name=mf.extension.name,this.vertexSize=6,ci??(ci=new hc(e.maxTextures)),this.shader=ci}packAttributes(e,t,s,r,n){const o=n<<16|e.roundPixels&65535,a=e.transform,l=a.a,c=a.b,h=a.c,u=a.d,p=a.tx,d=a.ty,{positions:g,uvs:_}=e,b=e.color,v=e.attributeOffset,C=v+e.attributeSize;for(let E=v;E<C;E++){const S=E*2,w=g[S],R=g[S+1];t[r++]=l*w+h*R+p,t[r++]=u*R+c*w+d,t[r++]=_[S],t[r++]=_[S+1],s[r++]=b,s[r++]=o}}packQuadAttributes(e,t,s,r,n){const o=e.texture,a=e.transform,l=a.a,c=a.b,h=a.c,u=a.d,p=a.tx,d=a.ty,g=e.bounds,_=g.maxX,b=g.minX,v=g.maxY,C=g.minY,E=o.uvs,S=e.color,w=n<<16|e.roundPixels&65535;t[r+0]=l*b+h*C+p,t[r+1]=u*C+c*b+d,t[r+2]=E.x0,t[r+3]=E.y0,s[r+4]=S,s[r+5]=w,t[r+6]=l*_+h*C+p,t[r+7]=u*C+c*_+d,t[r+8]=E.x1,t[r+9]=E.y1,s[r+10]=S,s[r+11]=w,t[r+12]=l*_+h*v+p,t[r+13]=u*v+c*_+d,t[r+14]=E.x2,t[r+15]=E.y2,s[r+16]=S,s[r+17]=w,t[r+18]=l*b+h*v+p,t[r+19]=u*v+c*b+d,t[r+20]=E.x3,t[r+21]=E.y3,s[r+22]=S,s[r+23]=w}_updateMaxTextures(e){this.shader.maxTextures!==e&&(ci=new hc(e),this.shader=ci)}destroy(){this.shader=null,super.destroy()}};uc.extension={type:[A.Batcher],name:"default"};let Nn=uc;class Rt{constructor(e){this.items=Object.create(null);const{renderer:t,type:s,onUnload:r,priority:n,name:o}=e;this._renderer=t,t.gc.addResourceHash(this,"items",s,n??0),this._onUnload=r,this.name=o}add(e){return this.items[e.uid]?!1:(this.items[e.uid]=e,e.once("unload",this.remove,this),e._gcLastUsed=this._renderer.gc.now,!0)}remove(e,...t){var r;if(!this.items[e.uid])return;const s=e._gpuData[this._renderer.uid];s&&((r=this._onUnload)==null||r.call(this,e,...t),s.destroy(),e._gpuData[this._renderer.uid]=null,this.items[e.uid]=null)}removeAll(...e){Object.values(this.items).forEach(t=>t&&this.remove(t,...e))}destroy(...e){this.removeAll(...e),this.items=Object.create(null),this._renderer=null,this._onUnload=null}}function pg(i,e,t,s,r,n,o,a=null){let l=0;t*=e,r*=n;const c=a.a,h=a.b,u=a.c,p=a.d,d=a.tx,g=a.ty;for(;l<o;){const _=i[t],b=i[t+1];s[r]=c*_+u*b+d,s[r+1]=h*_+p*b+g,r+=n,t+=e,l++}}function mg(i,e,t,s){let r=0;for(e*=t;r<s;)i[e]=0,i[e+1]=0,e+=t,r++}function dc(i,e,t,s,r){const n=e.a,o=e.b,a=e.c,l=e.d,c=e.tx,h=e.ty;t||(t=0),s||(s=2),r||(r=i.length/s-t);let u=t*s;for(let p=0;p<r;p++){const d=i[u],g=i[u+1];i[u]=n*d+a*g+c,i[u+1]=o*d+l*g+h,u+=s}}const gg=new H;class Un{constructor(){this.packAsQuad=!1,this.batcherName="default",this.topology="triangle-list",this.applyTransform=!0,this.roundPixels=0,this._batcher=null,this._batch=null}get uvs(){return this.geometryData.uvs}get positions(){return this.geometryData.vertices}get indices(){return this.geometryData.indices}get blendMode(){return this.renderable&&this.applyTransform?this.renderable.groupBlendMode:"normal"}get color(){const e=this.baseColor,t=e>>16|e&65280|(e&255)<<16,s=this.renderable;return s?gs(t,s.groupColor)+(this.alpha*s.groupAlpha*255<<24):t+(this.alpha*255<<24)}get transform(){var e;return((e=this.renderable)==null?void 0:e.groupTransform)||gg}copyTo(e){e.indexOffset=this.indexOffset,e.indexSize=this.indexSize,e.attributeOffset=this.attributeOffset,e.attributeSize=this.attributeSize,e.baseColor=this.baseColor,e.alpha=this.alpha,e.texture=this.texture,e.geometryData=this.geometryData,e.topology=this.topology}reset(){this.applyTransform=!0,this.renderable=null,this.topology="triangle-list"}destroy(){this.renderable=null,this.texture=null,this.geometryData=null,this._batcher=null,this._batch=null}}const hi={extension:{type:A.ShapeBuilder,name:"circle"},build(i,e){let t,s,r,n,o,a;if(i.type==="circle"){const S=i;if(o=a=S.radius,o<=0)return!1;t=S.x,s=S.y,r=n=0}else if(i.type==="ellipse"){const S=i;if(o=S.halfWidth,a=S.halfHeight,o<=0||a<=0)return!1;t=S.x,s=S.y,r=n=0}else{const S=i,w=S.width/2,R=S.height/2;t=S.x+w,s=S.y+R,o=a=Math.max(0,Math.min(S.radius,Math.min(w,R))),r=w-o,n=R-a}if(r<0||n<0)return!1;const l=Math.ceil(2.3*Math.sqrt(o+a)),c=l*8+(r?4:0)+(n?4:0);if(c===0)return!1;if(l===0)return e[0]=e[6]=t+r,e[1]=e[3]=s+n,e[2]=e[4]=t-r,e[5]=e[7]=s-n,!0;let h=0,u=l*4+(r?2:0)+2,p=u,d=c,g=r+o,_=n,b=t+g,v=t-g,C=s+_;if(e[h++]=b,e[h++]=C,e[--u]=C,e[--u]=v,n){const S=s-_;e[p++]=v,e[p++]=S,e[--d]=S,e[--d]=b}for(let S=1;S<l;S++){const w=Math.PI/2*(S/l),R=r+Math.cos(w)*o,M=n+Math.sin(w)*a,D=t+R,G=t-R,k=s+M,O=s-M;e[h++]=D,e[h++]=k,e[--u]=k,e[--u]=G,e[p++]=G,e[p++]=O,e[--d]=O,e[--d]=D}g=r,_=n+a,b=t+g,v=t-g,C=s+_;const E=s-_;return e[h++]=b,e[h++]=C,e[--d]=E,e[--d]=b,r&&(e[h++]=v,e[h++]=C,e[--d]=E,e[--d]=v),!0},triangulate(i,e,t,s,r,n){if(i.length===0)return;let o=0,a=0;for(let h=0;h<i.length;h+=2)o+=i[h],a+=i[h+1];o/=i.length/2,a/=i.length/2;let l=s;e[l*t]=o,e[l*t+1]=a;const c=l++;for(let h=0;h<i.length;h+=2)e[l*t]=i[h],e[l*t+1]=i[h+1],h>0&&(r[n++]=l,r[n++]=c,r[n++]=l-1),l++;r[n++]=c+1,r[n++]=c,r[n++]=l-1}},_g={...hi,extension:{...hi.extension,name:"ellipse"}},yg={...hi,extension:{...hi.extension,name:"roundedRectangle"}},fc=1e-4,pc=1e-4;function bg(i){const e=i.length;if(e<6)return 1;let t=0;for(let s=0,r=i[e-2],n=i[e-1];s<e;s+=2){const o=i[s],a=i[s+1];t+=(o-r)*(a+n),r=o,n=a}return t<0?-1:1}function mc(i,e,t,s,r,n,o,a){const l=i-t*r,c=e-s*r,h=i+t*n,u=e+s*n;let p,d;o?(p=s,d=-t):(p=-s,d=t);const g=l+p,_=c+d,b=h+p,v=u+d;return a.push(g,_),a.push(b,v),2}function ns(i,e,t,s,r,n,o,a){const l=t-i,c=s-e;let h=Math.atan2(l,c),u=Math.atan2(r-i,n-e);a&&h<u?h+=Math.PI*2:!a&&h>u&&(u+=Math.PI*2);let p=h;const d=u-h,g=Math.abs(d),_=Math.sqrt(l*l+c*c),b=(15*g*Math.sqrt(_)/Math.PI>>0)+1,v=d/b;if(p+=v,a){o.push(i,e),o.push(t,s);for(let C=1,E=p;C<b;C++,E+=v)o.push(i,e),o.push(i+Math.sin(E)*_,e+Math.cos(E)*_);o.push(i,e),o.push(r,n)}else{o.push(t,s),o.push(i,e);for(let C=1,E=p;C<b;C++,E+=v)o.push(i+Math.sin(E)*_,e+Math.cos(E)*_),o.push(i,e);o.push(r,n),o.push(i,e)}return b*2}function gc(i,e,t,s,r,n){const o=fc;if(i.length===0)return;const a=e;let l=a.alignment;if(e.alignment!==.5){let N=bg(i);l=(l-.5)*N+.5}const c=new ye(i[0],i[1]),h=new ye(i[i.length-2],i[i.length-1]),u=s,p=Math.abs(c.x-h.x)<o&&Math.abs(c.y-h.y)<o;if(u){i=i.slice(),p&&(i.pop(),i.pop(),h.set(i[i.length-2],i[i.length-1]));const N=(c.x+h.x)*.5,K=(h.y+c.y)*.5;i.unshift(N,K),i.push(N,K)}const d=r,g=i.length/2;let _=i.length;const b=d.length/2,v=a.width/2,C=v*v,E=a.miterLimit*a.miterLimit;let S=i[0],w=i[1],R=i[2],M=i[3],D=0,G=0,k=-(w-M),O=S-R,V=0,X=0,z=Math.sqrt(k*k+O*O);k/=z,O/=z,k*=v,O*=v;const de=l,B=(1-de)*2,U=de*2;u||(a.cap==="round"?_+=ns(S-k*(B-U)*.5,w-O*(B-U)*.5,S-k*B,w-O*B,S+k*U,w+O*U,d,!0)+2:a.cap==="square"&&(_+=mc(S,w,k,O,B,U,!0,d))),d.push(S-k*B,w-O*B),d.push(S+k*U,w+O*U);for(let N=1;N<g-1;++N){S=i[(N-1)*2],w=i[(N-1)*2+1],R=i[N*2],M=i[N*2+1],D=i[(N+1)*2],G=i[(N+1)*2+1],k=-(w-M),O=S-R,z=Math.sqrt(k*k+O*O),k/=z,O/=z,k*=v,O*=v,V=-(M-G),X=R-D,z=Math.sqrt(V*V+X*X),V/=z,X/=z,V*=v,X*=v;const K=R-S,Z=w-M,$=R-D,ae=G-M,xe=K*$+Z*ae,Se=Z*$-ae*K,F=Se<0;if(Math.abs(Se)<.001*Math.abs(xe)){d.push(R-k*B,M-O*B),d.push(R+k*U,M+O*U),xe>=0&&(a.join==="round"?_+=ns(R,M,R-k*B,M-O*B,R-V*B,M-X*B,d,!1)+4:_+=2,d.push(R-V*U,M-X*U),d.push(R+V*B,M+X*B));continue}const fe=(-k+S)*(-O+M)-(-k+R)*(-O+w),le=(-V+D)*(-X+M)-(-V+R)*(-X+G),L=(K*le-$*fe)/Se,me=(ae*fe-Z*le)/Se,Y=(L-R)*(L-R)+(me-M)*(me-M),se=R+(L-R)*B,we=M+(me-M)*B,ce=R-(L-R)*U,He=M-(me-M)*U,Zt=Math.min(K*K+Z*Z,$*$+ae*ae),Ct=F?B:U,hs=Zt+Ct*Ct*C;Y<=hs?a.join==="bevel"||Y/C>E?(F?(d.push(se,we),d.push(R+k*U,M+O*U),d.push(se,we),d.push(R+V*U,M+X*U)):(d.push(R-k*B,M-O*B),d.push(ce,He),d.push(R-V*B,M-X*B),d.push(ce,He)),_+=2):a.join==="round"?F?(d.push(se,we),d.push(R+k*U,M+O*U),_+=ns(R,M,R+k*U,M+O*U,R+V*U,M+X*U,d,!0)+4,d.push(se,we),d.push(R+V*U,M+X*U)):(d.push(R-k*B,M-O*B),d.push(ce,He),_+=ns(R,M,R-k*B,M-O*B,R-V*B,M-X*B,d,!1)+4,d.push(R-V*B,M-X*B),d.push(ce,He)):(d.push(se,we),d.push(ce,He)):(d.push(R-k*B,M-O*B),d.push(R+k*U,M+O*U),a.join==="round"?F?_+=ns(R,M,R+k*U,M+O*U,R+V*U,M+X*U,d,!0)+2:_+=ns(R,M,R-k*B,M-O*B,R-V*B,M-X*B,d,!1)+2:a.join==="miter"&&Y/C<=E&&(F?(d.push(ce,He),d.push(ce,He)):(d.push(se,we),d.push(se,we)),_+=2),d.push(R-V*B,M-X*B),d.push(R+V*U,M+X*U),_+=2)}S=i[(g-2)*2],w=i[(g-2)*2+1],R=i[(g-1)*2],M=i[(g-1)*2+1],k=-(w-M),O=S-R,z=Math.sqrt(k*k+O*O),k/=z,O/=z,k*=v,O*=v,d.push(R-k*B,M-O*B),d.push(R+k*U,M+O*U),u||(a.cap==="round"?_+=ns(R-k*(B-U)*.5,M-O*(B-U)*.5,R-k*B,M-O*B,R+k*U,M+O*U,d,!1)+2:a.cap==="square"&&(_+=mc(R,M,k,O,B,U,!1,d)));const q=pc*pc;for(let N=b;N<_+b-2;++N)S=d[N*2],w=d[N*2+1],R=d[(N+1)*2],M=d[(N+1)*2+1],D=d[(N+2)*2],G=d[(N+2)*2+1],!(Math.abs(S*(M-G)+R*(G-w)+D*(w-M))<q)&&n.push(N,N+1,N+2)}function vg(i,e,t,s){const r=fc;if(i.length===0)return;const n=i[0],o=i[1],a=i[i.length-2],l=i[i.length-1],c=e||Math.abs(n-a)<r&&Math.abs(o-l)<r,h=t,u=i.length/2,p=h.length/2;for(let d=0;d<u;d++)h.push(i[d*2]),h.push(i[d*2+1]);for(let d=0;d<u-1;d++)s.push(p+d,p+d+1);c&&s.push(p+u-1,p)}function _c(i,e,t,s,r,n,o){const a=Am(i,e,2);if(!a)return;for(let c=0;c<a.length;c+=3)n[o++]=a[c]+r,n[o++]=a[c+1]+r,n[o++]=a[c+2]+r;let l=r*s;for(let c=0;c<i.length;c+=2)t[l]=i[c],t[l+1]=i[c+1],l+=s}const xg=[],Cg={extension:{type:A.ShapeBuilder,name:"polygon"},build(i,e){for(let t=0;t<i.points.length;t++)e[t]=i.points[t];return!0},triangulate(i,e,t,s,r,n){_c(i,xg,e,t,s,r,n)}},Eg={extension:{type:A.ShapeBuilder,name:"rectangle"},build(i,e){const t=i,s=t.x,r=t.y,n=t.width,o=t.height;return n>0&&o>0?(e[0]=s,e[1]=r,e[2]=s+n,e[3]=r,e[4]=s+n,e[5]=r+o,e[6]=s,e[7]=r+o,!0):!1},triangulate(i,e,t,s,r,n){let o=0;s*=t,e[s+o]=i[0],e[s+o+1]=i[1],o+=t,e[s+o]=i[2],e[s+o+1]=i[3],o+=t,e[s+o]=i[6],e[s+o+1]=i[7],o+=t,e[s+o]=i[4],e[s+o+1]=i[5],o+=t;const a=s/t;r[n++]=a,r[n++]=a+1,r[n++]=a+2,r[n++]=a+1,r[n++]=a+3,r[n++]=a+2}},Sg={extension:{type:A.ShapeBuilder,name:"triangle"},build(i,e){return e[0]=i.x,e[1]=i.y,e[2]=i.x2,e[3]=i.y2,e[4]=i.x3,e[5]=i.y3,!0},triangulate(i,e,t,s,r,n){let o=0;s*=t,e[s+o]=i[0],e[s+o+1]=i[1],o+=t,e[s+o]=i[2],e[s+o+1]=i[3],o+=t,e[s+o]=i[4],e[s+o+1]=i[5];const a=s/t;r[n++]=a,r[n++]=a+1,r[n++]=a+2}},yc=[{offset:0,color:"white"},{offset:1,color:"black"}],Gn=class ta{constructor(...e){this.uid=be("fillGradient"),this._tick=0,this.type="linear",this.colorStops=[];let t=Tg(e);t={...t.type==="radial"?ta.defaultRadialOptions:ta.defaultLinearOptions,...da(t)},this._textureSize=t.textureSize,this._wrapMode=t.wrapMode,t.type==="radial"?(this.center=t.center,this.outerCenter=t.outerCenter??this.center,this.innerRadius=t.innerRadius,this.outerRadius=t.outerRadius,this.scale=t.scale,this.rotation=t.rotation):(this.start=t.start,this.end=t.end),this.textureSpace=t.textureSpace,this.type=t.type,t.colorStops.forEach(r=>{this.addColorStop(r.offset,r.color)})}addColorStop(e,t){return this.colorStops.push({offset:e,color:Pe.shared.setValue(t).toHexa()}),this}buildLinearGradient(){if(this.texture)return;let{x:e,y:t}=this.start,{x:s,y:r}=this.end,n=s-e,o=r-t;const a=n<0||o<0;if(this._wrapMode==="clamp-to-edge"){if(n<0){const b=e;e=s,s=b,n*=-1}if(o<0){const b=t;t=r,r=b,o*=-1}}const l=this.colorStops.length?this.colorStops:yc,c=this._textureSize,{canvas:h,context:u}=vc(c,1),p=a?u.createLinearGradient(this._textureSize,0,0,0):u.createLinearGradient(0,0,this._textureSize,0);bc(p,l),u.fillStyle=p,u.fillRect(0,0,c,1),this.texture=new j({source:new $i({resource:h,addressMode:this._wrapMode})});const d=Math.sqrt(n*n+o*o),g=Math.atan2(o,n),_=new H;_.scale(d/c,1),_.rotate(g),_.translate(e,t),this.textureSpace==="local"&&_.scale(c,c),this.transform=_}buildGradient(){this.texture||this._tick++,this.type==="linear"?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){if(this.texture)return;const e=this.colorStops.length?this.colorStops:yc,t=this._textureSize,{canvas:s,context:r}=vc(t,t),{x:n,y:o}=this.center,{x:a,y:l}=this.outerCenter,c=this.innerRadius,h=this.outerRadius,u=a-h,p=l-h,d=t/(h*2),g=(n-u)*d,_=(o-p)*d,b=r.createRadialGradient(g,_,c*d,(a-u)*d,(l-p)*d,h*d);bc(b,e),r.fillStyle=e[e.length-1].color,r.fillRect(0,0,t,t),r.fillStyle=b,r.translate(g,_),r.rotate(this.rotation),r.scale(1,this.scale),r.translate(-g,-_),r.fillRect(0,0,t,t),this.texture=new j({source:new $i({resource:s,addressMode:this._wrapMode})});const v=new H;v.scale(1/d,1/d),v.translate(u,p),this.textureSpace==="local"&&v.scale(t,t),this.transform=v}destroy(){var e;(e=this.texture)==null||e.destroy(!0),this.texture=null,this.transform=null,this.colorStops=[],this.start=null,this.end=null,this.center=null,this.outerCenter=null}get styleKey(){return`fill-gradient-${this.uid}-${this._tick}`}};Gn.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:"local",type:"linear",textureSize:256,wrapMode:"clamp-to-edge"},Gn.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,textureSpace:"local",type:"radial",textureSize:256,wrapMode:"clamp-to-edge"};let As=Gn;function bc(i,e){for(let t=0;t<e.length;t++){const s=e[t];i.addColorStop(s.offset,s.color)}}function vc(i,e){const t=pe.get().createCanvas(i,e),s=t.getContext("2d");return{canvas:t,context:s}}function Tg(i){let e=i[0]??{};return(typeof e=="number"||i[1])&&(ee("8.5.2","use options object instead"),e={type:"linear",start:{x:i[0],y:i[1]},end:{x:i[2],y:i[3]},textureSpace:i[4],textureSize:i[5]??As.defaultLinearOptions.textureSize}),e}const Ag=new H,wg=new Ce;function xc(i,e,t,s){const r=e.matrix?i.copyFrom(e.matrix).invert():i.identity();if(e.textureSpace==="local"){const o=t.getBounds(wg);e.width&&o.pad(e.width);const{x:a,y:l}=o,c=1/o.width,h=1/o.height,u=-a*c,p=-l*h,d=r.a,g=r.b,_=r.c,b=r.d;r.a*=c,r.b*=c,r.c*=h,r.d*=h,r.tx=u*d+p*_+r.tx,r.ty=u*g+p*b+r.ty}else r.translate(e.texture.frame.x,e.texture.frame.y),r.scale(1/e.texture.source.width,1/e.texture.source.height);const n=e.texture.source.style;return!(e.fill instanceof As)&&n.addressMode==="clamp-to-edge"&&(n.addressMode="repeat",n.update()),s&&r.append(Ag.copyFrom(s).invert()),r}const ui={};Q.handleByMap(A.ShapeBuilder,ui),Q.add(Eg,Cg,Sg,hi,_g,yg);const Ig=new Ce,Rg=new H;function Mg(i,e){const{geometryData:t,batches:s}=e;s.length=0,t.indices.length=0,t.vertices.length=0,t.uvs.length=0;for(let r=0;r<i.instructions.length;r++){const n=i.instructions[r];if(n.action==="texture")Pg(n.data,s,t);else if(n.action==="fill"||n.action==="stroke"){const o=n.action==="stroke",a=n.data.path.shapePath,l=n.data.style,c=n.data.hole;o&&c&&Cc(c.shapePath,l,!0,s,t),c&&(a.shapePrimitives[a.shapePrimitives.length-1].holes=c.shapePath.shapePrimitives),Cc(a,l,o,s,t)}}}function Pg(i,e,t){const s=[],r=ui.rectangle,n=Ig;n.x=i.dx,n.y=i.dy,n.width=i.dw,n.height=i.dh;const o=i.transform;if(!r.build(n,s))return;const{vertices:a,uvs:l,indices:c}=t,h=c.length,u=a.length/2;o&&dc(s,o),r.triangulate(s,a,2,u,c,h);const p=i.image,d=p.uvs;l.push(d.x0,d.y0,d.x1,d.y1,d.x3,d.y3,d.x2,d.y2);const g=Le.get(Un);g.indexOffset=h,g.indexSize=c.length-h,g.attributeOffset=u,g.attributeSize=a.length/2-u,g.baseColor=i.style,g.alpha=i.alpha,g.texture=p,g.geometryData=t,e.push(g)}function Cc(i,e,t,s,r){const{vertices:n,uvs:o,indices:a}=r;i.shapePrimitives.forEach(({shape:l,transform:c,holes:h})=>{const u=[],p=ui[l.type];if(!p.build(l,u))return;const d=a.length,g=n.length/2;let _="triangle-list";if(c&&dc(u,c),t){const E=l.closePath??!0,S=e;S.pixelLine?(vg(u,E,n,a),_="line-list"):gc(u,S,!1,E,n,a)}else if(h){const E=[],S=u.slice();kg(h).forEach(R=>{E.push(S.length/2),S.push(...R)}),_c(S,E,n,2,g,a,d)}else p.triangulate(u,n,2,g,a,d);const b=o.length/2,v=e.texture;if(v!==j.WHITE){const E=xc(Rg,e,l,c);pg(n,2,g,o,b,2,n.length/2-g,E)}else mg(o,b,2,n.length/2-g);const C=Le.get(Un);C.indexOffset=d,C.indexSize=a.length-d,C.attributeOffset=g,C.attributeSize=n.length/2-g,C.baseColor=e.color,C.alpha=e.alpha,C.texture=v,C.geometryData=r,C.topology=_,s.push(C)})}function kg(i){const e=[];for(let t=0;t<i.length;t++){const s=i[t].shape,r=[];ui[s.type].build(s,r)&&e.push(r)}return e}class Og{constructor(){this.batches=[],this.geometryData={vertices:[],uvs:[],indices:[]}}reset(){this.batches&&this.batches.forEach(e=>{Le.return(e)}),this.graphicsData&&Le.return(this.graphicsData),this.isBatchable=!1,this.context=null,this.batches.length=0,this.geometryData.indices.length=0,this.geometryData.vertices.length=0,this.geometryData.uvs.length=0,this.graphicsData=null}destroy(){this.reset(),this.batches=null,this.geometryData=null}}class Bg{constructor(){this.instructions=new Zr}init(e){const t=e.maxTextures;this.batcher?this.batcher._updateMaxTextures(t):this.batcher=new Nn({maxTextures:t}),this.instructions.reset()}get geometry(){return ee(zf,"GraphicsContextRenderData#geometry is deprecated, please use batcher.geometry instead."),this.batcher.geometry}destroy(){this.batcher.destroy(),this.instructions.destroy(),this.batcher=null,this.instructions=null}}const Fn=class sa{constructor(e){this._renderer=e,this._managedContexts=new Rt({renderer:e,type:"resource",name:"graphicsContext"})}init(e){sa.defaultOptions.bezierSmoothness=(e==null?void 0:e.bezierSmoothness)??sa.defaultOptions.bezierSmoothness}getContextRenderData(e){return e._gpuData[this._renderer.uid].graphicsData||this._initContextRenderData(e)}updateGpuContext(e){const t=!!e._gpuData[this._renderer.uid],s=e._gpuData[this._renderer.uid]||this._initContext(e);if(e.dirty||!t){t&&s.reset(),Mg(e,s);const r=e.batchMode;e.customShader||r==="no-batch"?s.isBatchable=!1:r==="auto"?s.isBatchable=s.geometryData.vertices.length<400:s.isBatchable=!0,e.dirty=!1}return s}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){const t=Le.get(Bg,{maxTextures:this._renderer.limits.maxBatchableTextures}),s=e._gpuData[this._renderer.uid],{batches:r,geometryData:n}=s;s.graphicsData=t;const o=n.vertices.length,a=n.indices.length;for(let u=0;u<r.length;u++)r[u].applyTransform=!1;const l=t.batcher;l.ensureAttributeBuffer(o),l.ensureIndexBuffer(a),l.begin();for(let u=0;u<r.length;u++){const p=r[u];l.add(p)}l.finish(t.instructions);const c=l.geometry;c.indexBuffer.setDataWithSize(l.indexBuffer,l.indexSize,!0),c.buffers[0].setDataWithSize(l.attributeBuffer.float32View,l.attributeSize,!0);const h=l.batches;for(let u=0;u<h.length;u++){const p=h[u];p.bindGroup=An(p.textures.textures,p.textures.count,this._renderer.limits.maxBatchableTextures)}return t}_initContext(e){const t=new Og;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}};Fn.extension={type:[A.WebGLSystem,A.WebGPUSystem],name:"graphicsContext"},Fn.defaultOptions={bezierSmoothness:.5};let Ln=Fn;const Dg=8,sr=11920929e-14,Ng=1;function Ec(i,e,t,s,r,n,o,a,l,c){const u=Math.min(.99,Math.max(0,c??Ln.defaultOptions.bezierSmoothness));let p=(Ng-u)/1;return p*=p,Ug(e,t,s,r,n,o,a,l,i,p),i}function Ug(i,e,t,s,r,n,o,a,l,c){Wn(i,e,t,s,r,n,o,a,l,c,0),l.push(o,a)}function Wn(i,e,t,s,r,n,o,a,l,c,h){if(h>Dg)return;const u=(i+t)/2,p=(e+s)/2,d=(t+r)/2,g=(s+n)/2,_=(r+o)/2,b=(n+a)/2,v=(u+d)/2,C=(p+g)/2,E=(d+_)/2,S=(g+b)/2,w=(v+E)/2,R=(C+S)/2;if(h>0){let M=o-i,D=a-e;const G=Math.abs((t-o)*D-(s-a)*M),k=Math.abs((r-o)*D-(n-a)*M);if(G>sr&&k>sr){if((G+k)*(G+k)<=c*(M*M+D*D)){l.push(w,R);return}}else if(G>sr){if(G*G<=c*(M*M+D*D)){l.push(w,R);return}}else if(k>sr){if(k*k<=c*(M*M+D*D)){l.push(w,R);return}}else if(M=w-(i+o)/2,D=R-(e+a)/2,M*M+D*D<=c){l.push(w,R);return}}Wn(i,e,u,p,v,C,w,R,l,c,h+1),Wn(w,R,E,S,_,b,o,a,l,c,h+1)}const Gg=8,Fg=11920929e-14,Lg=1;function Wg(i,e,t,s,r,n,o,a){const c=Math.min(.99,Math.max(0,a??Ln.defaultOptions.bezierSmoothness));let h=(Lg-c)/1;return h*=h,Hg(e,t,s,r,n,o,i,h),i}function Hg(i,e,t,s,r,n,o,a){Hn(o,i,e,t,s,r,n,a,0),o.push(r,n)}function Hn(i,e,t,s,r,n,o,a,l){if(l>Gg)return;const c=(e+s)/2,h=(t+r)/2,u=(s+n)/2,p=(r+o)/2,d=(c+u)/2,g=(h+p)/2;let _=n-e,b=o-t;const v=Math.abs((s-n)*b-(r-o)*_);if(v>Fg){if(v*v<=a*(_*_+b*b)){i.push(d,g);return}}else if(_=d-(e+n)/2,b=g-(t+o)/2,_*_+b*b<=a){i.push(d,g);return}Hn(i,e,t,c,h,d,g,a,l+1),Hn(i,d,g,u,p,n,o,a,l+1)}function Sc(i,e,t,s,r,n,o,a){let l=Math.abs(r-n);(!o&&r>n||o&&n>r)&&(l=2*Math.PI-l),a||(a=Math.max(6,Math.floor(6*Math.pow(s,1/3)*(l/Math.PI)))),a=Math.max(a,3);let c=l/a,h=r;c*=o?-1:1;for(let u=0;u<a+1;u++){const p=Math.cos(h),d=Math.sin(h),g=e+p*s,_=t+d*s;i.push(g,_),h+=c}}function Vg(i,e,t,s,r,n){const o=i[i.length-2],l=i[i.length-1]-t,c=o-e,h=r-t,u=s-e,p=Math.abs(l*u-c*h);if(p<1e-8||n===0){(i[i.length-2]!==e||i[i.length-1]!==t)&&i.push(e,t);return}const d=l*l+c*c,g=h*h+u*u,_=l*h+c*u,b=n*Math.sqrt(d)/p,v=n*Math.sqrt(g)/p,C=b*_/d,E=v*_/g,S=b*u+v*c,w=b*h+v*l,R=c*(v+C),M=l*(v+C),D=u*(b+E),G=h*(b+E),k=Math.atan2(M-w,R-S),O=Math.atan2(G-w,D-S);Sc(i,S+e,w+t,n,k,O,c*h>u*l)}const di=Math.PI*2,Vn={centerX:0,centerY:0,ang1:0,ang2:0},zn=({x:i,y:e},t,s,r,n,o,a,l)=>{i*=t,e*=s;const c=r*i-n*e,h=n*i+r*e;return l.x=c+o,l.y=h+a,l};function zg(i,e){const t=e===-1.5707963267948966?-.551915024494:1.3333333333333333*Math.tan(e/4),s=e===1.5707963267948966?.551915024494:t,r=Math.cos(i),n=Math.sin(i),o=Math.cos(i+e),a=Math.sin(i+e);return[{x:r-n*s,y:n+r*s},{x:o+a*s,y:a-o*s},{x:o,y:a}]}const Tc=(i,e,t,s)=>{const r=i*s-e*t<0?-1:1;let n=i*t+e*s;return n>1&&(n=1),n<-1&&(n=-1),r*Math.acos(n)},$g=(i,e,t,s,r,n,o,a,l,c,h,u,p)=>{const d=Math.pow(r,2),g=Math.pow(n,2),_=Math.pow(h,2),b=Math.pow(u,2);let v=d*g-d*b-g*_;v<0&&(v=0),v/=d*b+g*_,v=Math.sqrt(v)*(o===a?-1:1);const C=v*r/n*u,E=v*-n/r*h,S=c*C-l*E+(i+t)/2,w=l*C+c*E+(e+s)/2,R=(h-C)/r,M=(u-E)/n,D=(-h-C)/r,G=(-u-E)/n,k=Tc(1,0,R,M);let O=Tc(R,M,D,G);a===0&&O>0&&(O-=di),a===1&&O<0&&(O+=di),p.centerX=S,p.centerY=w,p.ang1=k,p.ang2=O};function jg(i,e,t,s,r,n,o,a=0,l=0,c=0){if(n===0||o===0)return;const h=Math.sin(a*di/360),u=Math.cos(a*di/360),p=u*(e-s)/2+h*(t-r)/2,d=-h*(e-s)/2+u*(t-r)/2;if(p===0&&d===0)return;n=Math.abs(n),o=Math.abs(o);const g=Math.pow(p,2)/Math.pow(n,2)+Math.pow(d,2)/Math.pow(o,2);g>1&&(n*=Math.sqrt(g),o*=Math.sqrt(g)),$g(e,t,s,r,n,o,l,c,h,u,p,d,Vn);let{ang1:_,ang2:b}=Vn;const{centerX:v,centerY:C}=Vn;let E=Math.abs(b)/(di/4);Math.abs(1-E)<1e-7&&(E=1);const S=Math.max(Math.ceil(E),1);b/=S;let w=i[i.length-2],R=i[i.length-1];const M={x:0,y:0};for(let D=0;D<S;D++){const G=zg(_,b),{x:k,y:O}=zn(G[0],n,o,u,h,v,C,M),{x:V,y:X}=zn(G[1],n,o,u,h,v,C,M),{x:z,y:de}=zn(G[2],n,o,u,h,v,C,M);Ec(i,w,R,k,O,V,X,z,de),w=z,R=de,_+=b}}function Xg(i,e,t){const s=(o,a)=>{const l=a.x-o.x,c=a.y-o.y,h=Math.sqrt(l*l+c*c),u=l/h,p=c/h;return{len:h,nx:u,ny:p}},r=(o,a)=>{o===0?i.moveTo(a.x,a.y):i.lineTo(a.x,a.y)};let n=e[e.length-1];for(let o=0;o<e.length;o++){const a=e[o%e.length],l=a.radius??t;if(l<=0){r(o,a),n=a;continue}const c=e[(o+1)%e.length],h=s(a,n),u=s(a,c);if(h.len<1e-4||u.len<1e-4){r(o,a),n=a;continue}let p=Math.asin(h.nx*u.ny-h.ny*u.nx),d=1,g=!1;h.nx*u.nx-h.ny*-u.ny<0?p<0?p=Math.PI+p:(p=Math.PI-p,d=-1,g=!0):p>0&&(d=-1,g=!0);const _=p/2;let b,v=Math.abs(Math.cos(_)*l/Math.sin(_));v>Math.min(h.len/2,u.len/2)?(v=Math.min(h.len/2,u.len/2),b=Math.abs(v*Math.sin(_)/Math.cos(_))):b=l;const C=a.x+u.nx*v+-u.ny*b*d,E=a.y+u.ny*v+u.nx*b*d,S=Math.atan2(h.ny,h.nx)+Math.PI/2*d,w=Math.atan2(u.ny,u.nx)-Math.PI/2*d;o===0&&i.moveTo(C+Math.cos(S)*b,E+Math.sin(S)*b),i.arc(C,E,b,S,w,g),n=a}}function Yg(i,e,t,s){const r=(a,l)=>Math.sqrt((a.x-l.x)**2+(a.y-l.y)**2),n=(a,l,c)=>({x:a.x+(l.x-a.x)*c,y:a.y+(l.y-a.y)*c}),o=e.length;for(let a=0;a<o;a++){const l=e[(a+1)%o],c=l.radius??t;if(c<=0){a===0?i.moveTo(l.x,l.y):i.lineTo(l.x,l.y);continue}const h=e[a],u=e[(a+2)%o],p=r(h,l);let d;if(p<1e-4)d=l;else{const b=Math.min(p/2,c);d=n(l,h,b/p)}const g=r(u,l);let _;if(g<1e-4)_=l;else{const b=Math.min(g/2,c);_=n(l,u,b/g)}a===0?i.moveTo(d.x,d.y):i.lineTo(d.x,d.y),i.quadraticCurveTo(l.x,l.y,_.x,_.y,s)}}const qg=new Ce;class Kg{constructor(e){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new Ye,this._graphicsPath2D=e,this.signed=e.checkForHoles}moveTo(e,t){return this.startPoly(e,t),this}lineTo(e,t){this._ensurePoly();const s=this._currentPoly.points,r=s[s.length-2],n=s[s.length-1];return(r!==e||n!==t)&&s.push(e,t),this}arc(e,t,s,r,n,o){this._ensurePoly(!1);const a=this._currentPoly.points;return Sc(a,e,t,s,r,n,o),this}arcTo(e,t,s,r,n){this._ensurePoly();const o=this._currentPoly.points;return Vg(o,e,t,s,r,n),this}arcToSvg(e,t,s,r,n,o,a){const l=this._currentPoly.points;return jg(l,this._currentPoly.lastX,this._currentPoly.lastY,o,a,e,t,s,r,n),this}bezierCurveTo(e,t,s,r,n,o,a){this._ensurePoly();const l=this._currentPoly;return Ec(this._currentPoly.points,l.lastX,l.lastY,e,t,s,r,n,o,a),this}quadraticCurveTo(e,t,s,r,n){this._ensurePoly();const o=this._currentPoly;return Wg(this._currentPoly.points,o.lastX,o.lastY,e,t,s,r,n),this}closePath(){return this.endPoly(!0),this}addPath(e,t){this.endPoly(),t&&!t.isIdentity()&&(e=e.clone(!0),e.transform(t));const s=this.shapePrimitives,r=s.length;for(let n=0;n<e.instructions.length;n++){const o=e.instructions[n];this[o.action](...o.data)}if(e.checkForHoles&&s.length-r>1){let n=null;for(let o=r;o<s.length;o++){const a=s[o];if(a.shape.type==="polygon"){const l=a.shape,c=n==null?void 0:n.shape;c&&c.containsPolygon(l)?(n.holes||(n.holes=[]),n.holes.push(a),s.copyWithin(o,o+1),s.length--,o--):n=a}}}return this}finish(e=!1){this.endPoly(e)}rect(e,t,s,r,n){return this.drawShape(new Ce(e,t,s,r),n),this}circle(e,t,s,r){return this.drawShape(new En(e,t,s),r),this}poly(e,t,s){const r=new oi(e);return r.closePath=t,this.drawShape(r,s),this}regularPoly(e,t,s,r,n=0,o){r=Math.max(r|0,3);const a=-1*Math.PI/2+n,l=Math.PI*2/r,c=[];for(let h=0;h<r;h++){const u=a-h*l;c.push(e+s*Math.cos(u),t+s*Math.sin(u))}return this.poly(c,!0,o),this}roundPoly(e,t,s,r,n,o=0,a){if(r=Math.max(r|0,3),n<=0)return this.regularPoly(e,t,s,r,o);const l=s*Math.sin(Math.PI/r)-.001;n=Math.min(n,l);const c=-1*Math.PI/2+o,h=Math.PI*2/r,u=(r-2)*Math.PI/r/2;for(let p=0;p<r;p++){const d=p*h+c,g=e+s*Math.cos(d),_=t+s*Math.sin(d),b=d+Math.PI+u,v=d-Math.PI-u,C=g+n*Math.cos(b),E=_+n*Math.sin(b),S=g+n*Math.cos(v),w=_+n*Math.sin(v);p===0?this.moveTo(C,E):this.lineTo(C,E),this.quadraticCurveTo(g,_,S,w,a)}return this.closePath()}roundShape(e,t,s=!1,r){return e.length<3?this:(s?Yg(this,e,t,r):Xg(this,e,t),this.closePath())}filletRect(e,t,s,r,n){if(n===0)return this.rect(e,t,s,r);const o=Math.min(s,r)/2,a=Math.min(o,Math.max(-o,n)),l=e+s,c=t+r,h=a<0?-a:0,u=Math.abs(a);return this.moveTo(e,t+u).arcTo(e+h,t+h,e+u,t,u).lineTo(l-u,t).arcTo(l-h,t+h,l,t+u,u).lineTo(l,c-u).arcTo(l-h,c-h,e+s-u,c,u).lineTo(e+u,c).arcTo(e+h,c-h,e,c-u,u).closePath()}chamferRect(e,t,s,r,n,o){if(n<=0)return this.rect(e,t,s,r);const a=Math.min(n,Math.min(s,r)/2),l=e+s,c=t+r,h=[e+a,t,l-a,t,l,t+a,l,c-a,l-a,c,e+a,c,e,c-a,e,t+a];for(let u=h.length-1;u>=2;u-=2)h[u]===h[u-2]&&h[u-1]===h[u-3]&&h.splice(u-1,2);return this.poly(h,!0,o)}ellipse(e,t,s,r,n){return this.drawShape(new Sn(e,t,s,r),n),this}roundRect(e,t,s,r,n,o){return this.drawShape(new Tn(e,t,s,r,n),o),this}drawShape(e,t){return this.endPoly(),this.shapePrimitives.push({shape:e,transform:t}),this}startPoly(e,t){let s=this._currentPoly;return s&&this.endPoly(),s=new oi,s.points.push(e,t),this._currentPoly=s,this}endPoly(e=!1){const t=this._currentPoly;return t&&t.points.length>2&&(t.closePath=e,this.shapePrimitives.push({shape:t})),this._currentPoly=null,this}_ensurePoly(e=!0){if(!this._currentPoly&&(this._currentPoly=new oi,e)){const t=this.shapePrimitives[this.shapePrimitives.length-1];if(t){let s=t.shape.x,r=t.shape.y;if(t.transform&&!t.transform.isIdentity()){const n=t.transform,o=s;s=n.a*s+n.c*r+n.tx,r=n.b*o+n.d*r+n.ty}this._currentPoly.points.push(s,r)}else this._currentPoly.points.push(0,0)}}buildPath(){const e=this._graphicsPath2D;this.shapePrimitives.length=0,this._currentPoly=null;for(let t=0;t<e.instructions.length;t++){const s=e.instructions[t];this[s.action](...s.data)}this.finish()}get bounds(){const e=this._bounds;e.clear();const t=this.shapePrimitives;for(let s=0;s<t.length;s++){const r=t[s],n=r.shape.getBounds(qg);r.transform?e.addRect(n,r.transform):e.addRect(n)}return e}}class Mt{constructor(e,t=!1){this.instructions=[],this.uid=be("graphicsPath"),this._dirty=!0,this.checkForHoles=t,typeof e=="string"?Bm(e,this):this.instructions=(e==null?void 0:e.slice())??[]}get shapePath(){return this._shapePath||(this._shapePath=new Kg(this)),this._dirty&&(this._dirty=!1,this._shapePath.buildPath()),this._shapePath}addPath(e,t){return e=e.clone(),this.instructions.push({action:"addPath",data:[e,t]}),this._dirty=!0,this}arc(...e){return this.instructions.push({action:"arc",data:e}),this._dirty=!0,this}arcTo(...e){return this.instructions.push({action:"arcTo",data:e}),this._dirty=!0,this}arcToSvg(...e){return this.instructions.push({action:"arcToSvg",data:e}),this._dirty=!0,this}bezierCurveTo(...e){return this.instructions.push({action:"bezierCurveTo",data:e}),this._dirty=!0,this}bezierCurveToShort(e,t,s,r,n){const o=this.instructions[this.instructions.length-1],a=this.getLastPoint(ye.shared);let l=0,c=0;if(!o||o.action!=="bezierCurveTo")l=a.x,c=a.y;else{l=o.data[2],c=o.data[3];const h=a.x,u=a.y;l=h+(h-l),c=u+(u-c)}return this.instructions.push({action:"bezierCurveTo",data:[l,c,e,t,s,r,n]}),this._dirty=!0,this}closePath(){return this.instructions.push({action:"closePath",data:[]}),this._dirty=!0,this}ellipse(...e){return this.instructions.push({action:"ellipse",data:e}),this._dirty=!0,this}lineTo(...e){return this.instructions.push({action:"lineTo",data:e}),this._dirty=!0,this}moveTo(...e){return this.instructions.push({action:"moveTo",data:e}),this}quadraticCurveTo(...e){return this.instructions.push({action:"quadraticCurveTo",data:e}),this._dirty=!0,this}quadraticCurveToShort(e,t,s){const r=this.instructions[this.instructions.length-1],n=this.getLastPoint(ye.shared);let o=0,a=0;if(!r||r.action!=="quadraticCurveTo")o=n.x,a=n.y;else{o=r.data[0],a=r.data[1];const l=n.x,c=n.y;o=l+(l-o),a=c+(c-a)}return this.instructions.push({action:"quadraticCurveTo",data:[o,a,e,t,s]}),this._dirty=!0,this}rect(e,t,s,r,n){return this.instructions.push({action:"rect",data:[e,t,s,r,n]}),this._dirty=!0,this}circle(e,t,s,r){return this.instructions.push({action:"circle",data:[e,t,s,r]}),this._dirty=!0,this}roundRect(...e){return this.instructions.push({action:"roundRect",data:e}),this._dirty=!0,this}poly(...e){return this.instructions.push({action:"poly",data:e}),this._dirty=!0,this}regularPoly(...e){return this.instructions.push({action:"regularPoly",data:e}),this._dirty=!0,this}roundPoly(...e){return this.instructions.push({action:"roundPoly",data:e}),this._dirty=!0,this}roundShape(...e){return this.instructions.push({action:"roundShape",data:e}),this._dirty=!0,this}filletRect(...e){return this.instructions.push({action:"filletRect",data:e}),this._dirty=!0,this}chamferRect(...e){return this.instructions.push({action:"chamferRect",data:e}),this._dirty=!0,this}star(e,t,s,r,n,o,a){n||(n=r/2);const l=-1*Math.PI/2+o,c=s*2,h=Math.PI*2/c,u=[];for(let p=0;p<c;p++){const d=p%2?n:r,g=p*h+l;u.push(e+d*Math.cos(g),t+d*Math.sin(g))}return this.poly(u,!0,a),this}clone(e=!1){const t=new Mt;if(t.checkForHoles=this.checkForHoles,!e)t.instructions=this.instructions.slice();else for(let s=0;s<this.instructions.length;s++){const r=this.instructions[s];t.instructions.push({action:r.action,data:r.data.slice()})}return t}clear(){return this.instructions.length=0,this._dirty=!0,this}transform(e){if(e.isIdentity())return this;const t=e.a,s=e.b,r=e.c,n=e.d,o=e.tx,a=e.ty;let l=0,c=0,h=0,u=0,p=0,d=0,g=0,_=0;for(let b=0;b<this.instructions.length;b++){const v=this.instructions[b],C=v.data;switch(v.action){case"moveTo":case"lineTo":l=C[0],c=C[1],C[0]=t*l+r*c+o,C[1]=s*l+n*c+a;break;case"bezierCurveTo":h=C[0],u=C[1],p=C[2],d=C[3],l=C[4],c=C[5],C[0]=t*h+r*u+o,C[1]=s*h+n*u+a,C[2]=t*p+r*d+o,C[3]=s*p+n*d+a,C[4]=t*l+r*c+o,C[5]=s*l+n*c+a;break;case"quadraticCurveTo":h=C[0],u=C[1],l=C[2],c=C[3],C[0]=t*h+r*u+o,C[1]=s*h+n*u+a,C[2]=t*l+r*c+o,C[3]=s*l+n*c+a;break;case"arcToSvg":l=C[5],c=C[6],g=C[0],_=C[1],C[0]=t*g+r*_,C[1]=s*g+n*_,C[5]=t*l+r*c+o,C[6]=s*l+n*c+a;break;case"circle":C[4]=fi(C[3],e);break;case"rect":C[4]=fi(C[4],e);break;case"ellipse":C[8]=fi(C[8],e);break;case"roundRect":C[5]=fi(C[5],e);break;case"addPath":C[0].transform(e);break;case"poly":C[2]=fi(C[2],e);break;default:ie("unknown transform action",v.action);break}}return this._dirty=!0,this}get bounds(){return this.shapePath.bounds}getLastPoint(e){let t=this.instructions.length-1,s=this.instructions[t];if(!s)return e.x=0,e.y=0,e;for(;s.action==="closePath";){if(t--,t<0)return e.x=0,e.y=0,e;s=this.instructions[t]}switch(s.action){case"moveTo":case"lineTo":e.x=s.data[0],e.y=s.data[1];break;case"quadraticCurveTo":e.x=s.data[2],e.y=s.data[3];break;case"bezierCurveTo":e.x=s.data[4],e.y=s.data[5];break;case"arc":case"arcToSvg":e.x=s.data[5],e.y=s.data[6];break;case"addPath":s.data[0].getLastPoint(e);break}return e}}function fi(i,e){return i?i.prepend(e):e.clone()}function Ie(i,e,t){const s=i.getAttribute(e);return s?Number(s):t}function Zg(i,e){const t=i.querySelectorAll("defs");for(let s=0;s<t.length;s++){const r=t[s];for(let n=0;n<r.children.length;n++){const o=r.children[n];switch(o.nodeName.toLowerCase()){case"lineargradient":e.defs[o.id]=Jg(o);break;case"radialgradient":e.defs[o.id]=Qg();break}}}}function Jg(i){const e=Ie(i,"x1",0),t=Ie(i,"y1",0),s=Ie(i,"x2",1),r=Ie(i,"y2",0),n=i.getAttribute("gradientUnits")||"objectBoundingBox",o=new As(e,t,s,r,n==="objectBoundingBox"?"local":"global");for(let a=0;a<i.children.length;a++){const l=i.children[a],c=Ie(l,"offset",0),h=Pe.shared.setValue(l.getAttribute("stop-color")).toNumber();o.addColorStop(c,h)}return o}function Qg(i){return ie("[SVG Parser] Radial gradients are not yet supported"),new As(0,0,1,0)}function Ac(i){const e=i.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return e?e[1]:""}const wc={fill:{type:"paint",default:0},"fill-opacity":{type:"number",default:1},stroke:{type:"paint",default:0},"stroke-width":{type:"number",default:1},"stroke-opacity":{type:"number",default:1},"stroke-linecap":{type:"string",default:"butt"},"stroke-linejoin":{type:"string",default:"miter"},"stroke-miterlimit":{type:"number",default:10},"stroke-dasharray":{type:"string",default:"none"},"stroke-dashoffset":{type:"number",default:0},opacity:{type:"number",default:1}};function Ic(i,e){const t=i.getAttribute("style"),s={},r={},n={strokeStyle:s,fillStyle:r,useFill:!1,useStroke:!1};for(const o in wc){const a=i.getAttribute(o);a&&Rc(e,n,o,a.trim())}if(t){const o=t.split(";");for(let a=0;a<o.length;a++){const l=o[a].trim(),[c,h]=l.split(":");wc[c]&&Rc(e,n,c,h.trim())}}return{strokeStyle:n.useStroke?s:null,fillStyle:n.useFill?r:null,useFill:n.useFill,useStroke:n.useStroke}}function Rc(i,e,t,s){switch(t){case"stroke":if(s!=="none"){if(s.startsWith("url(")){const r=Ac(s);e.strokeStyle.fill=i.defs[r]}else e.strokeStyle.color=Pe.shared.setValue(s).toNumber();e.useStroke=!0}break;case"stroke-width":e.strokeStyle.width=Number(s);break;case"fill":if(s!=="none"){if(s.startsWith("url(")){const r=Ac(s);e.fillStyle.fill=i.defs[r]}else e.fillStyle.color=Pe.shared.setValue(s).toNumber();e.useFill=!0}break;case"fill-opacity":e.fillStyle.alpha=Number(s);break;case"stroke-opacity":e.strokeStyle.alpha=Number(s);break;case"opacity":e.fillStyle.alpha=Number(s),e.strokeStyle.alpha=Number(s);break}}function e_(i){if(i.length<=2)return!0;const e=i.map(a=>a.area).sort((a,l)=>l-a),[t,s]=e,r=e[e.length-1],n=t/s,o=s/r;return!(n>3&&o<2)}function t_(i){return i.split(/(?=[Mm])/).filter(s=>s.trim().length>0)}function s_(i){const e=i.match(/[-+]?[0-9]*\.?[0-9]+/g);if(!e||e.length<4)return 0;const t=e.map(Number),s=[],r=[];for(let h=0;h<t.length;h+=2)h+1<t.length&&(s.push(t[h]),r.push(t[h+1]));if(s.length===0||r.length===0)return 0;const n=Math.min(...s),o=Math.max(...s),a=Math.min(...r),l=Math.max(...r);return(o-n)*(l-a)}function Mc(i,e){const t=new Mt(i,!1);for(const s of t.instructions)e.instructions.push(s)}function i_(i,e){if(typeof i=="string"){const o=document.createElement("div");o.innerHTML=i.trim(),i=o.querySelector("svg")}const t={context:e,defs:{},path:new Mt};Zg(i,t);const s=i.children,{fillStyle:r,strokeStyle:n}=Ic(i,t);for(let o=0;o<s.length;o++){const a=s[o];a.nodeName.toLowerCase()!=="defs"&&Pc(a,t,r,n)}return e}function Pc(i,e,t,s){const r=i.children,{fillStyle:n,strokeStyle:o}=Ic(i,e);n&&t?t={...t,...n}:n&&(t=n),o&&s?s={...s,...o}:o&&(s=o);const a=!t&&!s;a&&(t={color:0});let l,c,h,u,p,d,g,_,b,v,C,E,S,w,R,M,D;switch(i.nodeName.toLowerCase()){case"path":{w=i.getAttribute("d");const G=i.getAttribute("fill-rule"),k=t_(w),O=G==="evenodd",V=k.length>1;if(O&&V){const z=k.map(B=>({path:B,area:s_(B)}));if(z.sort((B,U)=>U.area-B.area),k.length>3||!e_(z))for(let B=0;B<z.length;B++){const U=z[B],q=B===0;e.context.beginPath();const N=new Mt(void 0,!0);Mc(U.path,N),e.context.path(N),q?(t&&e.context.fill(t),s&&e.context.stroke(s)):e.context.cut()}else for(let B=0;B<z.length;B++){const U=z[B],q=B%2===1;e.context.beginPath();const N=new Mt(void 0,!0);Mc(U.path,N),e.context.path(N),q?e.context.cut():(t&&e.context.fill(t),s&&e.context.stroke(s))}}else{const z=G?G==="evenodd":!0;R=new Mt(w,z),e.context.path(R),t&&e.context.fill(t),s&&e.context.stroke(s)}break}case"circle":g=Ie(i,"cx",0),_=Ie(i,"cy",0),b=Ie(i,"r",0),e.context.ellipse(g,_,b,b),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"rect":l=Ie(i,"x",0),c=Ie(i,"y",0),M=Ie(i,"width",0),D=Ie(i,"height",0),v=Ie(i,"rx",0),C=Ie(i,"ry",0),v||C?e.context.roundRect(l,c,M,D,v||C):e.context.rect(l,c,M,D),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"ellipse":g=Ie(i,"cx",0),_=Ie(i,"cy",0),v=Ie(i,"rx",0),C=Ie(i,"ry",0),e.context.beginPath(),e.context.ellipse(g,_,v,C),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"line":h=Ie(i,"x1",0),u=Ie(i,"y1",0),p=Ie(i,"x2",0),d=Ie(i,"y2",0),e.context.beginPath(),e.context.moveTo(h,u),e.context.lineTo(p,d),s&&e.context.stroke(s);break;case"polygon":S=i.getAttribute("points"),E=S.match(/-?\d+/g).map(G=>parseInt(G,10)),e.context.poly(E,!0),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"polyline":S=i.getAttribute("points"),E=S.match(/-?\d+/g).map(G=>parseInt(G,10)),e.context.poly(E,!1),s&&e.context.stroke(s);break;case"g":case"svg":break;default:{ie(`[SVG parser] <${i.nodeName}> elements unsupported`);break}}a&&(t=null);for(let G=0;G<r.length;G++)Pc(r[G],e,t,s)}const kc={repeat:{addressModeU:"repeat",addressModeV:"repeat"},"repeat-x":{addressModeU:"repeat",addressModeV:"clamp-to-edge"},"repeat-y":{addressModeU:"clamp-to-edge",addressModeV:"repeat"},"no-repeat":{addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}};class Oc{constructor(e,t){this.uid=be("fillPattern"),this._tick=0,this.transform=new H,this.texture=e,this.transform.scale(1/e.frame.width,1/e.frame.height),t&&(e.source.style.addressModeU=kc[t].addressModeU,e.source.style.addressModeV=kc[t].addressModeV)}setTransform(e){const t=this.texture;this.transform.copyFrom(e),this.transform.invert(),this.transform.scale(1/t.frame.width,1/t.frame.height),this._tick++}get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._tick++)}get styleKey(){return`fill-pattern-${this.uid}-${this._tick}`}destroy(){this.texture.destroy(!0),this.texture=null}}function r_(i){return Pe.isColorLike(i)}function Bc(i){return i instanceof Oc}function Dc(i){return i instanceof As}function n_(i){return i instanceof j}function o_(i,e,t){const s=Pe.shared.setValue(e??0);return i.color=s.toNumber(),i.alpha=s.alpha===1?t.alpha:s.alpha,i.texture=j.WHITE,{...t,...i}}function a_(i,e,t){return i.texture=e,{...t,...i}}function Nc(i,e,t){return i.fill=e,i.color=16777215,i.texture=e.texture,i.matrix=e.transform,{...t,...i}}function Uc(i,e,t){return e.buildGradient(),i.fill=e,i.color=16777215,i.texture=e.texture,i.matrix=e.transform,i.textureSpace=e.textureSpace,{...t,...i}}function l_(i,e){const t={...e,...i},s=Pe.shared.setValue(t.color);return t.alpha*=s.alpha,t.color=s.toNumber(),t}function pi(i,e){if(i==null)return null;const t={},s=i;return r_(i)?o_(t,i,e):n_(i)?a_(t,i,e):Bc(i)?Nc(t,i,e):Dc(i)?Uc(t,i,e):s.fill&&Bc(s.fill)?Nc(s,s.fill,e):s.fill&&Dc(s.fill)?Uc(s,s.fill,e):l_(s,e)}function Gc(i,e){const{width:t,alignment:s,miterLimit:r,cap:n,join:o,pixelLine:a,...l}=e,c=pi(i,l);return c?{width:t,alignment:s,miterLimit:r,cap:n,join:o,pixelLine:a,...c}:null}function c_(i,e){let t=1;const s=i.shapePath.shapePrimitives;for(let r=0;r<s.length;r++){const n=s[r].shape;if(n.type!=="polygon")continue;const o=n.points,a=o.length;if(a<6)continue;const l=n.closePath;for(let c=0;c<a;c+=2){if(!l&&(c===0||c===a-2))continue;const h=(c-2+a)%a,u=(c+2)%a,p=o[h],d=o[h+1],g=o[c],_=o[c+1],b=o[u],v=o[u+1],C=p-g,E=d-_,S=b-g,w=v-_,R=C*C+E*E,M=S*S+w*w;if(R<1e-12||M<1e-12)continue;let k=(C*S+E*w)/Math.sqrt(R*M);k<-1?k=-1:k>1&&(k=1);const O=Math.sqrt((1-k)*.5);if(O<1e-6)continue;const V=Math.min(1/O,e);V>t&&(t=V)}}return t}const h_=new ye,Fc=new H,$n=class Et extends lt{constructor(){super(...arguments),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=be("graphicsContext"),this.dirty=!0,this.batchMode="auto",this.instructions=[],this.destroyed=!1,this._activePath=new Mt,this._transform=new H,this._fillStyle={...Et.defaultFillStyle},this._strokeStyle={...Et.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new Ye,this._boundsDirty=!0}clone(){const e=new Et;return e.batchMode=this.batchMode,e.instructions=this.instructions.slice(),e._activePath=this._activePath.clone(),e._transform=this._transform.clone(),e._fillStyle={...this._fillStyle},e._strokeStyle={...this._strokeStyle},e._stateStack=this._stateStack.slice(),e._bounds=this._bounds.clone(),e._boundsDirty=!0,e}get fillStyle(){return this._fillStyle}set fillStyle(e){this._fillStyle=pi(e,Et.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(e){this._strokeStyle=Gc(e,Et.defaultStrokeStyle)}setFillStyle(e){return this._fillStyle=pi(e,Et.defaultFillStyle),this}setStrokeStyle(e){return this._strokeStyle=pi(e,Et.defaultStrokeStyle),this}texture(e,t,s,r,n,o){return this.instructions.push({action:"texture",data:{image:e,dx:s||0,dy:r||0,dw:n||e.frame.width,dh:o||e.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:t||t===0?Pe.shared.setValue(t).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new Mt,this}fill(e,t){let s;const r=this.instructions[this.instructions.length-1];return this._tick===0&&(r==null?void 0:r.action)==="stroke"?s=r.data.path:s=this._activePath.clone(),s?(e!=null&&(t!==void 0&&typeof e=="number"&&(ee(Be,"GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead"),e={color:e,alpha:t}),this._fillStyle=pi(e,Et.defaultFillStyle)),this.instructions.push({action:"fill",data:{style:this.fillStyle,path:s}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}_initNextPathLocation(){const{x:e,y:t}=this._activePath.getLastPoint(ye.shared);this._activePath.clear(),this._activePath.moveTo(e,t)}stroke(e){let t;const s=this.instructions[this.instructions.length-1];return this._tick===0&&(s==null?void 0:s.action)==="fill"?t=s.data.path:t=this._activePath.clone(),t?(e!=null&&(this._strokeStyle=Gc(e,Et.defaultStrokeStyle)),this.instructions.push({action:"stroke",data:{style:this.strokeStyle,path:t}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}cut(){for(let e=0;e<2;e++){const t=this.instructions[this.instructions.length-1-e],s=this._activePath.clone();if(t&&(t.action==="stroke"||t.action==="fill"))if(t.data.hole)t.data.hole.addPath(s);else{t.data.hole=s;break}}return this._initNextPathLocation(),this}arc(e,t,s,r,n,o){this._tick++;const a=this._transform;return this._activePath.arc(a.a*e+a.c*t+a.tx,a.b*e+a.d*t+a.ty,s,r,n,o),this}arcTo(e,t,s,r,n){this._tick++;const o=this._transform;return this._activePath.arcTo(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,o.a*s+o.c*r+o.tx,o.b*s+o.d*r+o.ty,n),this}arcToSvg(e,t,s,r,n,o,a){this._tick++;const l=this._transform;return this._activePath.arcToSvg(e,t,s,r,n,l.a*o+l.c*a+l.tx,l.b*o+l.d*a+l.ty),this}bezierCurveTo(e,t,s,r,n,o,a){this._tick++;const l=this._transform;return this._activePath.bezierCurveTo(l.a*e+l.c*t+l.tx,l.b*e+l.d*t+l.ty,l.a*s+l.c*r+l.tx,l.b*s+l.d*r+l.ty,l.a*n+l.c*o+l.tx,l.b*n+l.d*o+l.ty,a),this}closePath(){var e;return this._tick++,(e=this._activePath)==null||e.closePath(),this}ellipse(e,t,s,r){return this._tick++,this._activePath.ellipse(e,t,s,r,this._transform.clone()),this}circle(e,t,s){return this._tick++,this._activePath.circle(e,t,s,this._transform.clone()),this}path(e){return this._tick++,this._activePath.addPath(e,this._transform.clone()),this}lineTo(e,t){this._tick++;const s=this._transform;return this._activePath.lineTo(s.a*e+s.c*t+s.tx,s.b*e+s.d*t+s.ty),this}moveTo(e,t){this._tick++;const s=this._transform,r=this._activePath.instructions,n=s.a*e+s.c*t+s.tx,o=s.b*e+s.d*t+s.ty;return r.length===1&&r[0].action==="moveTo"?(r[0].data[0]=n,r[0].data[1]=o,this):(this._activePath.moveTo(n,o),this)}quadraticCurveTo(e,t,s,r,n){this._tick++;const o=this._transform;return this._activePath.quadraticCurveTo(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,o.a*s+o.c*r+o.tx,o.b*s+o.d*r+o.ty,n),this}rect(e,t,s,r){return this._tick++,this._activePath.rect(e,t,s,r,this._transform.clone()),this}roundRect(e,t,s,r,n){return this._tick++,this._activePath.roundRect(e,t,s,r,n,this._transform.clone()),this}poly(e,t){return this._tick++,this._activePath.poly(e,t,this._transform.clone()),this}regularPoly(e,t,s,r,n=0,o){return this._tick++,this._activePath.regularPoly(e,t,s,r,n,o),this}roundPoly(e,t,s,r,n,o){return this._tick++,this._activePath.roundPoly(e,t,s,r,n,o),this}roundShape(e,t,s,r){return this._tick++,this._activePath.roundShape(e,t,s,r),this}filletRect(e,t,s,r,n){return this._tick++,this._activePath.filletRect(e,t,s,r,n),this}chamferRect(e,t,s,r,n,o){return this._tick++,this._activePath.chamferRect(e,t,s,r,n,o),this}star(e,t,s,r,n=0,o=0){return this._tick++,this._activePath.star(e,t,s,r,n,o,this._transform.clone()),this}svg(e){return this._tick++,i_(e,this),this}restore(){const e=this._stateStack.pop();return e&&(this._transform=e.transform,this._fillStyle=e.fillStyle,this._strokeStyle=e.strokeStyle),this}save(){return this._stateStack.push({transform:this._transform.clone(),fillStyle:{...this._fillStyle},strokeStyle:{...this._strokeStyle}}),this}getTransform(){return this._transform}resetTransform(){return this._transform.identity(),this}rotate(e){return this._transform.rotate(e),this}scale(e,t=e){return this._transform.scale(e,t),this}setTransform(e,t,s,r,n,o){return e instanceof H?(this._transform.set(e.a,e.b,e.c,e.d,e.tx,e.ty),this):(this._transform.set(e,t,s,r,n,o),this)}transform(e,t,s,r,n,o){return e instanceof H?(this._transform.append(e),this):(Fc.set(e,t,s,r,n,o),this._transform.append(Fc),this)}translate(e,t=e){return this._transform.translate(e,t),this}clear(){return this._activePath.clear(),this.instructions.length=0,this.resetTransform(),this.onUpdate(),this}onUpdate(){this._boundsDirty=!0,this.dirty=!0,this.emit("update",this,16)}get bounds(){if(!this._boundsDirty)return this._bounds;this._boundsDirty=!1;const e=this._bounds;e.clear();for(let t=0;t<this.instructions.length;t++){const s=this.instructions[t],r=s.action;if(r==="fill"){const n=s.data;e.addBounds(n.path.bounds)}else if(r==="texture"){const n=s.data;e.addFrame(n.dx,n.dy,n.dx+n.dw,n.dy+n.dh,n.transform)}if(r==="stroke"){const n=s.data,o=n.style.alignment;let a=n.style.width*(1-o);n.style.join==="miter"&&(a*=c_(n.path,n.style.miterLimit));const l=n.path.bounds;e.addFrame(l.minX-a,l.minY-a,l.maxX+a,l.maxY+a)}}return e.isValid||e.set(0,0,0,0),e}containsPoint(e){var r;if(!this.bounds.containsPoint(e.x,e.y))return!1;const t=this.instructions;let s=!1;for(let n=0;n<t.length;n++){const o=t[n],a=o.data,l=a.path;if(!o.action||!l)continue;const c=a.style,h=l.shapePath.shapePrimitives;for(let u=0;u<h.length;u++){const p=h[u].shape;if(!c||!p)continue;const d=h[u].transform,g=d?d.applyInverse(e,h_):e;if(o.action==="fill")s=p.contains(g.x,g.y);else{const b=c;s=p.strokeContains(g.x,g.y,b.width,b.alignment)}const _=a.hole;if(_){const b=(r=_.shapePath)==null?void 0:r.shapePrimitives;if(b)for(let v=0;v<b.length;v++)b[v].shape.contains(g.x,g.y)&&(s=!1)}if(s)return!0}}return s}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(e=!1){if(this.destroyed)return;if(this.destroyed=!0,this._stateStack.length=0,this._transform=null,this.unload(),this.emit("destroy",this),this.removeAllListeners(),typeof e=="boolean"?e:e==null?void 0:e.texture){const s=typeof e=="boolean"?e:e==null?void 0:e.textureSource;this._fillStyle.texture&&(this._fillStyle.fill&&"uid"in this._fillStyle.fill?this._fillStyle.fill.destroy():this._fillStyle.texture.destroy(s)),this._strokeStyle.texture&&(this._strokeStyle.fill&&"uid"in this._strokeStyle.fill?this._strokeStyle.fill.destroy():this._strokeStyle.texture.destroy(s))}this._fillStyle=null,this._strokeStyle=null,this.instructions=null,this._activePath=null,this._bounds=null,this._stateStack=null,this.customShader=null,this._transform=null}};$n.defaultFillStyle={color:16777215,alpha:1,texture:j.WHITE,matrix:null,fill:null,textureSpace:"local"},$n.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:"butt",join:"miter",texture:j.WHITE,matrix:null,fill:null,textureSpace:"local",pixelLine:!1};let mi=$n;class Lc{constructor(e){this._attachedDomElements=[],this._renderer=e,this._renderer.runners.postrender.add(this),this._renderer.runners.init.add(this),this._domElement=document.createElement("div"),this._domElement.style.position="absolute",this._domElement.style.top="0",this._domElement.style.left="0",this._domElement.style.pointerEvents="none",this._domElement.style.zIndex="1000"}init(){this._canvasObserver=new Qa({domElement:this._domElement,renderer:this._renderer})}addRenderable(e,t){this._attachedDomElements.includes(e)||this._attachedDomElements.push(e)}updateRenderable(e){}validateRenderable(e){return!0}postrender(){const e=this._attachedDomElements;if(e.length===0){this._domElement.remove();return}this._canvasObserver.ensureAttached();for(let t=0;t<e.length;t++){const s=e[t],r=s.element;if(!s.parent||s.globalDisplayStatus<7)r==null||r.remove(),e.splice(t,1),t--;else{this._domElement.contains(r)||(r.style.position="absolute",r.style.pointerEvents="auto",this._domElement.appendChild(r));const n=s.worldTransform,o=s._anchor,a=s.width*o.x,l=s.height*o.y;r.style.transformOrigin=`${a}px ${l}px`,r.style.transform=`matrix(${n.a}, ${n.b}, ${n.c}, ${n.d}, ${n.tx-a}, ${n.ty-l})`,r.style.opacity=s.groupAlpha.toString()}}}destroy(){var e;this._renderer.runners.postrender.remove(this);for(let t=0;t<this._attachedDomElements.length;t++)(e=this._attachedDomElements[t].element)==null||e.remove();this._attachedDomElements.length=0,this._domElement.remove(),this._canvasObserver.destroy(),this._renderer=null}}Lc.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"dom"};class u_{constructor(){this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}init(e){this.removeTickerListener(),this.events=e,this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}get pauseUpdate(){return this._pauseUpdate}set pauseUpdate(e){this._pauseUpdate=e}addTickerListener(){this._tickerAdded||!this.domElement||(at.system.add(this._tickerUpdate,this,ys.INTERACTION),this._tickerAdded=!0)}removeTickerListener(){this._tickerAdded&&(at.system.remove(this._tickerUpdate,this),this._tickerAdded=!1)}pointerMoved(){this._didMove=!0}_update(){if(!this.domElement||this._pauseUpdate)return;if(this._didMove){this._didMove=!1;return}const e=this.events._rootPointerEvent;this.events.supportsTouchEvents&&e.pointerType==="touch"||globalThis.document.dispatchEvent(this.events.supportsPointerEvents?new PointerEvent("pointermove",{clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,pointerId:e.pointerId}):new MouseEvent("mousemove",{clientX:e.clientX,clientY:e.clientY}))}_tickerUpdate(e){this._deltaTime+=e.deltaTime,!(this._deltaTime<this.interactionFrequency)&&(this._deltaTime=0,this._update())}destroy(){this.removeTickerListener(),this.events=null,this.domElement=null,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}}const Pt=new u_;class ir extends qs{constructor(){super(...arguments),this.client=new ye,this.movement=new ye,this.offset=new ye,this.global=new ye,this.screen=new ye}get clientX(){return this.client.x}get clientY(){return this.client.y}get x(){return this.clientX}get y(){return this.clientY}get movementX(){return this.movement.x}get movementY(){return this.movement.y}get offsetX(){return this.offset.x}get offsetY(){return this.offset.y}get globalX(){return this.global.x}get globalY(){return this.global.y}get screenX(){return this.screen.x}get screenY(){return this.screen.y}getLocalPosition(e,t,s){return e.worldTransform.applyInverse(s||this.global,t)}getModifierState(e){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(e)}initMouseEvent(e,t,s,r,n,o,a,l,c,h,u,p,d,g,_){throw new Error("Method not implemented.")}}class ht extends ir{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1}getCoalescedEvents(){return this.type==="pointermove"||this.type==="mousemove"||this.type==="touchmove"?[this]:[]}getPredictedEvents(){throw new Error("getPredictedEvents is not supported!")}}class ws extends ir{constructor(){super(...arguments),this.DOM_DELTA_PIXEL=0,this.DOM_DELTA_LINE=1,this.DOM_DELTA_PAGE=2}}ws.DOM_DELTA_PIXEL=0,ws.DOM_DELTA_LINE=1,ws.DOM_DELTA_PAGE=2;const d_=2048,f_=new ye,gi=new ye;class p_{constructor(e){this.dispatch=new lt,this.moveOnAll=!1,this.enableGlobalMoveEvents=!0,this.mappingState={trackingData:{}},this.eventPool=new Map,this._allInteractiveElements=[],this._hitElements=[],this._isPointerMoveEvent=!1,this.rootTarget=e,this.hitPruneFn=this.hitPruneFn.bind(this),this.hitTestFn=this.hitTestFn.bind(this),this.mapPointerDown=this.mapPointerDown.bind(this),this.mapPointerMove=this.mapPointerMove.bind(this),this.mapPointerOut=this.mapPointerOut.bind(this),this.mapPointerOver=this.mapPointerOver.bind(this),this.mapPointerUp=this.mapPointerUp.bind(this),this.mapPointerUpOutside=this.mapPointerUpOutside.bind(this),this.mapWheel=this.mapWheel.bind(this),this.mappingTable={},this.addEventMapping("pointerdown",this.mapPointerDown),this.addEventMapping("pointermove",this.mapPointerMove),this.addEventMapping("pointerout",this.mapPointerOut),this.addEventMapping("pointerleave",this.mapPointerOut),this.addEventMapping("pointerover",this.mapPointerOver),this.addEventMapping("pointerup",this.mapPointerUp),this.addEventMapping("pointerupoutside",this.mapPointerUpOutside),this.addEventMapping("wheel",this.mapWheel)}addEventMapping(e,t){this.mappingTable[e]||(this.mappingTable[e]=[]),this.mappingTable[e].push({fn:t,priority:0}),this.mappingTable[e].sort((s,r)=>s.priority-r.priority)}dispatchEvent(e,t){e.propagationStopped=!1,e.propagationImmediatelyStopped=!1,this.propagate(e,t),this.dispatch.emit(t||e.type,e)}mapEvent(e){if(!this.rootTarget)return;const t=this.mappingTable[e.type];if(t)for(let s=0,r=t.length;s<r;s++)t[s].fn(e);else ie(`[EventBoundary]: Event mapping not defined for ${e.type}`)}hitTest(e,t){Pt.pauseUpdate=!0;const r=this._isPointerMoveEvent&&this.enableGlobalMoveEvents?"hitTestMoveRecursive":"hitTestRecursive",n=this[r](this.rootTarget,this.rootTarget.eventMode,f_.set(e,t),this.hitTestFn,this.hitPruneFn);return n&&n[0]}propagate(e,t){if(!e.target)return;const s=e.composedPath();e.eventPhase=e.CAPTURING_PHASE;for(let r=0,n=s.length-1;r<n;r++)if(e.currentTarget=s[r],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return;if(e.eventPhase=e.AT_TARGET,e.currentTarget=e.target,this.notifyTarget(e,t),!(e.propagationStopped||e.propagationImmediatelyStopped)){e.eventPhase=e.BUBBLING_PHASE;for(let r=s.length-2;r>=0;r--)if(e.currentTarget=s[r],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return}}all(e,t,s=this._allInteractiveElements){if(s.length===0)return;e.eventPhase=e.BUBBLING_PHASE;const r=Array.isArray(t)?t:[t];for(let n=s.length-1;n>=0;n--)r.forEach(o=>{e.currentTarget=s[n],this.notifyTarget(e,o)})}propagationPath(e){const t=[e];for(let s=0;s<d_&&e!==this.rootTarget&&e.parent;s++){if(!e.parent)throw new Error("Cannot find propagation path to disconnected target");t.push(e.parent),e=e.parent}return t.reverse(),t}hitTestMoveRecursive(e,t,s,r,n,o=!1){let a=!1;if(this._interactivePrune(e))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(Pt.pauseUpdate=!1),e.interactiveChildren&&e.children){const h=e.children;for(let u=h.length-1;u>=0;u--){const p=h[u],d=this.hitTestMoveRecursive(p,this._isInteractive(t)?t:p.eventMode,s,r,n,o||n(e,s));if(d){if(d.length>0&&!d[d.length-1].parent)continue;const g=e.isInteractive();(d.length>0||g)&&(g&&this._allInteractiveElements.push(e),d.push(e)),this._hitElements.length===0&&(this._hitElements=d),a=!0}}}const l=this._isInteractive(t),c=e.isInteractive();return c&&c&&this._allInteractiveElements.push(e),o||this._hitElements.length>0?null:a?this._hitElements:l&&!n(e,s)&&r(e,s)?c?[e]:[]:null}hitTestRecursive(e,t,s,r,n){if(this._interactivePrune(e)||n(e,s))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(Pt.pauseUpdate=!1),e.interactiveChildren&&e.children){const l=e.children,c=s;for(let h=l.length-1;h>=0;h--){const u=l[h],p=this.hitTestRecursive(u,this._isInteractive(t)?t:u.eventMode,c,r,n);if(p){if(p.length>0&&!p[p.length-1].parent)continue;const d=e.isInteractive();return(p.length>0||d)&&p.push(e),p}}}const o=this._isInteractive(t),a=e.isInteractive();return o&&r(e,s)?a?[e]:[]:null}_isInteractive(e){return e==="static"||e==="dynamic"}_interactivePrune(e){return!e||!e.visible||!e.renderable||!e.measurable||e.eventMode==="none"||e.eventMode==="passive"&&!e.interactiveChildren}hitPruneFn(e,t){if(e.hitArea&&(e.worldTransform.applyInverse(t,gi),!e.hitArea.contains(gi.x,gi.y)))return!0;if(e.effects&&e.effects.length)for(let s=0;s<e.effects.length;s++){const r=e.effects[s];if(r.containsPoint&&!r.containsPoint(t,this.hitTestFn))return!0}return!1}hitTestFn(e,t){return e.hitArea?!0:e!=null&&e.containsPoint?(e.worldTransform.applyInverse(t,gi),e.containsPoint(gi)):!1}notifyTarget(e,t){var n,o;if(!e.currentTarget.isInteractive())return;t??(t=e.type);const s=`on${t}`;(o=(n=e.currentTarget)[s])==null||o.call(n,e);const r=e.eventPhase===e.CAPTURING_PHASE||e.eventPhase===e.AT_TARGET?`${t}capture`:t;this._notifyListeners(e,r),e.eventPhase===e.AT_TARGET&&this._notifyListeners(e,t)}mapPointerDown(e){if(!(e instanceof ht)){ie("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.createPointerEvent(e);if(this.dispatchEvent(t,"pointerdown"),t.pointerType==="touch")this.dispatchEvent(t,"touchstart");else if(t.pointerType==="mouse"||t.pointerType==="pen"){const r=t.button===2;this.dispatchEvent(t,r?"rightdown":"mousedown")}const s=this.trackingData(e.pointerId);s.pressTargetsByButton[e.button]=t.composedPath(),this.freeEvent(t)}mapPointerMove(e){var l,c;if(!(e instanceof ht)){ie("EventBoundary cannot map a non-pointer event as a pointer event");return}this._allInteractiveElements.length=0,this._hitElements.length=0,this._isPointerMoveEvent=!0;const t=this.createPointerEvent(e);this._isPointerMoveEvent=!1;const s=t.pointerType==="mouse"||t.pointerType==="pen",r=this.trackingData(e.pointerId),n=this.findMountedTarget(r.overTargets);if(((l=r.overTargets)==null?void 0:l.length)>0&&n!==t.target){const h=e.type==="mousemove"?"mouseout":"pointerout",u=this.createPointerEvent(e,h,n);if(this.dispatchEvent(u,"pointerout"),s&&this.dispatchEvent(u,"mouseout"),!t.composedPath().includes(n)){const p=this.createPointerEvent(e,"pointerleave",n);for(p.eventPhase=p.AT_TARGET;p.target&&!t.composedPath().includes(p.target);)p.currentTarget=p.target,this.notifyTarget(p),s&&this.notifyTarget(p,"mouseleave"),p.target=p.target.parent;this.freeEvent(p)}this.freeEvent(u)}if(n!==t.target){const h=e.type==="mousemove"?"mouseover":"pointerover",u=this.clonePointerEvent(t,h);this.dispatchEvent(u,"pointerover"),s&&this.dispatchEvent(u,"mouseover");let p=n==null?void 0:n.parent;for(;p&&p!==this.rootTarget.parent&&p!==t.target;)p=p.parent;if(!p||p===this.rootTarget.parent){const g=this.clonePointerEvent(t,"pointerenter");for(g.eventPhase=g.AT_TARGET;g.target&&g.target!==n&&g.target!==this.rootTarget.parent;)g.currentTarget=g.target,this.notifyTarget(g),s&&this.notifyTarget(g,"mouseenter"),g.target=g.target.parent;this.freeEvent(g)}this.freeEvent(u)}const o=[],a=this.enableGlobalMoveEvents??!0;this.moveOnAll?o.push("pointermove"):this.dispatchEvent(t,"pointermove"),a&&o.push("globalpointermove"),t.pointerType==="touch"&&(this.moveOnAll?o.splice(1,0,"touchmove"):this.dispatchEvent(t,"touchmove"),a&&o.push("globaltouchmove")),s&&(this.moveOnAll?o.splice(1,0,"mousemove"):this.dispatchEvent(t,"mousemove"),a&&o.push("globalmousemove"),this.cursor=(c=t.target)==null?void 0:c.cursor),o.length>0&&this.all(t,o),this._allInteractiveElements.length=0,this._hitElements.length=0,r.overTargets=t.composedPath(),this.freeEvent(t)}mapPointerOver(e){var o;if(!(e instanceof ht)){ie("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),s=this.createPointerEvent(e),r=s.pointerType==="mouse"||s.pointerType==="pen";this.dispatchEvent(s,"pointerover"),r&&this.dispatchEvent(s,"mouseover"),s.pointerType==="mouse"&&(this.cursor=(o=s.target)==null?void 0:o.cursor);const n=this.clonePointerEvent(s,"pointerenter");for(n.eventPhase=n.AT_TARGET;n.target&&n.target!==this.rootTarget.parent;)n.currentTarget=n.target,this.notifyTarget(n),r&&this.notifyTarget(n,"mouseenter"),n.target=n.target.parent;t.overTargets=s.composedPath(),this.freeEvent(s),this.freeEvent(n)}mapPointerOut(e){if(!(e instanceof ht)){ie("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId);if(t.overTargets){const s=e.pointerType==="mouse"||e.pointerType==="pen",r=this.findMountedTarget(t.overTargets),n=this.createPointerEvent(e,"pointerout",r);this.dispatchEvent(n),s&&this.dispatchEvent(n,"mouseout");const o=this.createPointerEvent(e,"pointerleave",r);for(o.eventPhase=o.AT_TARGET;o.target&&o.target!==this.rootTarget.parent;)o.currentTarget=o.target,this.notifyTarget(o),s&&this.notifyTarget(o,"mouseleave"),o.target=o.target.parent;t.overTargets=null,this.freeEvent(n),this.freeEvent(o)}this.cursor=null}mapPointerUp(e){if(!(e instanceof ht)){ie("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=performance.now(),s=this.createPointerEvent(e);if(this.dispatchEvent(s,"pointerup"),s.pointerType==="touch")this.dispatchEvent(s,"touchend");else if(s.pointerType==="mouse"||s.pointerType==="pen"){const a=s.button===2;this.dispatchEvent(s,a?"rightup":"mouseup")}const r=this.trackingData(e.pointerId),n=this.findMountedTarget(r.pressTargetsByButton[e.button]);let o=n;if(n&&!s.composedPath().includes(n)){let a=n;for(;a&&!s.composedPath().includes(a);){if(s.currentTarget=a,this.notifyTarget(s,"pointerupoutside"),s.pointerType==="touch")this.notifyTarget(s,"touchendoutside");else if(s.pointerType==="mouse"||s.pointerType==="pen"){const l=s.button===2;this.notifyTarget(s,l?"rightupoutside":"mouseupoutside")}a=a.parent}delete r.pressTargetsByButton[e.button],o=a}if(o){const a=this.clonePointerEvent(s,"click");a.target=o,a.path=null,r.clicksByButton[e.button]||(r.clicksByButton[e.button]={clickCount:0,target:a.target,timeStamp:t});const l=r.clicksByButton[e.button];if(l.target===a.target&&t-l.timeStamp<200?++l.clickCount:l.clickCount=1,l.target=a.target,l.timeStamp=t,a.detail=l.clickCount,a.pointerType==="mouse"){const c=a.button===2;this.dispatchEvent(a,c?"rightclick":"click")}else a.pointerType==="touch"&&this.dispatchEvent(a,"tap");this.dispatchEvent(a,"pointertap"),this.freeEvent(a)}this.freeEvent(s)}mapPointerUpOutside(e){if(!(e instanceof ht)){ie("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),s=this.findMountedTarget(t.pressTargetsByButton[e.button]),r=this.createPointerEvent(e);if(s){let n=s;for(;n;)r.currentTarget=n,this.notifyTarget(r,"pointerupoutside"),r.pointerType==="touch"?this.notifyTarget(r,"touchendoutside"):(r.pointerType==="mouse"||r.pointerType==="pen")&&this.notifyTarget(r,r.button===2?"rightupoutside":"mouseupoutside"),n=n.parent;delete t.pressTargetsByButton[e.button]}this.freeEvent(r)}mapWheel(e){if(!(e instanceof ws)){ie("EventBoundary cannot map a non-wheel event as a wheel event");return}const t=this.createWheelEvent(e);this.dispatchEvent(t),this.freeEvent(t)}findMountedTarget(e){if(!e)return null;let t=e[0];for(let s=1;s<e.length&&e[s].parent===t;s++)t=e[s];return t}createPointerEvent(e,t,s){const r=this.allocateEvent(ht);return this.copyPointerData(e,r),this.copyMouseData(e,r),this.copyData(e,r),r.nativeEvent=e.nativeEvent,r.originalEvent=e,r.target=s??this.hitTest(r.global.x,r.global.y)??this._hitElements[0],typeof t=="string"&&(r.type=t),r}createWheelEvent(e){const t=this.allocateEvent(ws);return this.copyWheelData(e,t),this.copyMouseData(e,t),this.copyData(e,t),t.nativeEvent=e.nativeEvent,t.originalEvent=e,t.target=this.hitTest(t.global.x,t.global.y),t}clonePointerEvent(e,t){const s=this.allocateEvent(ht);return s.nativeEvent=e.nativeEvent,s.originalEvent=e.originalEvent,this.copyPointerData(e,s),this.copyMouseData(e,s),this.copyData(e,s),s.target=e.target,s.path=e.composedPath().slice(),s.type=t??s.type,s}copyWheelData(e,t){t.deltaMode=e.deltaMode,t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ}copyPointerData(e,t){e instanceof ht&&t instanceof ht&&(t.pointerId=e.pointerId,t.width=e.width,t.height=e.height,t.isPrimary=e.isPrimary,t.pointerType=e.pointerType,t.pressure=e.pressure,t.tangentialPressure=e.tangentialPressure,t.tiltX=e.tiltX,t.tiltY=e.tiltY,t.twist=e.twist)}copyMouseData(e,t){e instanceof ir&&t instanceof ir&&(t.altKey=e.altKey,t.button=e.button,t.buttons=e.buttons,t.client.copyFrom(e.client),t.ctrlKey=e.ctrlKey,t.metaKey=e.metaKey,t.movement.copyFrom(e.movement),t.screen.copyFrom(e.screen),t.shiftKey=e.shiftKey,t.global.copyFrom(e.global))}copyData(e,t){t.isTrusted=e.isTrusted,t.srcElement=e.srcElement,t.timeStamp=performance.now(),t.type=e.type,t.detail=e.detail,t.view=e.view,t.which=e.which,t.layer.copyFrom(e.layer),t.page.copyFrom(e.page)}trackingData(e){return this.mappingState.trackingData[e]||(this.mappingState.trackingData[e]={pressTargetsByButton:{},clicksByButton:{},overTarget:null}),this.mappingState.trackingData[e]}allocateEvent(e){this.eventPool.has(e)||this.eventPool.set(e,[]);const t=this.eventPool.get(e).pop()||new e(this);return t.eventPhase=t.NONE,t.currentTarget=null,t.defaultPrevented=!1,t.path=null,t.target=null,t}freeEvent(e){if(e.manager!==this)throw new Error("It is illegal to free an event not managed by this EventBoundary!");const t=e.constructor;this.eventPool.has(t)||this.eventPool.set(t,[]),this.eventPool.get(t).push(e)}_notifyListeners(e,t){const s=e.currentTarget._events[t];if(s)if("fn"in s)s.once&&e.currentTarget.removeListener(t,s.fn,void 0,!0),s.fn.call(s.context,e);else for(let r=0,n=s.length;r<n&&!e.propagationImmediatelyStopped;r++)s[r].once&&e.currentTarget.removeListener(t,s[r].fn,void 0,!0),s[r].fn.call(s[r].context,e)}}const m_=1,g_={touchstart:"pointerdown",touchend:"pointerup",touchendoutside:"pointerupoutside",touchmove:"pointermove",touchcancel:"pointercancel"},jn=class ia{constructor(e){this.supportsTouchEvents="ontouchstart"in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=e,this.rootBoundary=new p_(null),Pt.init(this),this.autoPreventDefault=!0,this._eventsAdded=!1,this._rootPointerEvent=new ht(null),this._rootWheelEvent=new ws(null),this.cursorStyles={default:"inherit",pointer:"pointer"},this.features=new Proxy({...ia.defaultEventFeatures},{set:(t,s,r)=>(s==="globalMove"&&(this.rootBoundary.enableGlobalMoveEvents=r),t[s]=r,!0)}),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onPointerOverOut=this._onPointerOverOut.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(e){const{canvas:t,resolution:s}=this.renderer;this.setTargetElement(t),this.resolution=s,ia._defaultEventMode=e.eventMode??"passive",Object.assign(this.features,e.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(e){this.resolution=e}destroy(){Pt.destroy(),this.setTargetElement(null),this.renderer=null,this._currentCursor=null}setCursor(e){e||(e="default");let t=!0;if(globalThis.OffscreenCanvas&&this.domElement instanceof OffscreenCanvas&&(t=!1),this._currentCursor===e)return;this._currentCursor=e;const s=this.cursorStyles[e];if(s)switch(typeof s){case"string":t&&(this.domElement.style.cursor=s);break;case"function":s(e);break;case"object":t&&Object.assign(this.domElement.style,s);break}else t&&typeof e=="string"&&!Object.prototype.hasOwnProperty.call(this.cursorStyles,e)&&(this.domElement.style.cursor=e)}get pointer(){return this._rootPointerEvent}_onPointerDown(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const t=this._normalizeToPointerData(e);this.autoPreventDefault&&t[0].isNormalized&&(e.cancelable||!("cancelable"in e))&&e.preventDefault();for(let s=0,r=t.length;s<r;s++){const n=t[s],o=this._bootstrapEvent(this._rootPointerEvent,n);this.rootBoundary.mapEvent(o)}this.setCursor(this.rootBoundary.cursor)}_onPointerMove(e){if(!this.features.move)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,Pt.pointerMoved();const t=this._normalizeToPointerData(e);for(let s=0,r=t.length;s<r;s++){const n=this._bootstrapEvent(this._rootPointerEvent,t[s]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}_onPointerUp(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let t=e.target;e.composedPath&&e.composedPath().length>0&&(t=e.composedPath()[0]);const s=t!==this.domElement?"outside":"",r=this._normalizeToPointerData(e);for(let n=0,o=r.length;n<o;n++){const a=this._bootstrapEvent(this._rootPointerEvent,r[n]);a.type+=s,this.rootBoundary.mapEvent(a)}this.setCursor(this.rootBoundary.cursor)}_onPointerOverOut(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const t=this._normalizeToPointerData(e);for(let s=0,r=t.length;s<r;s++){const n=this._bootstrapEvent(this._rootPointerEvent,t[s]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}onWheel(e){if(!this.features.wheel)return;const t=this.normalizeWheelEvent(e);this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,this.rootBoundary.mapEvent(t)}setTargetElement(e){this._removeEvents(),this.domElement=e,Pt.domElement=e,this._addEvents()}_addEvents(){if(this._eventsAdded||!this.domElement)return;Pt.addTickerListener();const e=this.domElement.style;e&&(globalThis.navigator.msPointerEnabled?(e.msContentZooming="none",e.msTouchAction="none"):this.supportsPointerEvents&&(e.touchAction="none")),this.supportsPointerEvents?(globalThis.document.addEventListener("pointermove",this._onPointerMove,!0),this.domElement.addEventListener("pointerdown",this._onPointerDown,!0),this.domElement.addEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.addEventListener("pointerover",this._onPointerOverOut,!0),globalThis.addEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.addEventListener("mousemove",this._onPointerMove,!0),this.domElement.addEventListener("mousedown",this._onPointerDown,!0),this.domElement.addEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.addEventListener("mouseover",this._onPointerOverOut,!0),globalThis.addEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.addEventListener("touchstart",this._onPointerDown,!0),this.domElement.addEventListener("touchend",this._onPointerUp,!0),this.domElement.addEventListener("touchmove",this._onPointerMove,!0))),this.domElement.addEventListener("wheel",this.onWheel,{passive:!0,capture:!0}),this._eventsAdded=!0}_removeEvents(){if(!this._eventsAdded||!this.domElement)return;Pt.removeTickerListener();const e=this.domElement.style;e&&(globalThis.navigator.msPointerEnabled?(e.msContentZooming="",e.msTouchAction=""):this.supportsPointerEvents&&(e.touchAction="")),this.supportsPointerEvents?(globalThis.document.removeEventListener("pointermove",this._onPointerMove,!0),this.domElement.removeEventListener("pointerdown",this._onPointerDown,!0),this.domElement.removeEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.removeEventListener("pointerover",this._onPointerOverOut,!0),globalThis.removeEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.removeEventListener("mousemove",this._onPointerMove,!0),this.domElement.removeEventListener("mousedown",this._onPointerDown,!0),this.domElement.removeEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.removeEventListener("mouseover",this._onPointerOverOut,!0),globalThis.removeEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.removeEventListener("touchstart",this._onPointerDown,!0),this.domElement.removeEventListener("touchend",this._onPointerUp,!0),this.domElement.removeEventListener("touchmove",this._onPointerMove,!0))),this.domElement.removeEventListener("wheel",this.onWheel,!0),this.domElement=null,this._eventsAdded=!1}mapPositionToPoint(e,t,s){const r=this.domElement.isConnected?this.domElement.getBoundingClientRect():{width:this.domElement.width,height:this.domElement.height,left:0,top:0},n=1/this.resolution;e.x=(t-r.left)*(this.domElement.width/r.width)*n,e.y=(s-r.top)*(this.domElement.height/r.height)*n}_normalizeToPointerData(e){const t=[];if(this.supportsTouchEvents&&e instanceof TouchEvent)for(let s=0,r=e.changedTouches.length;s<r;s++){const n=e.changedTouches[s];typeof n.button>"u"&&(n.button=0),typeof n.buttons>"u"&&(n.buttons=1),typeof n.isPrimary>"u"&&(n.isPrimary=e.touches.length===1&&e.type==="touchstart"),typeof n.width>"u"&&(n.width=n.radiusX||1),typeof n.height>"u"&&(n.height=n.radiusY||1),typeof n.tiltX>"u"&&(n.tiltX=0),typeof n.tiltY>"u"&&(n.tiltY=0),typeof n.pointerType>"u"&&(n.pointerType="touch"),typeof n.pointerId>"u"&&(n.pointerId=n.identifier||0),typeof n.pressure>"u"&&(n.pressure=n.force||.5),typeof n.twist>"u"&&(n.twist=0),typeof n.tangentialPressure>"u"&&(n.tangentialPressure=0),typeof n.layerX>"u"&&(n.layerX=n.offsetX=n.clientX),typeof n.layerY>"u"&&(n.layerY=n.offsetY=n.clientY),n.isNormalized=!0,n.type=e.type,n.altKey??(n.altKey=e.altKey),n.ctrlKey??(n.ctrlKey=e.ctrlKey),n.metaKey??(n.metaKey=e.metaKey),n.shiftKey??(n.shiftKey=e.shiftKey),t.push(n)}else if(!globalThis.MouseEvent||e instanceof MouseEvent&&(!this.supportsPointerEvents||!(e instanceof globalThis.PointerEvent))){const s=e;typeof s.isPrimary>"u"&&(s.isPrimary=!0),typeof s.width>"u"&&(s.width=1),typeof s.height>"u"&&(s.height=1),typeof s.tiltX>"u"&&(s.tiltX=0),typeof s.tiltY>"u"&&(s.tiltY=0),typeof s.pointerType>"u"&&(s.pointerType="mouse"),typeof s.pointerId>"u"&&(s.pointerId=m_),typeof s.pressure>"u"&&(s.pressure=.5),typeof s.twist>"u"&&(s.twist=0),typeof s.tangentialPressure>"u"&&(s.tangentialPressure=0),s.isNormalized=!0,t.push(s)}else t.push(e);return t}normalizeWheelEvent(e){const t=this._rootWheelEvent;return this._transferMouseData(t,e),t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ,t.deltaMode=e.deltaMode,this.mapPositionToPoint(t.screen,e.clientX,e.clientY),t.global.copyFrom(t.screen),t.offset.copyFrom(t.screen),t.nativeEvent=e,t.type=e.type,t}_bootstrapEvent(e,t){return e.originalEvent=null,e.nativeEvent=t,e.pointerId=t.pointerId,e.width=t.width,e.height=t.height,e.isPrimary=t.isPrimary,e.pointerType=t.pointerType,e.pressure=t.pressure,e.tangentialPressure=t.tangentialPressure,e.tiltX=t.tiltX,e.tiltY=t.tiltY,e.twist=t.twist,this._transferMouseData(e,t),this.mapPositionToPoint(e.screen,t.clientX,t.clientY),e.global.copyFrom(e.screen),e.offset.copyFrom(e.screen),e.isTrusted=t.isTrusted,e.type==="pointerleave"&&(e.type="pointerout"),e.type.startsWith("mouse")&&(e.type=e.type.replace("mouse","pointer")),e.type.startsWith("touch")&&(e.type=g_[e.type]||e.type),e}_transferMouseData(e,t){e.isTrusted=t.isTrusted,e.srcElement=t.srcElement,e.timeStamp=performance.now(),e.type=t.type,e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.client.x=t.clientX,e.client.y=t.clientY,e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.movement.x=t.movementX,e.movement.y=t.movementY,e.page.x=t.pageX,e.page.y=t.pageY,e.relatedTarget=null,e.shiftKey=t.shiftKey}};jn.extension={name:"events",type:[A.WebGLSystem,A.CanvasSystem,A.WebGPUSystem],priority:-1},jn.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0};let Wc=jn;const __={onclick:null,onmousedown:null,onmouseenter:null,onmouseleave:null,onmousemove:null,onglobalmousemove:null,onmouseout:null,onmouseover:null,onmouseup:null,onmouseupoutside:null,onpointercancel:null,onpointerdown:null,onpointerenter:null,onpointerleave:null,onpointermove:null,onglobalpointermove:null,onpointerout:null,onpointerover:null,onpointertap:null,onpointerup:null,onpointerupoutside:null,onrightclick:null,onrightdown:null,onrightup:null,onrightupoutside:null,ontap:null,ontouchcancel:null,ontouchend:null,ontouchendoutside:null,ontouchmove:null,onglobaltouchmove:null,ontouchstart:null,onwheel:null,get interactive(){return this.eventMode==="dynamic"||this.eventMode==="static"},set interactive(i){this.eventMode=i?"static":"passive"},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??Wc.defaultEventMode},set eventMode(i){this._internalEventMode=i},isInteractive(){return this.eventMode==="static"||this.eventMode==="dynamic"},interactiveChildren:!0,hitArea:null,addEventListener(i,e,t){const s=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,r=typeof t=="object"?t.signal:void 0,n=typeof t=="object"?t.once===!0:!1,o=typeof e=="function"?void 0:e;i=s?`${i}capture`:i;const a=typeof e=="function"?e:e.handleEvent,l=this;r&&r.addEventListener("abort",()=>{l.off(i,a,o)}),n?l.once(i,a,o):l.on(i,a,o)},removeEventListener(i,e,t){const s=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,r=typeof e=="function"?void 0:e;i=s?`${i}capture`:i,e=typeof e=="function"?e:e.handleEvent,this.off(i,e,r)},dispatchEvent(i){if(!(i instanceof qs))throw new Error("Container cannot propagate events outside of the Federated Events API");return i.defaultPrevented=!1,i.path=null,i.target=this,i.manager.dispatchEvent(i),!i.defaultPrevented}};var y_=`in vec2 aPosition;
|
|
252
252
|
out vec2 vTextureCoord;
|
|
253
253
|
|
|
254
254
|
uniform vec4 uInputSize;
|
|
@@ -275,7 +275,7 @@ void main(void)
|
|
|
275
275
|
gl_Position = filterVertexPosition();
|
|
276
276
|
vTextureCoord = filterTextureCoord();
|
|
277
277
|
}
|
|
278
|
-
`,
|
|
278
|
+
`,b_=`in vec2 vTextureCoord;
|
|
279
279
|
out vec4 finalColor;
|
|
280
280
|
uniform sampler2D uTexture;
|
|
281
281
|
void main() {
|
|
@@ -330,7 +330,7 @@ fn mainFragment(
|
|
|
330
330
|
) -> @location(0) vec4<f32> {
|
|
331
331
|
return textureSample(uTexture, uSampler, uv);
|
|
332
332
|
}
|
|
333
|
-
`;class
|
|
333
|
+
`;class v_ extends Sl{constructor(){const e=is.from({vertex:{source:Hc,entryPoint:"mainVertex"},fragment:{source:Hc,entryPoint:"mainFragment"},name:"passthrough-filter"}),t=Es.from({vertex:y_,fragment:b_,name:"passthrough-filter"});super({gpuProgram:e,glProgram:t})}}class Vc{constructor(e){this._renderer=e}push(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"filter",canBundle:!1,action:"pushFilter",container:t,filterEffect:e})}pop(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}execute(e){e.action==="pushFilter"?this._renderer.filter.push(e):e.action==="popFilter"&&this._renderer.filter.pop()}destroy(){this._renderer=null}}Vc.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"filter"};const zc=new H;function x_(i,e){e.clear();const t=e.matrix;for(let s=0;s<i.length;s++){const r=i[s];if(r.globalDisplayStatus<7)continue;const n=r.renderGroup??r.parentRenderGroup;n!=null&&n.isCachedAsTexture?e.matrix=zc.copyFrom(n.textureOffsetInverseTransform).append(r.worldTransform):n!=null&&n._parentCacheAsTextureRenderGroup?e.matrix=zc.copyFrom(n._parentCacheAsTextureRenderGroup.inverseWorldTransform).append(r.groupTransform):e.matrix=r.worldTransform,e.addBounds(r.bounds)}return e.matrix=t,e}const C_=new In({attributes:{aPosition:{buffer:new Float32Array([0,0,1,0,1,1,0,1]),format:"float32x2",stride:8,offset:0}},indexBuffer:new Uint32Array([0,1,2,0,2,3])});class E_{constructor(){this.skip=!1,this.inputTexture=null,this.backTexture=null,this.filters=null,this.bounds=new Ye,this.container=null,this.blendRequired=!1,this.outputRenderSurface=null,this.globalFrame={x:0,y:0,width:0,height:0},this.firstEnabledIndex=-1,this.lastEnabledIndex=-1}}class $c{constructor(e){this._filterStackIndex=0,this._filterStack=[],this._filterGlobalUniforms=new gt({uInputSize:{value:new Float32Array(4),type:"vec4<f32>"},uInputPixel:{value:new Float32Array(4),type:"vec4<f32>"},uInputClamp:{value:new Float32Array(4),type:"vec4<f32>"},uOutputFrame:{value:new Float32Array(4),type:"vec4<f32>"},uGlobalFrame:{value:new Float32Array(4),type:"vec4<f32>"},uOutputTexture:{value:new Float32Array(4),type:"vec4<f32>"}}),this._globalFilterBindGroup=new Nt({}),this.renderer=e}get activeBackTexture(){var e;return(e=this._activeFilterData)==null?void 0:e.backTexture}push(e){const t=this.renderer,s=e.filterEffect.filters,r=this._pushFilterData();r.skip=!1,r.filters=s,r.container=e.container,r.outputRenderSurface=t.renderTarget.renderSurface;const n=t.renderTarget.renderTarget.colorTexture.source,o=n.resolution,a=n.antialias;if(s.every(d=>!d.enabled)){r.skip=!0;return}const l=r.bounds;if(this._calculateFilterArea(e,l),this._calculateFilterBounds(r,t.renderTarget.rootViewPort,a,o,1),r.skip)return;const c=this._getPreviousFilterData(),h=this._findFilterResolution(o);let u=0,p=0;c&&(u=c.bounds.minX,p=c.bounds.minY),this._calculateGlobalFrame(r,u,p,h,n.width,n.height),this._setupFilterTextures(r,l,t,c)}generateFilteredTexture({texture:e,filters:t}){const s=this._pushFilterData();this._activeFilterData=s,s.skip=!1,s.filters=t;const r=e.source,n=r.resolution,o=r.antialias;if(t.every(d=>!d.enabled))return s.skip=!0,e;const a=s.bounds;if(a.addRect(e.frame),this._calculateFilterBounds(s,a.rectangle,o,n,0),s.skip)return e;const l=n;this._calculateGlobalFrame(s,0,0,l,r.width,r.height),s.outputRenderSurface=Qe.getOptimalTexture(a.width,a.height,s.resolution,s.antialias),s.backTexture=j.EMPTY,s.inputTexture=e,this.renderer.renderTarget.finishRenderPass(),this._applyFiltersToTexture(s,!0);const p=s.outputRenderSurface;return p.source.alphaMode="premultiplied-alpha",p}pop(){const e=this.renderer,t=this._popFilterData();t.skip||(e.globalUniforms.pop(),e.renderTarget.finishRenderPass(),this._activeFilterData=t,this._applyFiltersToTexture(t,!1),t.blendRequired&&Qe.returnTexture(t.backTexture),Qe.returnTexture(t.inputTexture))}getBackTexture(e,t,s){const r=e.colorTexture.source._resolution,n=Qe.getOptimalTexture(t.width,t.height,r,!1);let o=t.minX,a=t.minY;s&&(o-=s.minX,a-=s.minY),o=Math.floor(o*r),a=Math.floor(a*r);const l=Math.ceil(t.width*r),c=Math.ceil(t.height*r);return this.renderer.renderTarget.copyToTexture(e,n,{x:o,y:a},{width:l,height:c},{x:0,y:0}),n}applyFilter(e,t,s,r){const n=this.renderer,o=this._activeFilterData,l=o.outputRenderSurface===s,c=n.renderTarget.rootRenderTarget.colorTexture.source._resolution,h=this._findFilterResolution(c);let u=0,p=0;if(l){const g=this._findPreviousFilterOffset();u=g.x,p=g.y}this._updateFilterUniforms(t,s,o,u,p,h,l,r);const d=e.enabled?e:this._getPassthroughFilter();this._setupBindGroupsAndRender(d,t,n)}calculateSpriteMatrix(e,t){const s=this._activeFilterData,r=e.set(s.inputTexture._source.width,0,0,s.inputTexture._source.height,s.bounds.minX,s.bounds.minY),n=t.worldTransform.copyTo(H.shared),o=t.renderGroup||t.parentRenderGroup;return o&&o.cacheToLocalTransform&&n.prepend(o.cacheToLocalTransform),n.invert(),r.prepend(n),r.scale(1/t.texture.orig.width,1/t.texture.orig.height),r.translate(t.anchor.x,t.anchor.y),r}destroy(){var e;(e=this._passthroughFilter)==null||e.destroy(!0),this._passthroughFilter=null}_getPassthroughFilter(){return this._passthroughFilter??(this._passthroughFilter=new v_),this._passthroughFilter}_setupBindGroupsAndRender(e,t,s){if(s.renderPipes.uniformBatch){const r=s.renderPipes.uniformBatch.getUboResource(this._filterGlobalUniforms);this._globalFilterBindGroup.setResource(r,0)}else this._globalFilterBindGroup.setResource(this._filterGlobalUniforms,0);this._globalFilterBindGroup.setResource(t.source,1),this._globalFilterBindGroup.setResource(t.source.style,2),e.groups[0]=this._globalFilterBindGroup,s.encoder.draw({geometry:C_,shader:e,state:e._state,topology:"triangle-list"}),s.type===_t.WEBGL&&s.renderTarget.finishRenderPass()}_setupFilterTextures(e,t,s,r){if(e.backTexture=j.EMPTY,e.inputTexture=Qe.getOptimalTexture(t.width,t.height,e.resolution,e.antialias),e.blendRequired){s.renderTarget.finishRenderPass();const n=s.renderTarget.getRenderTarget(e.outputRenderSurface);e.backTexture=this.getBackTexture(n,t,r==null?void 0:r.bounds)}s.renderTarget.bind(e.inputTexture,!0),s.globalUniforms.push({offset:t})}_calculateGlobalFrame(e,t,s,r,n,o){const a=e.globalFrame;a.x=t*r,a.y=s*r,a.width=n*r,a.height=o*r}_updateFilterUniforms(e,t,s,r,n,o,a,l){const c=this._filterGlobalUniforms.uniforms,h=c.uOutputFrame,u=c.uInputSize,p=c.uInputPixel,d=c.uInputClamp,g=c.uGlobalFrame,_=c.uOutputTexture;a?(h[0]=s.bounds.minX-r,h[1]=s.bounds.minY-n):(h[0]=0,h[1]=0),h[2]=e.frame.width,h[3]=e.frame.height,u[0]=e.source.width,u[1]=e.source.height,u[2]=1/u[0],u[3]=1/u[1],p[0]=e.source.pixelWidth,p[1]=e.source.pixelHeight,p[2]=1/p[0],p[3]=1/p[1],d[0]=.5*p[2],d[1]=.5*p[3],d[2]=e.frame.width*u[2]-.5*p[2],d[3]=e.frame.height*u[3]-.5*p[3];const b=this.renderer.renderTarget.rootRenderTarget.colorTexture;g[0]=r*o,g[1]=n*o,g[2]=b.source.width*o,g[3]=b.source.height*o,t instanceof j&&(t.source.resource=null);const v=this.renderer.renderTarget.getRenderTarget(t);this.renderer.renderTarget.bind(t,!!l),t instanceof j?(_[0]=t.frame.width,_[1]=t.frame.height):(_[0]=v.width,_[1]=v.height),_[2]=v.isRoot?-1:1,this._filterGlobalUniforms.update()}_findFilterResolution(e){let t=this._filterStackIndex-1;for(;t>0&&this._filterStack[t].skip;)--t;return t>0&&this._filterStack[t].inputTexture?this._filterStack[t].inputTexture.source._resolution:e}_findPreviousFilterOffset(){let e=0,t=0,s=this._filterStackIndex;for(;s>0;){s--;const r=this._filterStack[s];if(!r.skip){e=r.bounds.minX,t=r.bounds.minY;break}}return{x:e,y:t}}_calculateFilterArea(e,t){if(e.renderables?x_(e.renderables,t):e.filterEffect.filterArea?(t.clear(),t.addRect(e.filterEffect.filterArea),t.applyMatrix(e.container.worldTransform)):e.container.getFastGlobalBounds(!0,t),e.container){const r=(e.container.renderGroup||e.container.parentRenderGroup).cacheToLocalTransform;r&&t.applyMatrix(r)}}_applyFiltersToTexture(e,t){const s=e.inputTexture,r=e.bounds,n=e.filters,o=e.firstEnabledIndex,a=e.lastEnabledIndex;if(this._globalFilterBindGroup.setResource(s.source.style,2),this._globalFilterBindGroup.setResource(e.backTexture.source,3),o===a)n[o].apply(this,s,e.outputRenderSurface,t);else{let l=e.inputTexture;const c=Qe.getOptimalTexture(r.width,r.height,l.source._resolution,!1);let h=c;for(let u=o;u<a;u++){const p=n[u];if(!p.enabled)continue;p.apply(this,l,h,!0);const d=l;l=h,h=d}n[a].apply(this,l,e.outputRenderSurface,t),Qe.returnTexture(c)}}_calculateFilterBounds(e,t,s,r,n){var v;const o=this.renderer,a=e.bounds,l=e.filters;let c=1/0,h=0,u=!0,p=!1,d=!1,g=!0,_=-1,b=-1;for(let C=0;C<l.length;C++){const E=l[C];if(!E.enabled)continue;if(_===-1&&(_=C),b=C,c=Math.min(c,E.resolution==="inherit"?r:E.resolution),h+=E.padding,E.antialias==="off"?u=!1:E.antialias==="inherit"&&u&&(u=s),E.clipToViewport||(g=!1),!!!(E.compatibleRenderers&o.type)){d=!1;break}if(E.blendRequired&&!(((v=o.backBuffer)==null?void 0:v.useBackBuffer)??!0)){ie("Blend filter requires backBuffer on WebGL renderer to be enabled. Set `useBackBuffer: true` in the renderer options."),d=!1;break}d=!0,p||(p=E.blendRequired)}if(!d){e.skip=!0;return}if(g&&a.fitBounds(0,t.width/r,0,t.height/r),a.scale(c).ceil().scale(1/c).pad((h|0)*n),!a.isPositive){e.skip=!0;return}e.antialias=u,e.resolution=c,e.blendRequired=p,e.firstEnabledIndex=_,e.lastEnabledIndex=b}_popFilterData(){return this._filterStackIndex--,this._filterStack[this._filterStackIndex]}_getPreviousFilterData(){let e,t=this._filterStackIndex-1;for(;t>0&&(t--,e=this._filterStack[t],!!e.skip););return e}_pushFilterData(){let e=this._filterStack[this._filterStackIndex];return e||(e=this._filterStack[this._filterStackIndex]=new E_),this._filterStackIndex++,e}}$c.extension={type:[A.WebGLSystem,A.WebGPUSystem],name:"filter"};var S_=`in vec2 vMaskCoord;
|
|
334
334
|
in vec2 vTextureCoord;
|
|
335
335
|
|
|
336
336
|
uniform sampler2D uTexture;
|
|
@@ -364,7 +364,7 @@ void main(void)
|
|
|
364
364
|
|
|
365
365
|
finalColor = original * a;
|
|
366
366
|
}
|
|
367
|
-
`,
|
|
367
|
+
`,T_=`in vec2 aPosition;
|
|
368
368
|
|
|
369
369
|
out vec2 vTextureCoord;
|
|
370
370
|
out vec2 vMaskCoord;
|
|
@@ -499,7 +499,7 @@ fn mainFragment(
|
|
|
499
499
|
|
|
500
500
|
return source * a;
|
|
501
501
|
}
|
|
502
|
-
`;class T_ extends Sl{constructor(e){const{sprite:t,...s}=e,r=new _a(t.texture),n=new gt({uFilterMatrix:{value:new H,type:"mat3x3<f32>"},uMaskClamp:{value:r.uClampFrame,type:"vec4<f32>"},uAlpha:{value:1,type:"f32"},uInverse:{value:e.inverse?1:0,type:"f32"}}),o=is.from({vertex:{source:jc,entryPoint:"mainVertex"},fragment:{source:jc,entryPoint:"mainFragment"}}),a=Es.from({vertex:S_,fragment:E_,name:"mask-filter"});super({...s,gpuProgram:o,glProgram:a,clipToViewport:!1,resources:{filterUniforms:n,uMaskTexture:t.texture.source}}),this.sprite=t,this._textureMatrix=r}set inverse(e){this.resources.filterUniforms.uniforms.uInverse=e?1:0}get inverse(){return this.resources.filterUniforms.uniforms.uInverse===1}apply(e,t,s,r){this._textureMatrix.texture=this.sprite.texture,e.calculateSpriteMatrix(this.resources.filterUniforms.uniforms.uFilterMatrix,this.sprite).prepend(this._textureMatrix.mapCoord),this.resources.uMaskTexture=this.sprite.texture.source,e.applyFilter(this,t,s,r)}}class A_{constructor(){this.isBatchable=!1}reset(){this.isBatchable=!1,this.context=null,this.graphicsData&&(this.graphicsData.destroy(),this.graphicsData=null)}destroy(){this.reset()}}class w_{constructor(){this.instructions=new Zr}init(){this.instructions.reset()}destroy(){this.instructions.destroy(),this.instructions=null}}const Xn=class ra{constructor(e){this._renderer=e,this._managedContexts=new Rt({renderer:e,type:"resource",name:"graphicsContext"})}init(e){ra.defaultOptions.bezierSmoothness=(e==null?void 0:e.bezierSmoothness)??ra.defaultOptions.bezierSmoothness}getContextRenderData(e){return this.getGpuContext(e).graphicsData||this._initContextRenderData(e)}updateGpuContext(e){const t=e._gpuData,s=!!t[this._renderer.uid],r=t[this._renderer.uid]||this._initContext(e);return(e.dirty||!s)&&(s&&r.reset(),r.isBatchable=!1,e.dirty=!1),r}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){const t=new w_,s=this.getGpuContext(e);return s.graphicsData=t,t.init(),t}_initContext(e){const t=new A_;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}};Xn.extension={type:[A.CanvasSystem],name:"graphicsContext"},Xn.defaultOptions={bezierSmoothness:.5};let I_=Xn;class Xc{constructor(e,t){this.state=It.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new Rt({renderer:e,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){return!1}addRenderable(e,t){this._managedGraphics.add(e),this.renderer.renderPipes.batch.break(t),t.add(e)}updateRenderable(e){}execute(e){e.isRenderable&&this._adaptor.execute(this,e)}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null}}Xc.extension={type:[A.CanvasPipes],name:"graphics"};function Yc(i,e,t){const s=(i>>24&255)/255;e[t++]=(i&255)/255*s,e[t++]=(i>>8&255)/255*s,e[t++]=(i>>16&255)/255*s,e[t++]=s}class R_{constructor(){this.batches=[],this.batched=!1}destroy(){this.batches.forEach(e=>{Le.return(e)}),this.batches.length=0}}class qc{constructor(e,t){this.state=It.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new Rt({renderer:e,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){const t=e.context,s=!!e._gpuData,n=this.renderer.graphicsContext.updateGpuContext(t);return!!(n.isBatchable||s!==n.isBatchable)}addRenderable(e,t){const r=this.renderer.graphicsContext.updateGpuContext(e.context);e.didViewUpdate&&this._rebuild(e),r.isBatchable?this._addToBatcher(e,t):(this.renderer.renderPipes.batch.break(t),t.add(e))}updateRenderable(e){const s=this._getGpuDataForRenderable(e).batches;for(let r=0;r<s.length;r++){const n=s[r];n._batcher.updateElement(n)}}execute(e){if(!e.isRenderable)return;const t=this.renderer,s=e.context;if(!t.graphicsContext.getGpuContext(s).batches.length)return;const n=s.customShader||this._adaptor.shader;this.state.blendMode=e.groupBlendMode;const o=n.resources.localUniforms.uniforms;o.uTransformMatrix=e.groupTransform,o.uRound=t._roundPixels|e._roundPixels,Yc(e.groupColorAlpha,o.uColor,0),this._adaptor.execute(this,e)}_rebuild(e){const t=this._getGpuDataForRenderable(e),r=this.renderer.graphicsContext.updateGpuContext(e.context);t.destroy(),r.isBatchable&&this._updateBatchesForRenderable(e,t)}_addToBatcher(e,t){const s=this.renderer.renderPipes.batch,r=this._getGpuDataForRenderable(e).batches;for(let n=0;n<r.length;n++){const o=r[n];s.addToBatch(o,t)}}_getGpuDataForRenderable(e){return e._gpuData[this.renderer.uid]||this._initGpuDataForRenderable(e)}_initGpuDataForRenderable(e){const t=new R_;return e._gpuData[this.renderer.uid]=t,this._managedGraphics.add(e),t}_updateBatchesForRenderable(e,t){const s=e.context,n=this.renderer.graphicsContext.getGpuContext(s),o=this.renderer._roundPixels|e._roundPixels;t.batches=n.batches.map(a=>{const l=Le.get(Un);return a.copyTo(l),l.renderable=e,l.roundPixels=o,l})}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null}}qc.extension={type:[A.WebGLPipes,A.WebGPUPipes],name:"graphics"},Q.add(Xc),Q.add(qc),Q.add(I_),Q.add(Ln);class rr extends Da{constructor(e){e instanceof mi&&(e={context:e});const{context:t,roundPixels:s,...r}=e||{};super({label:"Graphics",...r}),this.renderPipeId="graphics",t?this.context=t:(this.context=this._ownedContext=new mi,this.context.autoGarbageCollect=this.autoGarbageCollect),this.didViewUpdate=!0,this.allowChildren=!1,this.roundPixels=s??!1}set context(e){e!==this._context&&(this._context&&(this._context.off("update",this.onViewUpdate,this),this._context.off("unload",this.unload,this)),this._context=e,this._context.on("update",this.onViewUpdate,this),this._context.on("unload",this.unload,this),this.onViewUpdate())}get context(){return this._context}get bounds(){return this._context.bounds}updateBounds(){}containsPoint(e){return this._context.containsPoint(e)}destroy(e){this._ownedContext&&!e?this._ownedContext.destroy(e):(e===!0||(e==null?void 0:e.context)===!0)&&this._context.destroy(e),this._ownedContext=null,this._context=null,super.destroy(e)}_onTouch(e){this._gcLastUsed=e,this._context._gcLastUsed=e}_callContextMethod(e,t){return this.context[e](...t),this}setFillStyle(...e){return this._callContextMethod("setFillStyle",e)}setStrokeStyle(...e){return this._callContextMethod("setStrokeStyle",e)}fill(...e){return this._callContextMethod("fill",e)}stroke(...e){return this._callContextMethod("stroke",e)}texture(...e){return this._callContextMethod("texture",e)}beginPath(){return this._callContextMethod("beginPath",[])}cut(){return this._callContextMethod("cut",[])}arc(...e){return this._callContextMethod("arc",e)}arcTo(...e){return this._callContextMethod("arcTo",e)}arcToSvg(...e){return this._callContextMethod("arcToSvg",e)}bezierCurveTo(...e){return this._callContextMethod("bezierCurveTo",e)}closePath(){return this._callContextMethod("closePath",[])}ellipse(...e){return this._callContextMethod("ellipse",e)}circle(...e){return this._callContextMethod("circle",e)}path(...e){return this._callContextMethod("path",e)}lineTo(...e){return this._callContextMethod("lineTo",e)}moveTo(...e){return this._callContextMethod("moveTo",e)}quadraticCurveTo(...e){return this._callContextMethod("quadraticCurveTo",e)}rect(...e){return this._callContextMethod("rect",e)}roundRect(...e){return this._callContextMethod("roundRect",e)}poly(...e){return this._callContextMethod("poly",e)}regularPoly(...e){return this._callContextMethod("regularPoly",e)}roundPoly(...e){return this._callContextMethod("roundPoly",e)}roundShape(...e){return this._callContextMethod("roundShape",e)}filletRect(...e){return this._callContextMethod("filletRect",e)}chamferRect(...e){return this._callContextMethod("chamferRect",e)}star(...e){return this._callContextMethod("star",e)}svg(...e){return this._callContextMethod("svg",e)}restore(...e){return this._callContextMethod("restore",e)}save(){return this._callContextMethod("save",[])}getTransform(){return this.context.getTransform()}resetTransform(){return this._callContextMethod("resetTransform",[])}rotateTransform(...e){return this._callContextMethod("rotate",e)}scaleTransform(...e){return this._callContextMethod("scale",e)}setTransform(...e){return this._callContextMethod("setTransform",e)}transform(...e){return this._callContextMethod("transform",e)}translateTransform(...e){return this._callContextMethod("translate",e)}clear(){return this._callContextMethod("clear",[])}get fillStyle(){return this._context.fillStyle}set fillStyle(e){this._context.fillStyle=e}get strokeStyle(){return this._context.strokeStyle}set strokeStyle(e){this._context.strokeStyle=e}clone(e=!1){return e?new rr(this._context.clone()):(this._ownedContext=null,new rr(this._context))}lineStyle(e,t,s){ee(Be,"Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.");const r={};return e&&(r.width=e),t&&(r.color=t),s&&(r.alpha=s),this.context.strokeStyle=r,this}beginFill(e,t){ee(Be,"Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.");const s={};return e!==void 0&&(s.color=e),t!==void 0&&(s.alpha=t),this.context.fillStyle=s,this}endFill(){ee(Be,"Graphics#endFill is no longer needed. Use Graphics#fill to fill the shape with the desired style."),this.context.fill();const e=this.context.strokeStyle;return(e.width!==mi.defaultStrokeStyle.width||e.color!==mi.defaultStrokeStyle.color||e.alpha!==mi.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...e){return ee(Be,"Graphics#drawCircle has been renamed to Graphics#circle"),this._callContextMethod("circle",e)}drawEllipse(...e){return ee(Be,"Graphics#drawEllipse has been renamed to Graphics#ellipse"),this._callContextMethod("ellipse",e)}drawPolygon(...e){return ee(Be,"Graphics#drawPolygon has been renamed to Graphics#poly"),this._callContextMethod("poly",e)}drawRect(...e){return ee(Be,"Graphics#drawRect has been renamed to Graphics#rect"),this._callContextMethod("rect",e)}drawRoundedRect(...e){return ee(Be,"Graphics#drawRoundedRect has been renamed to Graphics#roundRect"),this._callContextMethod("roundRect",e)}drawStar(...e){return ee(Be,"Graphics#drawStar has been renamed to Graphics#star"),this._callContextMethod("star",e)}}let Is;function Kc(i){const e=pe.get().createCanvas(6,1),t=e.getContext("2d");return t.fillStyle=i,t.fillRect(0,0,6,1),e}function Zc(){if(Is!==void 0)return Is;try{const i=Kc("#ff00ff"),e=Kc("#ffff00"),s=pe.get().createCanvas(6,1).getContext("2d");s.globalCompositeOperation="multiply",s.drawImage(i,0,0),s.drawImage(e,2,0);const r=s.getImageData(2,0,1,1);if(!r)Is=!1;else{const n=r.data;Is=n[0]===255&&n[1]===0&&n[2]===0}}catch{Is=!1}return Is}const ne={canvas:null,convertTintToImage:!1,cacheStepsPerColorChannel:8,canUseMultiply:Zc(),tintMethod:null,_canvasSourceCache:new WeakMap,_unpremultipliedCache:new WeakMap,getCanvasSource:i=>{const e=i.source,t=e==null?void 0:e.resource;if(!t)return null;const s=e.alphaMode==="premultiplied-alpha",r=e.resourceWidth??e.pixelWidth,n=e.resourceHeight??e.pixelHeight,o=r!==e.pixelWidth||n!==e.pixelHeight;if(s){if((t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)&&!o)return t;const a=ne._unpremultipliedCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas}if(t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int8Array||t instanceof Uint16Array||t instanceof Int16Array||t instanceof Uint32Array||t instanceof Int32Array||t instanceof Float32Array||t instanceof ArrayBuffer){const a=ne._canvasSourceCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas;const l=pe.get().createCanvas(e.pixelWidth,e.pixelHeight),c=l.getContext("2d"),h=c.createImageData(e.pixelWidth,e.pixelHeight),u=h.data,p=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(e.format==="bgra8unorm")for(let d=0;d<u.length&&d+3<p.length;d+=4)u[d]=p[d+2],u[d+1]=p[d+1],u[d+2]=p[d],u[d+3]=p[d+3];else u.set(p.subarray(0,u.length));return c.putImageData(h,0,0),ne._canvasSourceCache.set(e,{canvas:l,resourceId:e._resourceId}),l}if(s){const a=pe.get().createCanvas(e.pixelWidth,e.pixelHeight),l=a.getContext("2d",{willReadFrequently:!0});a.width=e.pixelWidth,a.height=e.pixelHeight,l.drawImage(t,0,0);const c=l.getImageData(0,0,a.width,a.height),h=c.data;for(let u=0;u<h.length;u+=4){const p=h[u+3];if(p>0){const d=255/p;h[u]=Math.min(255,h[u]*d+.5),h[u+1]=Math.min(255,h[u+1]*d+.5),h[u+2]=Math.min(255,h[u+2]*d+.5)}}return l.putImageData(c,0,0),ne._unpremultipliedCache.set(e,{canvas:a,resourceId:e._resourceId}),a}if(o){const a=ne._canvasSourceCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas;const l=pe.get().createCanvas(e.pixelWidth,e.pixelHeight),c=l.getContext("2d");return l.width=e.pixelWidth,l.height=e.pixelHeight,c.drawImage(t,0,0),ne._canvasSourceCache.set(e,{canvas:l,resourceId:e._resourceId}),l}return t},getTintedCanvas:(i,e)=>{const t=i.texture,s=Pe.shared.setValue(e).toHex(),r=t.tintCache||(t.tintCache={}),n=r[s],o=t.source._resourceId;if((n==null?void 0:n.tintId)===o)return n;const a=n&&"getContext"in n?n:pe.get().createCanvas();return ne.tintMethod(t,e,a),a.tintId=o,r[s]=a,r[s]},getTintedPattern:(i,e)=>{const t=Pe.shared.setValue(e).toHex(),s=i.patternCache||(i.patternCache={}),r=i.source._resourceId;let n=s[t];return(n==null?void 0:n.tintId)===r||(ne.canvas||(ne.canvas=pe.get().createCanvas()),ne.tintMethod(i,e,ne.canvas),n=ne.canvas.getContext("2d").createPattern(ne.canvas,"repeat"),n.tintId=r,s[t]=n),n},applyPatternTransform:(i,e,t=!0)=>{if(!e)return;const s=i;if(!s.setTransform)return;const r=globalThis.DOMMatrix;if(!r)return;const n=new r([e.a,e.b,e.c,e.d,e.tx,e.ty]);s.setTransform(t?n.inverse():n)},tintWithMultiply:(i,e,t)=>{const s=t.getContext("2d"),r=i.frame.clone(),n=i.source._resolution??i.source.resolution??1,o=i.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=re.isVertical(o),l=a?r.height:r.width,c=a?r.width:r.height;t.width=Math.ceil(l),t.height=Math.ceil(c),s.save(),s.fillStyle=Pe.shared.setValue(e).toHex(),s.fillRect(0,0,l,c),s.globalCompositeOperation="multiply";const h=ne.getCanvasSource(i);if(!h){s.restore();return}o&&ne._applyInverseRotation(s,o,r.width,r.height),s.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.globalCompositeOperation="destination-atop",s.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.restore()},tintWithOverlay:(i,e,t)=>{const s=t.getContext("2d"),r=i.frame.clone(),n=i.source._resolution??i.source.resolution??1,o=i.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=re.isVertical(o),l=a?r.height:r.width,c=a?r.width:r.height;t.width=Math.ceil(l),t.height=Math.ceil(c),s.save(),s.globalCompositeOperation="copy",s.fillStyle=Pe.shared.setValue(e).toHex(),s.fillRect(0,0,l,c),s.globalCompositeOperation="destination-atop";const h=ne.getCanvasSource(i);if(!h){s.restore();return}o&&ne._applyInverseRotation(s,o,r.width,r.height),s.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.restore()},tintWithPerPixel:(i,e,t)=>{const s=t.getContext("2d"),r=i.frame.clone(),n=i.source._resolution??i.source.resolution??1,o=i.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=re.isVertical(o),l=a?r.height:r.width,c=a?r.width:r.height;t.width=Math.ceil(l),t.height=Math.ceil(c),s.save(),s.globalCompositeOperation="copy";const h=ne.getCanvasSource(i);if(!h){s.restore();return}o&&ne._applyInverseRotation(s,o,r.width,r.height),s.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.restore();const u=e>>16&255,p=e>>8&255,d=e&255,g=s.getImageData(0,0,l,c),_=g.data;for(let b=0;b<_.length;b+=4)_[b]=_[b]*u/255,_[b+1]=_[b+1]*p/255,_[b+2]=_[b+2]*d/255;s.putImageData(g,0,0)},_applyInverseRotation:(i,e,t,s)=>{const r=re.inv(e),n=re.uX(r),o=re.uY(r),a=re.vX(r),l=re.vY(r),c=-Math.min(0,n*t,a*s,n*t+a*s),h=-Math.min(0,o*t,l*s,o*t+l*s);i.transform(n,o,a,l,c,h)}};ne.tintMethod=ne.canUseMultiply?ne.tintWithMultiply:ne.tintWithPerPixel;const nr={name:"local-uniform-bit",vertex:{header:`
|
|
502
|
+
`;class A_ extends Sl{constructor(e){const{sprite:t,...s}=e,r=new _a(t.texture),n=new gt({uFilterMatrix:{value:new H,type:"mat3x3<f32>"},uMaskClamp:{value:r.uClampFrame,type:"vec4<f32>"},uAlpha:{value:1,type:"f32"},uInverse:{value:e.inverse?1:0,type:"f32"}}),o=is.from({vertex:{source:jc,entryPoint:"mainVertex"},fragment:{source:jc,entryPoint:"mainFragment"}}),a=Es.from({vertex:T_,fragment:S_,name:"mask-filter"});super({...s,gpuProgram:o,glProgram:a,clipToViewport:!1,resources:{filterUniforms:n,uMaskTexture:t.texture.source}}),this.sprite=t,this._textureMatrix=r}set inverse(e){this.resources.filterUniforms.uniforms.uInverse=e?1:0}get inverse(){return this.resources.filterUniforms.uniforms.uInverse===1}apply(e,t,s,r){this._textureMatrix.texture=this.sprite.texture,e.calculateSpriteMatrix(this.resources.filterUniforms.uniforms.uFilterMatrix,this.sprite).prepend(this._textureMatrix.mapCoord),this.resources.uMaskTexture=this.sprite.texture.source,e.applyFilter(this,t,s,r)}}class w_{constructor(){this.isBatchable=!1}reset(){this.isBatchable=!1,this.context=null,this.graphicsData&&(this.graphicsData.destroy(),this.graphicsData=null)}destroy(){this.reset()}}class I_{constructor(){this.instructions=new Zr}init(){this.instructions.reset()}destroy(){this.instructions.destroy(),this.instructions=null}}const Xn=class ra{constructor(e){this._renderer=e,this._managedContexts=new Rt({renderer:e,type:"resource",name:"graphicsContext"})}init(e){ra.defaultOptions.bezierSmoothness=(e==null?void 0:e.bezierSmoothness)??ra.defaultOptions.bezierSmoothness}getContextRenderData(e){return this.getGpuContext(e).graphicsData||this._initContextRenderData(e)}updateGpuContext(e){const t=e._gpuData,s=!!t[this._renderer.uid],r=t[this._renderer.uid]||this._initContext(e);return(e.dirty||!s)&&(s&&r.reset(),r.isBatchable=!1,e.dirty=!1),r}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){const t=new I_,s=this.getGpuContext(e);return s.graphicsData=t,t.init(),t}_initContext(e){const t=new w_;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}};Xn.extension={type:[A.CanvasSystem],name:"graphicsContext"},Xn.defaultOptions={bezierSmoothness:.5};let R_=Xn;class Xc{constructor(e,t){this.state=It.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new Rt({renderer:e,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){return!1}addRenderable(e,t){this._managedGraphics.add(e),this.renderer.renderPipes.batch.break(t),t.add(e)}updateRenderable(e){}execute(e){e.isRenderable&&this._adaptor.execute(this,e)}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null}}Xc.extension={type:[A.CanvasPipes],name:"graphics"};function Yc(i,e,t){const s=(i>>24&255)/255;e[t++]=(i&255)/255*s,e[t++]=(i>>8&255)/255*s,e[t++]=(i>>16&255)/255*s,e[t++]=s}class M_{constructor(){this.batches=[],this.batched=!1}destroy(){this.batches.forEach(e=>{Le.return(e)}),this.batches.length=0}}class qc{constructor(e,t){this.state=It.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new Rt({renderer:e,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){const t=e.context,s=!!e._gpuData,n=this.renderer.graphicsContext.updateGpuContext(t);return!!(n.isBatchable||s!==n.isBatchable)}addRenderable(e,t){const r=this.renderer.graphicsContext.updateGpuContext(e.context);e.didViewUpdate&&this._rebuild(e),r.isBatchable?this._addToBatcher(e,t):(this.renderer.renderPipes.batch.break(t),t.add(e))}updateRenderable(e){const s=this._getGpuDataForRenderable(e).batches;for(let r=0;r<s.length;r++){const n=s[r];n._batcher.updateElement(n)}}execute(e){if(!e.isRenderable)return;const t=this.renderer,s=e.context;if(!t.graphicsContext.getGpuContext(s).batches.length)return;const n=s.customShader||this._adaptor.shader;this.state.blendMode=e.groupBlendMode;const o=n.resources.localUniforms.uniforms;o.uTransformMatrix=e.groupTransform,o.uRound=t._roundPixels|e._roundPixels,Yc(e.groupColorAlpha,o.uColor,0),this._adaptor.execute(this,e)}_rebuild(e){const t=this._getGpuDataForRenderable(e),r=this.renderer.graphicsContext.updateGpuContext(e.context);t.destroy(),r.isBatchable&&this._updateBatchesForRenderable(e,t)}_addToBatcher(e,t){const s=this.renderer.renderPipes.batch,r=this._getGpuDataForRenderable(e).batches;for(let n=0;n<r.length;n++){const o=r[n];s.addToBatch(o,t)}}_getGpuDataForRenderable(e){return e._gpuData[this.renderer.uid]||this._initGpuDataForRenderable(e)}_initGpuDataForRenderable(e){const t=new M_;return e._gpuData[this.renderer.uid]=t,this._managedGraphics.add(e),t}_updateBatchesForRenderable(e,t){const s=e.context,n=this.renderer.graphicsContext.getGpuContext(s),o=this.renderer._roundPixels|e._roundPixels;t.batches=n.batches.map(a=>{const l=Le.get(Un);return a.copyTo(l),l.renderable=e,l.roundPixels=o,l})}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null}}qc.extension={type:[A.WebGLPipes,A.WebGPUPipes],name:"graphics"},Q.add(Xc),Q.add(qc),Q.add(R_),Q.add(Ln);class rr extends Da{constructor(e){e instanceof mi&&(e={context:e});const{context:t,roundPixels:s,...r}=e||{};super({label:"Graphics",...r}),this.renderPipeId="graphics",t?this.context=t:(this.context=this._ownedContext=new mi,this.context.autoGarbageCollect=this.autoGarbageCollect),this.didViewUpdate=!0,this.allowChildren=!1,this.roundPixels=s??!1}set context(e){e!==this._context&&(this._context&&(this._context.off("update",this.onViewUpdate,this),this._context.off("unload",this.unload,this)),this._context=e,this._context.on("update",this.onViewUpdate,this),this._context.on("unload",this.unload,this),this.onViewUpdate())}get context(){return this._context}get bounds(){return this._context.bounds}updateBounds(){}containsPoint(e){return this._context.containsPoint(e)}destroy(e){this._ownedContext&&!e?this._ownedContext.destroy(e):(e===!0||(e==null?void 0:e.context)===!0)&&this._context.destroy(e),this._ownedContext=null,this._context=null,super.destroy(e)}_onTouch(e){this._gcLastUsed=e,this._context._gcLastUsed=e}_callContextMethod(e,t){return this.context[e](...t),this}setFillStyle(...e){return this._callContextMethod("setFillStyle",e)}setStrokeStyle(...e){return this._callContextMethod("setStrokeStyle",e)}fill(...e){return this._callContextMethod("fill",e)}stroke(...e){return this._callContextMethod("stroke",e)}texture(...e){return this._callContextMethod("texture",e)}beginPath(){return this._callContextMethod("beginPath",[])}cut(){return this._callContextMethod("cut",[])}arc(...e){return this._callContextMethod("arc",e)}arcTo(...e){return this._callContextMethod("arcTo",e)}arcToSvg(...e){return this._callContextMethod("arcToSvg",e)}bezierCurveTo(...e){return this._callContextMethod("bezierCurveTo",e)}closePath(){return this._callContextMethod("closePath",[])}ellipse(...e){return this._callContextMethod("ellipse",e)}circle(...e){return this._callContextMethod("circle",e)}path(...e){return this._callContextMethod("path",e)}lineTo(...e){return this._callContextMethod("lineTo",e)}moveTo(...e){return this._callContextMethod("moveTo",e)}quadraticCurveTo(...e){return this._callContextMethod("quadraticCurveTo",e)}rect(...e){return this._callContextMethod("rect",e)}roundRect(...e){return this._callContextMethod("roundRect",e)}poly(...e){return this._callContextMethod("poly",e)}regularPoly(...e){return this._callContextMethod("regularPoly",e)}roundPoly(...e){return this._callContextMethod("roundPoly",e)}roundShape(...e){return this._callContextMethod("roundShape",e)}filletRect(...e){return this._callContextMethod("filletRect",e)}chamferRect(...e){return this._callContextMethod("chamferRect",e)}star(...e){return this._callContextMethod("star",e)}svg(...e){return this._callContextMethod("svg",e)}restore(...e){return this._callContextMethod("restore",e)}save(){return this._callContextMethod("save",[])}getTransform(){return this.context.getTransform()}resetTransform(){return this._callContextMethod("resetTransform",[])}rotateTransform(...e){return this._callContextMethod("rotate",e)}scaleTransform(...e){return this._callContextMethod("scale",e)}setTransform(...e){return this._callContextMethod("setTransform",e)}transform(...e){return this._callContextMethod("transform",e)}translateTransform(...e){return this._callContextMethod("translate",e)}clear(){return this._callContextMethod("clear",[])}get fillStyle(){return this._context.fillStyle}set fillStyle(e){this._context.fillStyle=e}get strokeStyle(){return this._context.strokeStyle}set strokeStyle(e){this._context.strokeStyle=e}clone(e=!1){return e?new rr(this._context.clone()):(this._ownedContext=null,new rr(this._context))}lineStyle(e,t,s){ee(Be,"Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.");const r={};return e&&(r.width=e),t&&(r.color=t),s&&(r.alpha=s),this.context.strokeStyle=r,this}beginFill(e,t){ee(Be,"Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.");const s={};return e!==void 0&&(s.color=e),t!==void 0&&(s.alpha=t),this.context.fillStyle=s,this}endFill(){ee(Be,"Graphics#endFill is no longer needed. Use Graphics#fill to fill the shape with the desired style."),this.context.fill();const e=this.context.strokeStyle;return(e.width!==mi.defaultStrokeStyle.width||e.color!==mi.defaultStrokeStyle.color||e.alpha!==mi.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...e){return ee(Be,"Graphics#drawCircle has been renamed to Graphics#circle"),this._callContextMethod("circle",e)}drawEllipse(...e){return ee(Be,"Graphics#drawEllipse has been renamed to Graphics#ellipse"),this._callContextMethod("ellipse",e)}drawPolygon(...e){return ee(Be,"Graphics#drawPolygon has been renamed to Graphics#poly"),this._callContextMethod("poly",e)}drawRect(...e){return ee(Be,"Graphics#drawRect has been renamed to Graphics#rect"),this._callContextMethod("rect",e)}drawRoundedRect(...e){return ee(Be,"Graphics#drawRoundedRect has been renamed to Graphics#roundRect"),this._callContextMethod("roundRect",e)}drawStar(...e){return ee(Be,"Graphics#drawStar has been renamed to Graphics#star"),this._callContextMethod("star",e)}}let Is;function Kc(i){const e=pe.get().createCanvas(6,1),t=e.getContext("2d");return t.fillStyle=i,t.fillRect(0,0,6,1),e}function Zc(){if(Is!==void 0)return Is;try{const i=Kc("#ff00ff"),e=Kc("#ffff00"),s=pe.get().createCanvas(6,1).getContext("2d");s.globalCompositeOperation="multiply",s.drawImage(i,0,0),s.drawImage(e,2,0);const r=s.getImageData(2,0,1,1);if(!r)Is=!1;else{const n=r.data;Is=n[0]===255&&n[1]===0&&n[2]===0}}catch{Is=!1}return Is}const ne={canvas:null,convertTintToImage:!1,cacheStepsPerColorChannel:8,canUseMultiply:Zc(),tintMethod:null,_canvasSourceCache:new WeakMap,_unpremultipliedCache:new WeakMap,getCanvasSource:i=>{const e=i.source,t=e==null?void 0:e.resource;if(!t)return null;const s=e.alphaMode==="premultiplied-alpha",r=e.resourceWidth??e.pixelWidth,n=e.resourceHeight??e.pixelHeight,o=r!==e.pixelWidth||n!==e.pixelHeight;if(s){if((t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)&&!o)return t;const a=ne._unpremultipliedCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas}if(t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int8Array||t instanceof Uint16Array||t instanceof Int16Array||t instanceof Uint32Array||t instanceof Int32Array||t instanceof Float32Array||t instanceof ArrayBuffer){const a=ne._canvasSourceCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas;const l=pe.get().createCanvas(e.pixelWidth,e.pixelHeight),c=l.getContext("2d"),h=c.createImageData(e.pixelWidth,e.pixelHeight),u=h.data,p=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(e.format==="bgra8unorm")for(let d=0;d<u.length&&d+3<p.length;d+=4)u[d]=p[d+2],u[d+1]=p[d+1],u[d+2]=p[d],u[d+3]=p[d+3];else u.set(p.subarray(0,u.length));return c.putImageData(h,0,0),ne._canvasSourceCache.set(e,{canvas:l,resourceId:e._resourceId}),l}if(s){const a=pe.get().createCanvas(e.pixelWidth,e.pixelHeight),l=a.getContext("2d",{willReadFrequently:!0});a.width=e.pixelWidth,a.height=e.pixelHeight,l.drawImage(t,0,0);const c=l.getImageData(0,0,a.width,a.height),h=c.data;for(let u=0;u<h.length;u+=4){const p=h[u+3];if(p>0){const d=255/p;h[u]=Math.min(255,h[u]*d+.5),h[u+1]=Math.min(255,h[u+1]*d+.5),h[u+2]=Math.min(255,h[u+2]*d+.5)}}return l.putImageData(c,0,0),ne._unpremultipliedCache.set(e,{canvas:a,resourceId:e._resourceId}),a}if(o){const a=ne._canvasSourceCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas;const l=pe.get().createCanvas(e.pixelWidth,e.pixelHeight),c=l.getContext("2d");return l.width=e.pixelWidth,l.height=e.pixelHeight,c.drawImage(t,0,0),ne._canvasSourceCache.set(e,{canvas:l,resourceId:e._resourceId}),l}return t},getTintedCanvas:(i,e)=>{const t=i.texture,s=Pe.shared.setValue(e).toHex(),r=t.tintCache||(t.tintCache={}),n=r[s],o=t.source._resourceId;if((n==null?void 0:n.tintId)===o)return n;const a=n&&"getContext"in n?n:pe.get().createCanvas();return ne.tintMethod(t,e,a),a.tintId=o,r[s]=a,r[s]},getTintedPattern:(i,e)=>{const t=Pe.shared.setValue(e).toHex(),s=i.patternCache||(i.patternCache={}),r=i.source._resourceId;let n=s[t];return(n==null?void 0:n.tintId)===r||(ne.canvas||(ne.canvas=pe.get().createCanvas()),ne.tintMethod(i,e,ne.canvas),n=ne.canvas.getContext("2d").createPattern(ne.canvas,"repeat"),n.tintId=r,s[t]=n),n},applyPatternTransform:(i,e,t=!0)=>{if(!e)return;const s=i;if(!s.setTransform)return;const r=globalThis.DOMMatrix;if(!r)return;const n=new r([e.a,e.b,e.c,e.d,e.tx,e.ty]);s.setTransform(t?n.inverse():n)},tintWithMultiply:(i,e,t)=>{const s=t.getContext("2d"),r=i.frame.clone(),n=i.source._resolution??i.source.resolution??1,o=i.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=re.isVertical(o),l=a?r.height:r.width,c=a?r.width:r.height;t.width=Math.ceil(l),t.height=Math.ceil(c),s.save(),s.fillStyle=Pe.shared.setValue(e).toHex(),s.fillRect(0,0,l,c),s.globalCompositeOperation="multiply";const h=ne.getCanvasSource(i);if(!h){s.restore();return}o&&ne._applyInverseRotation(s,o,r.width,r.height),s.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.globalCompositeOperation="destination-atop",s.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.restore()},tintWithOverlay:(i,e,t)=>{const s=t.getContext("2d"),r=i.frame.clone(),n=i.source._resolution??i.source.resolution??1,o=i.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=re.isVertical(o),l=a?r.height:r.width,c=a?r.width:r.height;t.width=Math.ceil(l),t.height=Math.ceil(c),s.save(),s.globalCompositeOperation="copy",s.fillStyle=Pe.shared.setValue(e).toHex(),s.fillRect(0,0,l,c),s.globalCompositeOperation="destination-atop";const h=ne.getCanvasSource(i);if(!h){s.restore();return}o&&ne._applyInverseRotation(s,o,r.width,r.height),s.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.restore()},tintWithPerPixel:(i,e,t)=>{const s=t.getContext("2d"),r=i.frame.clone(),n=i.source._resolution??i.source.resolution??1,o=i.rotate;r.x*=n,r.y*=n,r.width*=n,r.height*=n;const a=re.isVertical(o),l=a?r.height:r.width,c=a?r.width:r.height;t.width=Math.ceil(l),t.height=Math.ceil(c),s.save(),s.globalCompositeOperation="copy";const h=ne.getCanvasSource(i);if(!h){s.restore();return}o&&ne._applyInverseRotation(s,o,r.width,r.height),s.drawImage(h,r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.restore();const u=e>>16&255,p=e>>8&255,d=e&255,g=s.getImageData(0,0,l,c),_=g.data;for(let b=0;b<_.length;b+=4)_[b]=_[b]*u/255,_[b+1]=_[b+1]*p/255,_[b+2]=_[b+2]*d/255;s.putImageData(g,0,0)},_applyInverseRotation:(i,e,t,s)=>{const r=re.inv(e),n=re.uX(r),o=re.uY(r),a=re.vX(r),l=re.vY(r),c=-Math.min(0,n*t,a*s,n*t+a*s),h=-Math.min(0,o*t,l*s,o*t+l*s);i.transform(n,o,a,l,c,h)}};ne.tintMethod=ne.canUseMultiply?ne.tintWithMultiply:ne.tintWithPerPixel;const nr={name:"local-uniform-bit",vertex:{header:`
|
|
503
503
|
|
|
504
504
|
struct LocalUniforms {
|
|
505
505
|
uTransformMatrix:mat3x3<f32>,
|
|
@@ -516,7 +516,7 @@ fn mainFragment(
|
|
|
516
516
|
{
|
|
517
517
|
vPosition = vec4(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw);
|
|
518
518
|
}
|
|
519
|
-
`}},
|
|
519
|
+
`}},P_={...nr,vertex:{...nr.vertex,header:nr.vertex.header.replace("group(1)","group(2)")}},Jc={name:"local-uniform-bit",vertex:{header:`
|
|
520
520
|
|
|
521
521
|
uniform mat3 uTransformMatrix;
|
|
522
522
|
uniform vec4 uColor;
|
|
@@ -529,7 +529,7 @@ fn mainFragment(
|
|
|
529
529
|
{
|
|
530
530
|
gl_Position.xy = roundPixels(gl_Position.xy, uResolution);
|
|
531
531
|
}
|
|
532
|
-
`}};class
|
|
532
|
+
`}};class k_{constructor(e){this._canvasPool=Object.create(null),this.canvasOptions=e||{},this.enableFullScreen=!1}_createCanvasAndContext(e,t){const s=pe.get().createCanvas();s.width=e,s.height=t;const r=s.getContext("2d");return{canvas:s,context:r}}getOptimalCanvasAndContext(e,t,s=1){e=Math.ceil(e*s-1e-6),t=Math.ceil(t*s-1e-6),e=Gi(e),t=Gi(t);const r=(e<<17)+(t<<1);this._canvasPool[r]||(this._canvasPool[r]=[]);let n=this._canvasPool[r].pop();return n||(n=this._createCanvasAndContext(e,t)),n}returnCanvasAndContext(e){const t=e.canvas,{width:s,height:r}=t,n=(s<<17)+(r<<1);e.context.resetTransform(),e.context.clearRect(0,0,s,r),this._canvasPool[n].push(e)}clear(){this._canvasPool={}}}const Yn=new k_;ms.register(Yn);class Qc{constructor(){this.batcherName="default",this.topology="triangle-list",this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this._attributeStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null}destroy(){this.reset()}}function O_(){const{userAgent:i}=pe.get().getNavigator();return/^((?!chrome|android).)*safari/i.test(i)}const qn=class us{static _getPatternRepeat(e,t){const s=e&&e!=="clamp-to-edge",r=t&&t!=="clamp-to-edge";return s&&r?"repeat":s?"repeat-x":r?"repeat-y":"no-repeat"}start(e,t,s){}execute(e,t){var a,l,c,h;const s=t.elements;if(!s||!s.length)return;const r=e.renderer,n=r.canvasContext,o=n.activeContext;for(let u=0;u<s.length;u++){const p=s[u];if(!p.packAsQuad)continue;const d=p,g=d.texture,_=g?ne.getCanvasSource(g):null;if(!_)continue;const b=g.source.style,v=n.smoothProperty,C=b.scaleMode!=="nearest";o[v]!==C&&(o[v]=C),n.setBlendMode(t.blendMode);const E=((a=r.globalUniforms.globalUniformData)==null?void 0:a.worldColor)??4294967295,S=d.color,w=(E>>>24&255)/255,R=(S>>>24&255)/255,M=((l=r.filter)==null?void 0:l.alphaMultiplier)??1,D=w*R*M;if(D<=0)continue;o.globalAlpha=D;const G=E&16777215,k=S&16777215,O=_s(gs(k,G)),V=g.frame,X=b.addressModeU??b.addressMode,z=b.addressModeV??b.addressMode,de=us._getPatternRepeat(X,z),B=g.source._resolution??g.source.resolution??1,U=(h=(c=d.renderable)==null?void 0:c.renderGroup)==null?void 0:h.isCachedAsTexture,q=V.x*B,N=V.y*B,K=V.width*B,Z=V.height*B,$=d.bounds,ae=r.renderTarget.renderTarget.isRoot,xe=$.minX,Se=$.minY,F=$.maxX-$.minX,fe=$.maxY-$.minY,le=g.rotate,L=g.uvs,me=Math.min(L.x0,L.x1,L.x2,L.x3,L.y0,L.y1,L.y2,L.y3),Y=Math.max(L.x0,L.x1,L.x2,L.x3,L.y0,L.y1,L.y2,L.y3),se=de!=="no-repeat"&&(me<0||Y>1),ce=le&&!(!se&&(O!==16777215||le));ce?(us._tempPatternMatrix.copyFrom(d.transform),re.matrixAppendRotationInv(us._tempPatternMatrix,le,xe,Se,F,fe),n.setContextTransform(us._tempPatternMatrix,d.roundPixels===1,void 0,U&&ae)):n.setContextTransform(d.transform,d.roundPixels===1,void 0,U&&ae);const He=ce?0:xe,Zt=ce?0:Se,Ct=F,hs=fe;if(se){let Vs=_;const Bt=O!==16777215&&!le,dt=V.width<=g.source.width&&V.height<=g.source.height;Bt&&dt&&(Vs=ne.getTintedCanvas({texture:g},O));const tt=o.createPattern(Vs,de);if(!tt)continue;const zs=Ct,Mr=hs;if(zs===0||Mr===0)continue;const ft=1/zs,Pr=1/Mr,y=(L.x1-L.x0)*ft,f=(L.y1-L.y0)*ft,m=(L.x3-L.x0)*Pr,x=(L.y3-L.y0)*Pr,T=L.x0-y*He-m*Zt,I=L.y0-f*He-x*Zt,P=g.source.pixelWidth,J=g.source.pixelHeight;us._tempPatternMatrix.set(y*P,f*J,m*P,x*J,T*P,I*J),ne.applyPatternTransform(tt,us._tempPatternMatrix),o.fillStyle=tt,o.fillRect(He,Zt,Ct,hs)}else{const Bt=O!==16777215||le?ne.getTintedCanvas({texture:g},O):_,dt=Bt!==_;o.drawImage(Bt,dt?0:q,dt?0:N,dt?Bt.width:K,dt?Bt.height:Z,He,Zt,Ct,hs)}}}};qn._tempPatternMatrix=new H,qn.extension={type:[A.CanvasPipesAdaptor],name:"batch"};let B_=qn;class eh{constructor(){this._tempState=It.for2d(),this._didUploadHash={}}init(e){e.renderer.runners.contextChange.add(this)}contextChange(){this._didUploadHash={}}start(e,t,s){const r=e.renderer,n=this._didUploadHash[s.uid];r.shader.bind(s,n),n||(this._didUploadHash[s.uid]=!0),r.shader.updateUniformGroup(r.globalUniforms.uniformGroup),r.geometry.bind(t,s.glProgram)}execute(e,t){const s=e.renderer;this._tempState.blendMode=t.blendMode,s.state.set(this._tempState);const r=t.textures.textures;for(let n=0;n<t.textures.count;n++)s.texture.bind(r[n],n);s.geometry.draw(t.topology,t.size,t.start)}}eh.extension={type:[A.WebGLPipesAdaptor],name:"batch"};const or=It.for2d();class th{start(e,t,s){const r=e.renderer,n=r.encoder,o=s.gpuProgram;this._shader=s,this._geometry=t,n.setGeometry(t,o),or.blendMode="normal",r.pipeline.getPipeline(t,o,or);const a=r.globalUniforms.bindGroup;n.resetBindGroup(1),n.setBindGroup(0,a,o)}execute(e,t){const s=this._shader.gpuProgram,r=e.renderer,n=r.encoder;if(!t.bindGroup){const l=t.textures;t.bindGroup=An(l.textures,l.count,r.limits.maxBatchableTextures)}or.blendMode=t.blendMode;const o=r.bindGroup.getBindGroup(t.bindGroup,s,1),a=r.pipeline.getPipeline(this._geometry,s,or,t.topology);t.bindGroup._touch(r.gc.now,r.tick),n.setPipeline(a),n.renderPassEncoder.setBindGroup(1,o),n.renderPassEncoder.drawIndexed(t.size,1,t.start)}}th.extension={type:[A.WebGPUPipesAdaptor],name:"batch"};const Kn=class gf{constructor(e,t){var s,r;this.state=It.for2d(),this._batchersByInstructionSet=Object.create(null),this._activeBatches=Object.create(null),this.renderer=e,this._adaptor=t,(r=(s=this._adaptor).init)==null||r.call(s,this)}static getBatcher(e){return new this._availableBatchers[e]}buildStart(e){let t=this._batchersByInstructionSet[e.uid];t||(t=this._batchersByInstructionSet[e.uid]=Object.create(null),t.default||(t.default=new Nn({maxTextures:this.renderer.limits.maxBatchableTextures}))),this._activeBatches=t,this._activeBatch=this._activeBatches.default;for(const s in this._activeBatches)this._activeBatches[s].begin()}addToBatch(e,t){if(this._activeBatch.name!==e.batcherName){this._activeBatch.break(t);let s=this._activeBatches[e.batcherName];s||(s=this._activeBatches[e.batcherName]=gf.getBatcher(e.batcherName),s.begin()),this._activeBatch=s}this._activeBatch.add(e)}break(e){this._activeBatch.break(e)}buildEnd(e){this._activeBatch.break(e);const t=this._activeBatches;for(const s in t){const r=t[s],n=r.geometry;n.indexBuffer.setDataWithSize(r.indexBuffer,r.indexSize,!0),n.buffers[0].setDataWithSize(r.attributeBuffer.float32View,r.attributeSize,!1)}}upload(e){const t=this._batchersByInstructionSet[e.uid];for(const s in t){const r=t[s],n=r.geometry;r.dirty&&(r.dirty=!1,n.buffers[0].update(r.attributeSize*4))}}execute(e){if(e.action==="startBatch"){const t=e.batcher,s=t.geometry,r=t.shader;this._adaptor.start(this,s,r)}this._adaptor.execute(this,e)}destroy(){this.state=null,this.renderer=null,this._adaptor=null;for(const e in this._activeBatches)this._activeBatches[e].destroy();this._activeBatches=null}};Kn.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"batch"},Kn._availableBatchers=Object.create(null);let Zn=Kn;Q.handleByMap(A.Batcher,Zn._availableBatchers),Q.add(Nn);const D_={name:"texture-bit",vertex:{header:`
|
|
533
533
|
|
|
534
534
|
struct TextureUniforms {
|
|
535
535
|
uTextureMatrix:mat3x3<f32>,
|
|
@@ -545,7 +545,7 @@ fn mainFragment(
|
|
|
545
545
|
|
|
546
546
|
`,main:`
|
|
547
547
|
outColor = textureSample(uTexture, uSampler, vUV);
|
|
548
|
-
`}},
|
|
548
|
+
`}},N_={name:"texture-bit",vertex:{header:`
|
|
549
549
|
uniform mat3 uTextureMatrix;
|
|
550
550
|
`,main:`
|
|
551
551
|
uv = (uTextureMatrix * vec3(uv, 1.0)).xy;
|
|
@@ -555,9 +555,9 @@ fn mainFragment(
|
|
|
555
555
|
|
|
556
556
|
`,main:`
|
|
557
557
|
outColor = texture(uTexture, vUV);
|
|
558
|
-
`}},N_=new Ye;class U_ extends Li{constructor(){super(),this.filters=[new T_({sprite:new Dt(j.EMPTY),inverse:!1,resolution:"inherit",antialias:"inherit"})]}get sprite(){return this.filters[0].sprite}set sprite(e){this.filters[0].sprite=e}get inverse(){return this.filters[0].inverse}set inverse(e){this.filters[0].inverse=e}}class Jn{constructor(e){this._activeMaskStage=[],this._renderer=e}push(e,t,s){const r=this._renderer;if(r.renderPipes.batch.break(s),s.add({renderPipeId:"alphaMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1,maskedContainer:t}),e.inverse=t._maskOptions.inverse,e.renderMaskToTexture){const n=e.mask;n.includeInBuild=!0,n.collectRenderables(s,r,null),n.includeInBuild=!1}r.renderPipes.batch.break(s),s.add({renderPipeId:"alphaMask",action:"pushMaskEnd",mask:e,maskedContainer:t,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"alphaMask",action:"popMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){const t=this._renderer,s=e.mask.renderMaskToTexture;if(e.action==="pushMaskBegin"){const r=Le.get(U_);if(r.inverse=e.inverse,s){e.mask.mask.measurable=!0;const n=Yr(e.mask.mask,!0,N_);e.mask.mask.measurable=!1,n.ceil();const o=t.renderTarget.renderTarget.colorTexture.source,a=Qe.getOptimalTexture(n.width,n.height,o._resolution,o.antialias);t.renderTarget.push(a,!0),t.globalUniforms.push({offset:n,worldColor:4294967295});const l=r.sprite;l.texture=a,l.worldTransform.tx=n.minX,l.worldTransform.ty=n.minY,this._activeMaskStage.push({filterEffect:r,maskedContainer:e.maskedContainer,filterTexture:a})}else r.sprite=e.mask.mask,this._activeMaskStage.push({filterEffect:r,maskedContainer:e.maskedContainer})}else if(e.action==="pushMaskEnd"){const r=this._activeMaskStage[this._activeMaskStage.length-1];s&&(t.type===_t.WEBGL&&t.renderTarget.finishRenderPass(),t.renderTarget.pop(),t.globalUniforms.pop()),t.filter.push({renderPipeId:"filter",action:"pushFilter",container:r.maskedContainer,filterEffect:r.filterEffect,canBundle:!1})}else if(e.action==="popMaskEnd"){t.filter.pop();const r=this._activeMaskStage.pop();s&&Qe.returnTexture(r.filterTexture),Le.return(r.filterEffect)}}destroy(){this._renderer=null,this._activeMaskStage=null}}Jn.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"alphaMask"};class sh{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,s){this._renderer.renderPipes.batch.break(s);const r=this._colorStack;r[this._colorStackIndex]=r[this._colorStackIndex-1]&e.mask;const n=this._colorStack[this._colorStackIndex];n!==this._currentColor&&(this._currentColor=n,s.add({renderPipeId:"colorMask",colorMask:n,canBundle:!1})),this._colorStackIndex++}pop(e,t,s){this._renderer.renderPipes.batch.break(s);const r=this._colorStack;this._colorStackIndex--;const n=r[this._colorStackIndex-1];n!==this._currentColor&&(this._currentColor=n,s.add({renderPipeId:"colorMask",colorMask:n,canBundle:!1}))}execute(e){}destroy(){this._renderer=null,this._colorStack=null}}sh.extension={type:[A.CanvasPipes],name:"colorMask"};class ih{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,s){this._renderer.renderPipes.batch.break(s);const n=this._colorStack;n[this._colorStackIndex]=n[this._colorStackIndex-1]&e.mask;const o=this._colorStack[this._colorStackIndex];o!==this._currentColor&&(this._currentColor=o,s.add({renderPipeId:"colorMask",colorMask:o,canBundle:!1})),this._colorStackIndex++}pop(e,t,s){this._renderer.renderPipes.batch.break(s);const n=this._colorStack;this._colorStackIndex--;const o=n[this._colorStackIndex-1];o!==this._currentColor&&(this._currentColor=o,s.add({renderPipeId:"colorMask",colorMask:o,canBundle:!1}))}execute(e){this._renderer.colorMask.setMask(e.colorMask)}destroy(){this._renderer=null,this._colorStack=null}}ih.extension={type:[A.WebGLPipes,A.WebGPUPipes],name:"colorMask"};function G_(i,e,t,s,r,n){n=Math.max(0,Math.min(n,Math.min(s,r)/2)),i.moveTo(e+n,t),i.lineTo(e+s-n,t),i.quadraticCurveTo(e+s,t,e+s,t+n),i.lineTo(e+s,t+r-n),i.quadraticCurveTo(e+s,t+r,e+s-n,t+r),i.lineTo(e+n,t+r),i.quadraticCurveTo(e,t+r,e,t+r-n),i.lineTo(e,t+n),i.quadraticCurveTo(e,t,e+n,t)}function rh(i,e){switch(e.type){case"rectangle":{const t=e;i.rect(t.x,t.y,t.width,t.height);break}case"roundedRectangle":{const t=e;G_(i,t.x,t.y,t.width,t.height,t.radius);break}case"circle":{const t=e;i.moveTo(t.x+t.radius,t.y),i.arc(t.x,t.y,t.radius,0,Math.PI*2);break}case"ellipse":{const t=e;i.ellipse?(i.moveTo(t.x+t.halfWidth,t.y),i.ellipse(t.x,t.y,t.halfWidth,t.halfHeight,0,0,Math.PI*2)):(i.save(),i.translate(t.x,t.y),i.scale(t.halfWidth,t.halfHeight),i.moveTo(1,0),i.arc(0,0,1,0,Math.PI*2),i.restore());break}case"triangle":{const t=e;i.moveTo(t.x,t.y),i.lineTo(t.x2,t.y2),i.lineTo(t.x3,t.y3),i.closePath();break}case"polygon":default:{const t=e,s=t.points;if(!(s!=null&&s.length))break;i.moveTo(s[0],s[1]);for(let r=2;r<s.length;r+=2)i.lineTo(s[r],s[r+1]);t.closePath&&i.closePath();break}}}function F_(i,e){if(!(e!=null&&e.length))return!1;for(let t=0;t<e.length;t++){const s=e[t];if(!(s!=null&&s.shape))continue;const r=s.transform,n=r&&!r.isIdentity();n&&(i.save(),i.transform(r.a,r.b,r.c,r.d,r.tx,r.ty)),rh(i,s.shape),n&&i.restore()}return!0}class nh{constructor(e){this._warnedMaskTypes=new Set,this._canvasMaskStack=[],this._renderer=e}push(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"stencilMask",action:"popMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){var h,u,p;if(e.action!=="pushMaskBegin"&&e.action!=="popMaskEnd")return;const t=this._renderer,s=t.canvasContext,r=s==null?void 0:s.activeContext;if(!r)return;if(e.action==="popMaskEnd"){this._canvasMaskStack.pop()&&r.restore();return}e.inverse&&this._warnOnce("inverse","CanvasRenderer: inverse masks are not supported on Canvas2D; ignoring inverse flag.");const n=e.mask.mask;if(!(n instanceof rr)){this._warnOnce("nonGraphics","CanvasRenderer: only Graphics masks are supported in Canvas2D; skipping mask."),this._canvasMaskStack.push(!1);return}const o=n,a=(h=o.context)==null?void 0:h.instructions;if(!(a!=null&&a.length)){this._canvasMaskStack.push(!1);return}r.save(),s.setContextTransform(o.groupTransform,(t._roundPixels|o._roundPixels)===1),r.beginPath();let l=!1,c=!1;for(let d=0;d<a.length;d++){const g=a[d],_=g.action;if(_!=="fill"&&_!=="stroke")continue;const b=g.data,v=(u=b==null?void 0:b.path)==null?void 0:u.shapePath;if(!((p=v==null?void 0:v.shapePrimitives)!=null&&p.length))continue;const C=v.shapePrimitives;for(let E=0;E<C.length;E++){const S=C[E];if(!(S!=null&&S.shape))continue;const w=S.transform,R=w&&!w.isIdentity();R&&(r.save(),r.transform(w.a,w.b,w.c,w.d,w.tx,w.ty)),rh(r,S.shape),c=F_(r,S.holes)||c,l=!0,R&&r.restore()}}if(!l){r.restore(),this._canvasMaskStack.push(!1);return}c?r.clip("evenodd"):r.clip(),this._canvasMaskStack.push(!0)}destroy(){this._renderer=null,this._warnedMaskTypes=null,this._canvasMaskStack=null}_warnOnce(e,t){this._warnedMaskTypes.has(e)||(this._warnedMaskTypes.add(e),ie(t))}}nh.extension={type:[A.CanvasPipes],name:"stencilMask"};class oh{constructor(e){this._maskStackHash={},this._maskHash=new WeakMap,this._renderer=e}push(e,t,s){var r;const n=e,o=this._renderer;o.renderPipes.batch.break(s),o.renderPipes.blendMode.setBlendMode(n.mask,"none",s),s.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1});const a=n.mask;a.includeInBuild=!0,this._maskHash.has(n)||this._maskHash.set(n,{instructionsStart:0,instructionsLength:0});const l=this._maskHash.get(n);l.instructionsStart=s.instructionSize,a.collectRenderables(s,o,null),a.includeInBuild=!1,o.renderPipes.batch.break(s),s.add({renderPipeId:"stencilMask",action:"pushMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1});const c=s.instructionSize-l.instructionsStart-1;l.instructionsLength=c;const h=o.renderTarget.renderTarget.uid;(r=this._maskStackHash)[h]??(r[h]=0)}pop(e,t,s){const r=e,n=this._renderer;n.renderPipes.batch.break(s),n.renderPipes.blendMode.setBlendMode(r.mask,"none",s),s.add({renderPipeId:"stencilMask",action:"popMaskBegin",inverse:t._maskOptions.inverse,canBundle:!1});const o=this._maskHash.get(e);for(let a=0;a<o.instructionsLength;a++)s.instructions[s.instructionSize++]=s.instructions[o.instructionsStart++];s.add({renderPipeId:"stencilMask",action:"popMaskEnd",canBundle:!1})}execute(e){var t;const s=this._renderer,r=s,n=s.renderTarget.renderTarget.uid;let o=(t=this._maskStackHash)[n]??(t[n]=0);e.action==="pushMaskBegin"?(r.renderTarget.ensureDepthStencil(),r.stencil.setStencilMode(ke.RENDERING_MASK_ADD,o),o++,r.colorMask.setMask(0)):e.action==="pushMaskEnd"?(e.inverse?r.stencil.setStencilMode(ke.INVERSE_MASK_ACTIVE,o):r.stencil.setStencilMode(ke.MASK_ACTIVE,o),r.colorMask.setMask(15)):e.action==="popMaskBegin"?(r.colorMask.setMask(0),o!==0?r.stencil.setStencilMode(ke.RENDERING_MASK_REMOVE,o):(r.renderTarget.clear(null,st.STENCIL),r.stencil.setStencilMode(ke.DISABLED,o)),o--):e.action==="popMaskEnd"&&(e.inverse?r.stencil.setStencilMode(ke.INVERSE_MASK_ACTIVE,o):r.stencil.setStencilMode(ke.MASK_ACTIVE,o),r.colorMask.setMask(15)),this._maskStackHash[n]=o}destroy(){this._renderer=null,this._maskStackHash=null,this._maskHash=null}}oh.extension={type:[A.WebGLPipes,A.WebGPUPipes],name:"stencilMask"};const ge="source-over";function L_(){const i=Zc(),e=Object.create(null);return e.inherit=ge,e.none=ge,e.normal="source-over",e.add="lighter",e.multiply=i?"multiply":ge,e.screen=i?"screen":ge,e.overlay=i?"overlay":ge,e.darken=i?"darken":ge,e.lighten=i?"lighten":ge,e["color-dodge"]=i?"color-dodge":ge,e["color-burn"]=i?"color-burn":ge,e["hard-light"]=i?"hard-light":ge,e["soft-light"]=i?"soft-light":ge,e.difference=i?"difference":ge,e.exclusion=i?"exclusion":ge,e.saturation=i?"saturation":ge,e.color=i?"color":ge,e.luminosity=i?"luminosity":ge,e["linear-burn"]=i?"color-burn":ge,e["linear-dodge"]=i?"color-dodge":ge,e["linear-light"]=i?"hard-light":ge,e["pin-light"]=i?"hard-light":ge,e["vivid-light"]=i?"hard-light":ge,e["hard-mix"]=ge,e.negation=i?"difference":ge,e["normal-npm"]=e.normal,e["add-npm"]=e.add,e["screen-npm"]=e.screen,e.erase="destination-out",e.subtract=ge,e.divide=ge,e.min=ge,e.max=ge,e}const W_=new H;class ah{constructor(e){this.activeResolution=1,this.smoothProperty="imageSmoothingEnabled",this.blendModes=L_(),this._activeBlendMode="normal",this._projTransform=null,this._outerBlend=!1,this._warnedBlendModes=new Set,this._renderer=e}resolutionChange(e){this.activeResolution=e}init(){const e=this._renderer.background.alpha<1;if(this.rootContext=this._renderer.canvas.getContext("2d",{alpha:e}),this.activeContext=this.rootContext,this.activeResolution=this._renderer.resolution,!this.rootContext.imageSmoothingEnabled){const t=this.rootContext;t.webkitImageSmoothingEnabled?this.smoothProperty="webkitImageSmoothingEnabled":t.mozImageSmoothingEnabled?this.smoothProperty="mozImageSmoothingEnabled":t.oImageSmoothingEnabled?this.smoothProperty="oImageSmoothingEnabled":t.msImageSmoothingEnabled&&(this.smoothProperty="msImageSmoothingEnabled")}}setContextTransform(e,t,s,r){var c;const n=r?H.IDENTITY:((c=this._renderer.globalUniforms.globalUniformData)==null?void 0:c.worldTransformMatrix)||H.IDENTITY;let o=W_;o.copyFrom(n),o.append(e);const a=this._projTransform,l=this.activeResolution;if(s=s||l,a){const h=H.shared;h.copyFrom(o),h.prepend(a),o=h}t?this.activeContext.setTransform(o.a*s,o.b*s,o.c*s,o.d*s,o.tx*l|0,o.ty*l|0):this.activeContext.setTransform(o.a*s,o.b*s,o.c*s,o.d*s,o.tx*l,o.ty*l)}clear(e,t){const s=this.activeContext,r=this._renderer;if(s.clearRect(0,0,r.width,r.height),e){const n=Pe.shared.setValue(e);s.globalAlpha=t??n.alpha,s.fillStyle=n.toHex(),s.fillRect(0,0,r.width,r.height),s.globalAlpha=1}}setBlendMode(e){if(this._activeBlendMode===e)return;this._activeBlendMode=e,this._outerBlend=!1;const t=this.blendModes[e];if(!t){this._warnedBlendModes.has(e)||(console.warn(`CanvasRenderer: blend mode "${e}" is not supported in Canvas2D; falling back to "source-over".`),this._warnedBlendModes.add(e)),this.activeContext.globalCompositeOperation="source-over";return}this.activeContext.globalCompositeOperation=t}destroy(){this.rootContext=null,this.activeContext=null,this._warnedBlendModes.clear()}}ah.extension={type:[A.CanvasSystem],name:"canvasContext"};class lh{constructor(){this.maxTextures=16,this.maxBatchableTextures=16,this.maxUniformBindings=0}init(){}}lh.extension={type:[A.CanvasSystem],name:"limits"};class Qn{constructor(e){this._renderer=e}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}addRenderable(e,t){this._renderer.renderPipes.batch.break(t),t.add(e)}execute(e){e.isRenderable&&e.render(this._renderer)}destroy(){this._renderer=null}}Qn.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"customRender"};function eo(i,e){const t=i.instructionSet,s=t.instructions;for(let r=0;r<t.instructionSize;r++){const n=s[r];e[n.renderPipeId].execute(n)}}class to{constructor(e){this._renderer=e}addRenderGroup(e,t){e.isCachedAsTexture?this._addRenderableCacheAsTexture(e,t):this._addRenderableDirect(e,t)}execute(e){e.isRenderable&&(e.isCachedAsTexture?this._executeCacheAsTexture(e):this._executeDirect(e))}destroy(){this._renderer=null}_addRenderableDirect(e,t){this._renderer.renderPipes.batch.break(t),e._batchableRenderGroup&&(Le.return(e._batchableRenderGroup),e._batchableRenderGroup=null),t.add(e)}_addRenderableCacheAsTexture(e,t){const s=e._batchableRenderGroup??(e._batchableRenderGroup=Le.get(Qc));s.renderable=e.root,s.transform=e.root.relativeGroupTransform,s.texture=e.texture,s.bounds=e._textureBounds,t.add(e),this._renderer.renderPipes.blendMode.pushBlendMode(e,e.root.groupBlendMode,t),this._renderer.renderPipes.batch.addToBatch(s,t),this._renderer.renderPipes.blendMode.popBlendMode(t)}_executeCacheAsTexture(e){if(e.textureNeedsUpdate){e.textureNeedsUpdate=!1;const t=new H().translate(-e._textureBounds.x,-e._textureBounds.y);this._renderer.renderTarget.push(e.texture,!0,null,e.texture.frame),this._renderer.globalUniforms.push({worldTransformMatrix:t,worldColor:4294967295,offset:{x:0,y:0}}),eo(e,this._renderer.renderPipes),this._renderer.renderTarget.finishRenderPass(),this._renderer.renderTarget.pop(),this._renderer.globalUniforms.pop()}e._batchableRenderGroup._batcher.updateElement(e._batchableRenderGroup),e._batchableRenderGroup._batcher.geometry.buffers[0].update()}_executeDirect(e){this._renderer.globalUniforms.push({worldTransformMatrix:e.inverseParentTextureTransform,worldColor:e.worldColorAlpha}),eo(e,this._renderer.renderPipes),this._renderer.globalUniforms.pop()}}to.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"renderGroup"};const H_="#808080",ar=new H,V_=new H,z_=new H,so=new H;function $_(i,e,t){i.beginPath();for(let s=0;s<t.length;s+=3){const r=t[s]*2,n=t[s+1]*2,o=t[s+2]*2;i.moveTo(e[r],e[r+1]),i.lineTo(e[n],e[n+1]),i.lineTo(e[o],e[o+1]),i.closePath()}i.fill()}function j_(i){return`#${(i&16777215).toString(16).padStart(6,"0")}`}function X_(i,e,t,s,r,n){n=Math.max(0,Math.min(n,Math.min(s,r)/2)),i.moveTo(e+n,t),i.lineTo(e+s-n,t),i.quadraticCurveTo(e+s,t,e+s,t+n),i.lineTo(e+s,t+r-n),i.quadraticCurveTo(e+s,t+r,e+s-n,t+r),i.lineTo(e+n,t+r),i.quadraticCurveTo(e,t+r,e,t+r-n),i.lineTo(e,t+n),i.quadraticCurveTo(e,t,e+n,t)}function lr(i,e){switch(e.type){case"rectangle":{const t=e;i.rect(t.x,t.y,t.width,t.height);break}case"roundedRectangle":{const t=e;X_(i,t.x,t.y,t.width,t.height,t.radius);break}case"circle":{const t=e;i.arc(t.x,t.y,t.radius,0,Math.PI*2);break}case"ellipse":{const t=e;i.ellipse?i.ellipse(t.x,t.y,t.halfWidth,t.halfHeight,0,0,Math.PI*2):(i.save(),i.translate(t.x,t.y),i.scale(t.halfWidth,t.halfHeight),i.arc(0,0,1,0,Math.PI*2),i.restore());break}case"triangle":{const t=e;i.moveTo(t.x,t.y),i.lineTo(t.x2,t.y2),i.lineTo(t.x3,t.y3),i.closePath();break}case"polygon":default:{const t=e,s=t.points;if(!(s!=null&&s.length))break;i.moveTo(s[0],s[1]);for(let r=2;r<s.length;r+=2)i.lineTo(s[r],s[r+1]);t.closePath&&i.closePath();break}}}function Y_(i,e){if(!(e!=null&&e.length))return!1;for(let t=0;t<e.length;t++){const s=e[t];if(!(s!=null&&s.shape))continue;const r=s.transform,n=r&&!r.isIdentity();n&&(i.save(),i.transform(r.a,r.b,r.c,r.d,r.tx,r.ty)),lr(i,s.shape),n&&i.restore()}return!0}function q_(i,e,t,s){const r=i.fill;if(r instanceof As){r.buildGradient();const o=r.texture;if(o){const a=ne.getTintedPattern(o,e),l=t?so.copyFrom(t).scale(o.source.pixelWidth,o.source.pixelHeight):so.copyFrom(r.transform);return s&&!i.textureSpace&&l.append(s),ne.applyPatternTransform(a,l),a}}if(r instanceof Oc){const o=ne.getTintedPattern(r.texture,e);return ne.applyPatternTransform(o,r.transform),o}const n=i.texture;if(n&&n!==j.WHITE){if(!n.source.resource)return H_;const o=ne.getTintedPattern(n,e),a=t?so.copyFrom(t).scale(n.source.pixelWidth,n.source.pixelHeight):i.matrix;return ne.applyPatternTransform(o,a),o}return j_(e)}class ch{constructor(){this.shader=null}contextChange(e){}execute(e,t){var C,E,S,w,R,M,D;const s=e.renderer,r=s.canvasContext,n=r.activeContext,o=t.groupTransform,a=((C=s.globalUniforms.globalUniformData)==null?void 0:C.worldColor)??4294967295,l=t.groupColorAlpha,c=(a>>>24&255)/255,h=(l>>>24&255)/255,u=((E=s.filter)==null?void 0:E.alphaMultiplier)??1,p=c*h*u;if(p<=0)return;const d=a&16777215,g=l&16777215,_=_s(gs(g,d)),b=s._roundPixels|t._roundPixels;n.save(),r.setContextTransform(o,b===1),r.setBlendMode(t.groupBlendMode);const v=t.context.instructions;for(let G=0;G<v.length;G++){const k=v[G];if(k.action==="texture"){const q=k.data,N=q.image,K=N?ne.getCanvasSource(N):null;if(!K)continue;const Z=q.alpha*p;if(Z<=0)continue;const $=gs(q.style,_);n.globalAlpha=Z;let ae=K;$!==16777215&&(ae=ne.getTintedCanvas({texture:N},$));const xe=N.frame,Se=N.source._resolution??N.source.resolution??1;let F=xe.x*Se,fe=xe.y*Se;const le=xe.width*Se,L=xe.height*Se;ae!==K&&(F=0,fe=0);const me=q.transform,Y=me&&!me.isIdentity(),se=N.rotate;Y||se?(ar.copyFrom(o),Y&&ar.append(me),se&&re.matrixAppendRotationInv(ar,se,q.dx,q.dy,q.dw,q.dh),r.setContextTransform(ar,b===1)):r.setContextTransform(o,b===1),n.drawImage(ae,F,fe,ae===K?le:ae.width,ae===K?L:ae.height,se?0:q.dx,se?0:q.dy,q.dw,q.dh),(Y||se)&&r.setContextTransform(o,b===1);continue}const O=k.data,V=(S=O==null?void 0:O.path)==null?void 0:S.shapePath;if(!((w=V==null?void 0:V.shapePrimitives)!=null&&w.length))continue;const X=O.style,z=gs(X.color,_),de=X.alpha*p;if(de<=0)continue;const B=k.action==="stroke";if(n.globalAlpha=de,B){const q=X;n.lineWidth=q.width,n.lineCap=q.cap,n.lineJoin=q.join,n.miterLimit=q.miterLimit}const U=V.shapePrimitives;if(!B&&((D=(M=(R=O.hole)==null?void 0:R.shapePath)==null?void 0:M.shapePrimitives)!=null&&D.length)){const q=U[U.length-1];q.holes=O.hole.shapePath.shapePrimitives}for(let q=0;q<U.length;q++){const N=U[q];if(!(N!=null&&N.shape))continue;const K=N.transform,Z=K&&!K.isIdentity(),$=X.texture&&X.texture!==j.WHITE,ae=X.textureSpace==="global"?K:null,xe=$?xc(V_,X,N.shape,ae):null,Se=Z?z_.copyFrom(o).append(K):o,F=q_(X,z,xe,Se);if(Z&&(n.save(),n.transform(K.a,K.b,K.c,K.d,K.tx,K.ty)),B){const fe=X;if(fe.alignment!==.5&&!fe.pixelLine){const L=[],me=[],Y=[],se=ui[N.shape.type];if(se!=null&&se.build(N.shape,L)){const we=N.shape.closePath??!0;gc(L,fe,!1,we,me,Y),n.fillStyle=F,$_(n,me,Y)}else n.strokeStyle=F,n.beginPath(),lr(n,N.shape),n.stroke()}else n.strokeStyle=F,n.beginPath(),lr(n,N.shape),n.stroke()}else n.fillStyle=F,n.beginPath(),lr(n,N.shape),Y_(n,N.holes)?n.fill("evenodd"):n.fill();Z&&n.restore()}}n.restore()}destroy(){this.shader=null}}ch.extension={type:[A.CanvasPipesAdaptor],name:"graphics"};class io{constructor(e){this._renderer=e}addRenderable(e,t){const s=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,s),this._renderer.renderPipes.batch.addToBatch(s,t)}updateRenderable(e){const t=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,t),t._batcher.updateElement(t)}validateRenderable(e){const t=this._getGpuSprite(e);return!t._batcher.checkAndUpdateTexture(t,e._texture)}_updateBatchableSprite(e,t){t.bounds=e.visualBounds,t.texture=e._texture}_getGpuSprite(e){return e._gpuData[this._renderer.uid]||this._initGPUSprite(e)}_initGPUSprite(e){const t=new Qc;return t.renderable=e,t.transform=e.groupTransform,t.texture=e._texture,t.bounds=e.visualBounds,t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,t}destroy(){this._renderer=null}}io.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"sprite"};const _i={};Q.handle(A.BlendMode,i=>{if(!i.name)throw new Error("BlendMode extension must have a name property");_i[i.name]=i.ref},i=>{delete _i[i.name]});class ro{constructor(e){this._blendModeStack=[],this._isAdvanced=!1,this._filterHash=Object.create(null),this._renderer=e,this._renderer.runners.prerender.add(this)}prerender(){this._activeBlendMode="normal",this._isAdvanced=!1}pushBlendMode(e,t,s){this._blendModeStack.push(t),this.setBlendMode(e,t,s)}popBlendMode(e){this._blendModeStack.pop();const t=this._blendModeStack[this._activeBlendMode.length-1]??"normal";this.setBlendMode(null,t,e)}setBlendMode(e,t,s){var n;const r=e instanceof Jr;if(this._activeBlendMode===t){this._isAdvanced&&e&&!r&&((n=this._renderableList)==null||n.push(e));return}this._isAdvanced&&this._endAdvancedBlendMode(s),this._activeBlendMode=t,e&&(this._isAdvanced=!!_i[t],this._isAdvanced&&this._beginAdvancedBlendMode(e,s))}_beginAdvancedBlendMode(e,t){this._renderer.renderPipes.batch.break(t);const s=this._activeBlendMode;if(!_i[s]){ie(`Unable to assign BlendMode: '${s}'. You may want to include: import 'pixi.js/advanced-blend-modes'`);return}const r=this._ensureFilterEffect(s),n=e instanceof Jr,o={renderPipeId:"filter",action:"pushFilter",filterEffect:r,renderables:n?null:[e],container:n?e.root:null,canBundle:!1};this._renderableList=o.renderables,t.add(o)}_ensureFilterEffect(e){let t=this._filterHash[e];return t||(t=this._filterHash[e]=new Li,t.filters=[new _i[e]]),t}_endAdvancedBlendMode(e){this._isAdvanced=!1,this._renderableList=null,this._renderer.renderPipes.batch.break(e),e.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}buildStart(){this._isAdvanced=!1}buildEnd(e){this._isAdvanced&&this._endAdvancedBlendMode(e)}destroy(){this._renderer=null,this._renderableList=null;for(const e in this._filterHash)this._filterHash[e].destroy();this._filterHash=null}}ro.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"blendMode"};function no(i,e){e||(e=0);for(let t=e;t<i.length&&i[t];t++)i[t]=null}const K_=new Ve,hh=js|zi|tn;function uh(i,e=!1){Z_(i);const t=i.childrenToUpdate,s=i.updateTick++;for(const r in t){const n=Number(r),o=t[r],a=o.list,l=o.index;for(let c=0;c<l;c++){const h=a[c];h.parentRenderGroup===i&&h.relativeRenderGroupDepth===n&&dh(h,s,0)}no(a,l),o.index=0}if(e)for(let r=0;r<i.renderGroupChildren.length;r++)uh(i.renderGroupChildren[r],e)}function Z_(i){const e=i.root;let t;if(i.renderGroupParent){const s=i.renderGroupParent;i.worldTransform.appendFrom(e.relativeGroupTransform,s.worldTransform),i.worldColor=Wi(e.groupColor,s.worldColor),t=e.groupAlpha*s.worldAlpha}else i.worldTransform.copyFrom(e.localTransform),i.worldColor=e.localColor,t=e.localAlpha;t=t<0?0:t>1?1:t,i.worldAlpha=t,i.worldColorAlpha=i.worldColor+((t*255|0)<<24)}function dh(i,e,t){if(e===i.updateTick)return;i.updateTick=e,i.didChange=!1;const s=i.localTransform;i.updateLocalTransform();const r=i.parent;if(r&&!r.renderGroup?(t|=i._updateFlags,i.relativeGroupTransform.appendFrom(s,r.relativeGroupTransform),t&hh&&fh(i,r,t)):(t=i._updateFlags,i.relativeGroupTransform.copyFrom(s),t&hh&&fh(i,K_,t)),!i.renderGroup){const n=i.children,o=n.length;for(let c=0;c<o;c++)dh(n[c],e,t);const a=i.parentRenderGroup,l=i;l.renderPipeId&&!a.structureDidChange&&a.updateRenderable(l)}}function fh(i,e,t){if(t&zi){i.groupColor=Wi(i.localColor,e.groupColor);let s=i.localAlpha*e.groupAlpha;s=s<0?0:s>1?1:s,i.groupAlpha=s,i.groupColorAlpha=i.groupColor+((s*255|0)<<24)}t&tn&&(i.groupBlendMode=i.localBlendMode==="inherit"?e.groupBlendMode:i.localBlendMode),t&js&&(i.globalDisplayStatus=i.localDisplayStatus&e.globalDisplayStatus),i._updateFlags=0}function J_(i,e){const{list:t}=i.childrenRenderablesToUpdate;let s=!1;for(let r=0;r<i.childrenRenderablesToUpdate.index;r++){const n=t[r];if(s=e[n.renderPipeId].validateRenderable(n),s)break}return i.structureDidChange=s,s}const Q_=new H;class ph{constructor(e){this._renderer=e}render({container:e,transform:t}){const s=e.parent,r=e.renderGroup.renderGroupParent;e.parent=null,e.renderGroup.renderGroupParent=null;const n=this._renderer,o=Q_;t&&(o.copyFrom(e.renderGroup.localTransform),e.renderGroup.localTransform.copyFrom(t));const a=n.renderPipes;this._updateCachedRenderGroups(e.renderGroup,null),this._updateRenderGroups(e.renderGroup),n.globalUniforms.start({worldTransformMatrix:t?e.renderGroup.localTransform:e.renderGroup.worldTransform,worldColor:e.renderGroup.worldColorAlpha}),eo(e.renderGroup,a),a.uniformBatch&&a.uniformBatch.renderEnd(),t&&e.renderGroup.localTransform.copyFrom(o),e.parent=s,e.renderGroup.renderGroupParent=r}destroy(){this._renderer=null}_updateCachedRenderGroups(e,t){if(e._parentCacheAsTextureRenderGroup=t,e.isCachedAsTexture){if(!e.textureNeedsUpdate)return;t=e}for(let s=e.renderGroupChildren.length-1;s>=0;s--)this._updateCachedRenderGroups(e.renderGroupChildren[s],t);if(e.invalidateMatrices(),e.isCachedAsTexture){if(e.textureNeedsUpdate){const s=e.root.getLocalBounds(),r=this._renderer,n=e.textureOptions.resolution||r.view.resolution,o=e.textureOptions.antialias??r.view.antialias,a=e.textureOptions.scaleMode??"linear",l=e.texture;s.ceil(),e.texture&&Qe.returnTexture(e.texture,!0);const c=Qe.getOptimalTexture(s.width,s.height,n,o);c._source.style=new Fr({scaleMode:a}),e.texture=c,e._textureBounds||(e._textureBounds=new Ye),e._textureBounds.copyFrom(s),l!==e.texture&&e.renderGroupParent&&(e.renderGroupParent.structureDidChange=!0)}}else e.texture&&(Qe.returnTexture(e.texture,!0),e.texture=null)}_updateRenderGroups(e){const t=this._renderer,s=t.renderPipes;if(e.runOnRender(t),e.instructionSet.renderPipes=s,e.structureDidChange?no(e.childrenRenderablesToUpdate.list,0):J_(e,s),uh(e),e.structureDidChange?(e.structureDidChange=!1,this._buildInstructions(e,t)):this._updateRenderables(e),e.childrenRenderablesToUpdate.index=0,t.renderPipes.batch.upload(e.instructionSet),!(e.isCachedAsTexture&&!e.textureNeedsUpdate))for(let r=0;r<e.renderGroupChildren.length;r++)this._updateRenderGroups(e.renderGroupChildren[r])}_updateRenderables(e){const{list:t,index:s}=e.childrenRenderablesToUpdate;for(let r=0;r<s;r++){const n=t[r];n.didViewUpdate&&e.updateRenderable(n)}no(t,s)}_buildInstructions(e,t){const s=e.root,r=e.instructionSet;r.reset();const n=t.renderPipes?t:t.batch.renderer,o=n.renderPipes;o.batch.buildStart(r),o.blendMode.buildStart(),o.colorMask.buildStart(),s.sortableChildren&&s.sortChildren(),s.collectRenderablesWithEffects(r,n,null),o.batch.buildEnd(r),o.blendMode.buildEnd(r)}}ph.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"renderGroup"};const oo=class _f{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new Pe(0),this.color=this._backgroundColor,this.alpha=1}init(e){e={..._f.defaultOptions,...e},this.clearBeforeRender=e.clearBeforeRender,this.color=e.background||e.backgroundColor||this._backgroundColor,this.alpha=e.backgroundAlpha,this._backgroundColor.setAlpha(e.backgroundAlpha)}get color(){return this._backgroundColor}set color(e){Pe.shared.setValue(e).alpha<1&&this._backgroundColor.alpha===1&&ie("Cannot set a transparent background on an opaque canvas. To enable transparency, set backgroundAlpha < 1 when initializing your Application."),this._backgroundColor.setValue(e)}get alpha(){return this._backgroundColor.alpha}set alpha(e){this._backgroundColor.setAlpha(e)}get colorRgba(){return this._backgroundColor.toArray()}destroy(){}};oo.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"background",priority:0},oo.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0};let ey=oo;const ao={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},lo=class yf{constructor(e){this._renderer=e}_normalizeOptions(e,t={}){return e instanceof Ve||e instanceof j?{target:e,...t}:{...t,...e}}async image(e){const t=pe.get().createImage();return t.src=await this.base64(e),t}async base64(e){e=this._normalizeOptions(e,yf.defaultImageOptions);const{format:t,quality:s}=e,r=this.canvas(e);if(r.toBlob!==void 0)return new Promise((n,o)=>{r.toBlob(a=>{if(!a){o(new Error("ICanvas.toBlob failed!"));return}const l=new FileReader;l.onload=()=>n(l.result),l.onerror=o,l.readAsDataURL(a)},ao[t],s)});if(r.toDataURL!==void 0)return r.toDataURL(ao[t],s);if(r.convertToBlob!==void 0){const n=await r.convertToBlob({type:ao[t],quality:s});return new Promise((o,a)=>{const l=new FileReader;l.onload=()=>o(l.result),l.onerror=a,l.readAsDataURL(n)})}throw new Error("Extract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented")}canvas(e){e=this._normalizeOptions(e);const t=e.target,s=this._renderer;if(t instanceof j)return s.texture.generateCanvas(t);const r=s.textureGenerator.generateTexture(e),n=s.texture.generateCanvas(r);return r.destroy(!0),n}pixels(e){e=this._normalizeOptions(e);const t=e.target,s=this._renderer,r=t instanceof j?t:s.textureGenerator.generateTexture(e),n=s.texture.getPixels(r);return t instanceof Ve&&r.destroy(!0),n}texture(e){return e=this._normalizeOptions(e),e.target instanceof j?e.target:this._renderer.textureGenerator.generateTexture(e)}download(e){e=this._normalizeOptions(e);const t=this.canvas(e),s=document.createElement("a");s.download=e.filename??"image.png",s.href=t.toDataURL("image/png"),document.body.appendChild(s),s.click(),document.body.removeChild(s)}log(e){const t=e.width??200;e=this._normalizeOptions(e);const s=this.canvas(e),r=s.toDataURL();console.log(`[Pixi Texture] ${s.width}px ${s.height}px`);const n=["font-size: 1px;",`padding: ${t}px 300px;`,`background: url(${r}) no-repeat;`,"background-size: contain;"].join(" ");console.log("%c ",n)}destroy(){this._renderer=null}};lo.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"extract"},lo.defaultImageOptions={format:"png",quality:1};let ty=lo;class co extends j{static create(e){const{dynamic:t,...s}=e;return new co({source:new De(s),dynamic:t??!1})}resize(e,t,s){return this.source.resize(e,t,s),this}}const sy=new Ce,iy=new Ye,ry=[0,0,0,0];class mh{constructor(e){this._renderer=e}generateTexture(e){var c;e instanceof Ve&&(e={target:e,frame:void 0,textureSourceOptions:{},resolution:void 0});const t=e.resolution||this._renderer.resolution,s=e.antialias||this._renderer.view.antialias,r=e.target;let n=e.clearColor;n?n=Array.isArray(n)&&n.length===4?n:Pe.shared.setValue(n).toArray():n=ry;const o=((c=e.frame)==null?void 0:c.copyTo(sy))||Kr(r,iy).rectangle;o.width=Math.max(o.width,1/t)|0,o.height=Math.max(o.height,1/t)|0;const a=co.create({...e.textureSourceOptions,width:o.width,height:o.height,resolution:t,antialias:s}),l=H.shared.translate(-o.x,-o.y);return this._renderer.render({container:r,transform:l,target:a,clearColor:n}),a.source.updateMipmaps(),a}destroy(){this._renderer=null}}mh.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"textureGenerator"};function ny(i){let e=!1;for(const s in i)if(i[s]==null){e=!0;break}if(!e)return i;const t=Object.create(null);for(const s in i){const r=i[s];r&&(t[s]=r)}return t}function oy(i){let e=0;for(let t=0;t<i.length;t++)i[t]==null?e++:i[t-e]=i[t];return i.length-=e,i}const ho=class bf{constructor(e){this._managedResources=[],this._managedResourceHashes=[],this._managedCollections=[],this._ready=!1,this._renderer=e}init(e){e={...bf.defaultOptions,...e},this.maxUnusedTime=e.gcMaxUnusedTime,this._frequency=e.gcFrequency,this.enabled=e.gcActive,this.now=performance.now()}get enabled(){return!!this._handler}set enabled(e){this.enabled!==e&&(e?(this._handler=this._renderer.scheduler.repeat(()=>{this._ready=!0},this._frequency,!1),this._collectionsHandler=this._renderer.scheduler.repeat(()=>{for(const t of this._managedCollections){const{context:s,collection:r,type:n}=t;n==="hash"?s[r]=ny(s[r]):s[r]=oy(s[r])}},this._frequency)):(this._renderer.scheduler.cancel(this._handler),this._renderer.scheduler.cancel(this._collectionsHandler),this._handler=0,this._collectionsHandler=0))}prerender({container:e}){this.now=performance.now(),e.renderGroup.gcTick=this._renderer.tick++,this._updateInstructionGCTick(e.renderGroup,e.renderGroup.gcTick)}postrender(){!this._ready||!this.enabled||(this.run(),this._ready=!1)}_updateInstructionGCTick(e,t){e.instructionSet.gcTick=t,e.gcTick=t;for(const s of e.renderGroupChildren)this._updateInstructionGCTick(s,t)}addCollection(e,t,s){this._managedCollections.push({context:e,collection:t,type:s})}addResource(e,t){var r,n;if(e._gcLastUsed!==-1){e._gcLastUsed=this.now,(r=e._onTouch)==null||r.call(e,this.now);return}const s=this._managedResources.length;e._gcData={index:s,type:t},e._gcLastUsed=this.now,(n=e._onTouch)==null||n.call(e,this.now),e.once("unload",this.removeResource,this),this._managedResources.push(e)}removeResource(e){const t=e._gcData;if(!t)return;const s=t.index,r=this._managedResources.length-1;if(s!==r){const n=this._managedResources[r];this._managedResources[s]=n,n._gcData.index=s}this._managedResources.length--,e._gcData=null,e._gcLastUsed=-1}addResourceHash(e,t,s,r=0){this._managedResourceHashes.push({context:e,hash:t,type:s,priority:r}),this._managedResourceHashes.sort((n,o)=>n.priority-o.priority)}run(){const e=performance.now(),t=this._managedResourceHashes;for(const r of t)this.runOnHash(r,e);let s=0;for(let r=0;r<this._managedResources.length;r++){const n=this._managedResources[r];s=this.runOnResource(n,e,s)}this._managedResources.length=s}updateRenderableGCTick(e,t){var n,o;const s=e.renderGroup??e.parentRenderGroup,r=((n=s==null?void 0:s.instructionSet)==null?void 0:n.gcTick)??-1;((s==null?void 0:s.gcTick)??0)===r&&(e._gcLastUsed=t,(o=e._onTouch)==null||o.call(e,t))}runOnResource(e,t,s){const r=e._gcData;return r.type==="renderable"&&this.updateRenderableGCTick(e,t),t-e._gcLastUsed<this.maxUnusedTime||!e.autoGarbageCollect?(this._managedResources[s]=e,r.index=s,s++):(e.unload(),e._gcData=null,e._gcLastUsed=-1,e.off("unload",this.removeResource,this)),s}_createHashClone(e,t){const s=Object.create(null);for(const r in e){if(r===t)break;e[r]!==null&&(s[r]=e[r])}return s}runOnHash(e,t){var c;const{context:s,hash:r,type:n}=e,o=s[r];let a=null,l=0;for(const h in o){const u=o[h];if(u===null){l++,l===1e4&&!a&&(a=this._createHashClone(o,h));continue}if(u._gcLastUsed===-1){u._gcLastUsed=t,(c=u._onTouch)==null||c.call(u,t),a&&(a[h]=u);continue}if(n==="renderable"&&this.updateRenderableGCTick(u,t),!(t-u._gcLastUsed<this.maxUnusedTime)&&u.autoGarbageCollect){if(a||(l+1!==1e4?(o[h]=null,l++):a=this._createHashClone(o,h)),n==="renderable"){const d=u,g=d.renderGroup??d.parentRenderGroup;g&&(g.structureDidChange=!0)}u.unload(),u._gcData=null,u._gcLastUsed=-1}else a&&(a[h]=u)}a&&(s[r]=a)}destroy(){this.enabled=!1,this._managedResources.forEach(e=>{e.off("unload",this.removeResource,this)}),this._managedResources.length=0,this._managedResourceHashes.length=0,this._managedCollections.length=0,this._renderer=null}};ho.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"gc",priority:0},ho.defaultOptions={gcActive:!0,gcMaxUnusedTime:6e4,gcFrequency:3e4};let ay=ho;class gh{constructor(e){this._stackIndex=0,this._globalUniformDataStack=[],this._uniformsPool=[],this._activeUniforms=[],this._bindGroupPool=[],this._activeBindGroups=[],this._renderer=e}reset(){this._stackIndex=0;for(let e=0;e<this._activeUniforms.length;e++)this._uniformsPool.push(this._activeUniforms[e]);for(let e=0;e<this._activeBindGroups.length;e++)this._bindGroupPool.push(this._activeBindGroups[e]);this._activeUniforms.length=0,this._activeBindGroups.length=0}start(e){this.reset(),this.push(e)}bind({size:e,projectionMatrix:t,worldTransformMatrix:s,worldColor:r,offset:n}){const o=this._renderer.renderTarget.renderTarget,a=this._stackIndex?this._globalUniformDataStack[this._stackIndex-1]:{worldTransformMatrix:new H,worldColor:4294967295,offset:new ye},l={projectionMatrix:t||this._renderer.renderTarget.projectionMatrix,resolution:e||o.size,worldTransformMatrix:s||a.worldTransformMatrix,worldColor:r||a.worldColor,offset:n||a.offset,bindGroup:null},c=this._uniformsPool.pop()||this._createUniforms();this._activeUniforms.push(c);const h=c.uniforms;h.uProjectionMatrix=l.projectionMatrix,h.uResolution=l.resolution,h.uWorldTransformMatrix.copyFrom(l.worldTransformMatrix),h.uWorldTransformMatrix.tx-=l.offset.x,h.uWorldTransformMatrix.ty-=l.offset.y,Yc(l.worldColor,h.uWorldColorAlpha,0),c.update();let u;this._renderer.renderPipes.uniformBatch?u=this._renderer.renderPipes.uniformBatch.getUniformBindGroup(c,!1):(u=this._bindGroupPool.pop()||new Nt,this._activeBindGroups.push(u),u.setResource(c,0)),l.bindGroup=u,this._currentGlobalUniformData=l}push(e){this.bind(e),this._globalUniformDataStack[this._stackIndex++]=this._currentGlobalUniformData}pop(){this._currentGlobalUniformData=this._globalUniformDataStack[--this._stackIndex-1],this._renderer.type===_t.WEBGL&&this._currentGlobalUniformData.bindGroup.resources[0].update()}get bindGroup(){return this._currentGlobalUniformData.bindGroup}get globalUniformData(){return this._currentGlobalUniformData}get uniformGroup(){return this._currentGlobalUniformData.bindGroup.resources[0]}_createUniforms(){return new gt({uProjectionMatrix:{value:new H,type:"mat3x3<f32>"},uWorldTransformMatrix:{value:new H,type:"mat3x3<f32>"},uWorldColorAlpha:{value:new Float32Array(4),type:"vec4<f32>"},uResolution:{value:[0,0],type:"vec2<f32>"}},{isStatic:!0})}destroy(){this._renderer=null,this._globalUniformDataStack.length=0,this._uniformsPool.length=0,this._activeUniforms.length=0,this._bindGroupPool.length=0,this._activeBindGroups.length=0,this._currentGlobalUniformData=null}}gh.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"globalUniforms"};let ly=1;class _h{constructor(){this._tasks=[],this._offset=0}init(){at.system.add(this._update,this)}repeat(e,t,s=!0){const r=ly++;let n=0;return s&&(this._offset+=1e3,n=this._offset),this._tasks.push({func:e,duration:t,start:performance.now(),offset:n,last:performance.now(),repeat:!0,id:r}),r}cancel(e){for(let t=0;t<this._tasks.length;t++)if(this._tasks[t].id===e){this._tasks.splice(t,1);return}}_update(){const e=performance.now();for(let t=0;t<this._tasks.length;t++){const s=this._tasks[t];if(e-s.offset-s.last>=s.duration){const r=e-s.start;s.func(r),s.last=e}}}destroy(){at.system.remove(this._update,this),this._tasks.length=0}}_h.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"scheduler",priority:0};let yh=!1;function cy(i){if(!yh){if(pe.get().getNavigator().userAgent.toLowerCase().indexOf("chrome")>-1){const e=[`%c %c %c %c %c PixiJS %c v${Qi} (${i}) http://www.pixijs.com/
|
|
558
|
+
`}},U_=new Ye;class G_ extends Li{constructor(){super(),this.filters=[new A_({sprite:new Dt(j.EMPTY),inverse:!1,resolution:"inherit",antialias:"inherit"})]}get sprite(){return this.filters[0].sprite}set sprite(e){this.filters[0].sprite=e}get inverse(){return this.filters[0].inverse}set inverse(e){this.filters[0].inverse=e}}class Jn{constructor(e){this._activeMaskStage=[],this._renderer=e}push(e,t,s){const r=this._renderer;if(r.renderPipes.batch.break(s),s.add({renderPipeId:"alphaMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1,maskedContainer:t}),e.inverse=t._maskOptions.inverse,e.renderMaskToTexture){const n=e.mask;n.includeInBuild=!0,n.collectRenderables(s,r,null),n.includeInBuild=!1}r.renderPipes.batch.break(s),s.add({renderPipeId:"alphaMask",action:"pushMaskEnd",mask:e,maskedContainer:t,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"alphaMask",action:"popMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){const t=this._renderer,s=e.mask.renderMaskToTexture;if(e.action==="pushMaskBegin"){const r=Le.get(G_);if(r.inverse=e.inverse,s){e.mask.mask.measurable=!0;const n=Yr(e.mask.mask,!0,U_);e.mask.mask.measurable=!1,n.ceil();const o=t.renderTarget.renderTarget.colorTexture.source,a=Qe.getOptimalTexture(n.width,n.height,o._resolution,o.antialias);t.renderTarget.push(a,!0),t.globalUniforms.push({offset:n,worldColor:4294967295});const l=r.sprite;l.texture=a,l.worldTransform.tx=n.minX,l.worldTransform.ty=n.minY,this._activeMaskStage.push({filterEffect:r,maskedContainer:e.maskedContainer,filterTexture:a})}else r.sprite=e.mask.mask,this._activeMaskStage.push({filterEffect:r,maskedContainer:e.maskedContainer})}else if(e.action==="pushMaskEnd"){const r=this._activeMaskStage[this._activeMaskStage.length-1];s&&(t.type===_t.WEBGL&&t.renderTarget.finishRenderPass(),t.renderTarget.pop(),t.globalUniforms.pop()),t.filter.push({renderPipeId:"filter",action:"pushFilter",container:r.maskedContainer,filterEffect:r.filterEffect,canBundle:!1})}else if(e.action==="popMaskEnd"){t.filter.pop();const r=this._activeMaskStage.pop();s&&Qe.returnTexture(r.filterTexture),Le.return(r.filterEffect)}}destroy(){this._renderer=null,this._activeMaskStage=null}}Jn.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"alphaMask"};class sh{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,s){this._renderer.renderPipes.batch.break(s);const r=this._colorStack;r[this._colorStackIndex]=r[this._colorStackIndex-1]&e.mask;const n=this._colorStack[this._colorStackIndex];n!==this._currentColor&&(this._currentColor=n,s.add({renderPipeId:"colorMask",colorMask:n,canBundle:!1})),this._colorStackIndex++}pop(e,t,s){this._renderer.renderPipes.batch.break(s);const r=this._colorStack;this._colorStackIndex--;const n=r[this._colorStackIndex-1];n!==this._currentColor&&(this._currentColor=n,s.add({renderPipeId:"colorMask",colorMask:n,canBundle:!1}))}execute(e){}destroy(){this._renderer=null,this._colorStack=null}}sh.extension={type:[A.CanvasPipes],name:"colorMask"};class ih{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,s){this._renderer.renderPipes.batch.break(s);const n=this._colorStack;n[this._colorStackIndex]=n[this._colorStackIndex-1]&e.mask;const o=this._colorStack[this._colorStackIndex];o!==this._currentColor&&(this._currentColor=o,s.add({renderPipeId:"colorMask",colorMask:o,canBundle:!1})),this._colorStackIndex++}pop(e,t,s){this._renderer.renderPipes.batch.break(s);const n=this._colorStack;this._colorStackIndex--;const o=n[this._colorStackIndex-1];o!==this._currentColor&&(this._currentColor=o,s.add({renderPipeId:"colorMask",colorMask:o,canBundle:!1}))}execute(e){this._renderer.colorMask.setMask(e.colorMask)}destroy(){this._renderer=null,this._colorStack=null}}ih.extension={type:[A.WebGLPipes,A.WebGPUPipes],name:"colorMask"};function F_(i,e,t,s,r,n){n=Math.max(0,Math.min(n,Math.min(s,r)/2)),i.moveTo(e+n,t),i.lineTo(e+s-n,t),i.quadraticCurveTo(e+s,t,e+s,t+n),i.lineTo(e+s,t+r-n),i.quadraticCurveTo(e+s,t+r,e+s-n,t+r),i.lineTo(e+n,t+r),i.quadraticCurveTo(e,t+r,e,t+r-n),i.lineTo(e,t+n),i.quadraticCurveTo(e,t,e+n,t)}function rh(i,e){switch(e.type){case"rectangle":{const t=e;i.rect(t.x,t.y,t.width,t.height);break}case"roundedRectangle":{const t=e;F_(i,t.x,t.y,t.width,t.height,t.radius);break}case"circle":{const t=e;i.moveTo(t.x+t.radius,t.y),i.arc(t.x,t.y,t.radius,0,Math.PI*2);break}case"ellipse":{const t=e;i.ellipse?(i.moveTo(t.x+t.halfWidth,t.y),i.ellipse(t.x,t.y,t.halfWidth,t.halfHeight,0,0,Math.PI*2)):(i.save(),i.translate(t.x,t.y),i.scale(t.halfWidth,t.halfHeight),i.moveTo(1,0),i.arc(0,0,1,0,Math.PI*2),i.restore());break}case"triangle":{const t=e;i.moveTo(t.x,t.y),i.lineTo(t.x2,t.y2),i.lineTo(t.x3,t.y3),i.closePath();break}case"polygon":default:{const t=e,s=t.points;if(!(s!=null&&s.length))break;i.moveTo(s[0],s[1]);for(let r=2;r<s.length;r+=2)i.lineTo(s[r],s[r+1]);t.closePath&&i.closePath();break}}}function L_(i,e){if(!(e!=null&&e.length))return!1;for(let t=0;t<e.length;t++){const s=e[t];if(!(s!=null&&s.shape))continue;const r=s.transform,n=r&&!r.isIdentity();n&&(i.save(),i.transform(r.a,r.b,r.c,r.d,r.tx,r.ty)),rh(i,s.shape),n&&i.restore()}return!0}class nh{constructor(e){this._warnedMaskTypes=new Set,this._canvasMaskStack=[],this._renderer=e}push(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"stencilMask",action:"popMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){var h,u,p;if(e.action!=="pushMaskBegin"&&e.action!=="popMaskEnd")return;const t=this._renderer,s=t.canvasContext,r=s==null?void 0:s.activeContext;if(!r)return;if(e.action==="popMaskEnd"){this._canvasMaskStack.pop()&&r.restore();return}e.inverse&&this._warnOnce("inverse","CanvasRenderer: inverse masks are not supported on Canvas2D; ignoring inverse flag.");const n=e.mask.mask;if(!(n instanceof rr)){this._warnOnce("nonGraphics","CanvasRenderer: only Graphics masks are supported in Canvas2D; skipping mask."),this._canvasMaskStack.push(!1);return}const o=n,a=(h=o.context)==null?void 0:h.instructions;if(!(a!=null&&a.length)){this._canvasMaskStack.push(!1);return}r.save(),s.setContextTransform(o.groupTransform,(t._roundPixels|o._roundPixels)===1),r.beginPath();let l=!1,c=!1;for(let d=0;d<a.length;d++){const g=a[d],_=g.action;if(_!=="fill"&&_!=="stroke")continue;const b=g.data,v=(u=b==null?void 0:b.path)==null?void 0:u.shapePath;if(!((p=v==null?void 0:v.shapePrimitives)!=null&&p.length))continue;const C=v.shapePrimitives;for(let E=0;E<C.length;E++){const S=C[E];if(!(S!=null&&S.shape))continue;const w=S.transform,R=w&&!w.isIdentity();R&&(r.save(),r.transform(w.a,w.b,w.c,w.d,w.tx,w.ty)),rh(r,S.shape),c=L_(r,S.holes)||c,l=!0,R&&r.restore()}}if(!l){r.restore(),this._canvasMaskStack.push(!1);return}c?r.clip("evenodd"):r.clip(),this._canvasMaskStack.push(!0)}destroy(){this._renderer=null,this._warnedMaskTypes=null,this._canvasMaskStack=null}_warnOnce(e,t){this._warnedMaskTypes.has(e)||(this._warnedMaskTypes.add(e),ie(t))}}nh.extension={type:[A.CanvasPipes],name:"stencilMask"};class oh{constructor(e){this._maskStackHash={},this._maskHash=new WeakMap,this._renderer=e}push(e,t,s){var r;const n=e,o=this._renderer;o.renderPipes.batch.break(s),o.renderPipes.blendMode.setBlendMode(n.mask,"none",s),s.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1});const a=n.mask;a.includeInBuild=!0,this._maskHash.has(n)||this._maskHash.set(n,{instructionsStart:0,instructionsLength:0});const l=this._maskHash.get(n);l.instructionsStart=s.instructionSize,a.collectRenderables(s,o,null),a.includeInBuild=!1,o.renderPipes.batch.break(s),s.add({renderPipeId:"stencilMask",action:"pushMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1});const c=s.instructionSize-l.instructionsStart-1;l.instructionsLength=c;const h=o.renderTarget.renderTarget.uid;(r=this._maskStackHash)[h]??(r[h]=0)}pop(e,t,s){const r=e,n=this._renderer;n.renderPipes.batch.break(s),n.renderPipes.blendMode.setBlendMode(r.mask,"none",s),s.add({renderPipeId:"stencilMask",action:"popMaskBegin",inverse:t._maskOptions.inverse,canBundle:!1});const o=this._maskHash.get(e);for(let a=0;a<o.instructionsLength;a++)s.instructions[s.instructionSize++]=s.instructions[o.instructionsStart++];s.add({renderPipeId:"stencilMask",action:"popMaskEnd",canBundle:!1})}execute(e){var t;const s=this._renderer,r=s,n=s.renderTarget.renderTarget.uid;let o=(t=this._maskStackHash)[n]??(t[n]=0);e.action==="pushMaskBegin"?(r.renderTarget.ensureDepthStencil(),r.stencil.setStencilMode(ke.RENDERING_MASK_ADD,o),o++,r.colorMask.setMask(0)):e.action==="pushMaskEnd"?(e.inverse?r.stencil.setStencilMode(ke.INVERSE_MASK_ACTIVE,o):r.stencil.setStencilMode(ke.MASK_ACTIVE,o),r.colorMask.setMask(15)):e.action==="popMaskBegin"?(r.colorMask.setMask(0),o!==0?r.stencil.setStencilMode(ke.RENDERING_MASK_REMOVE,o):(r.renderTarget.clear(null,st.STENCIL),r.stencil.setStencilMode(ke.DISABLED,o)),o--):e.action==="popMaskEnd"&&(e.inverse?r.stencil.setStencilMode(ke.INVERSE_MASK_ACTIVE,o):r.stencil.setStencilMode(ke.MASK_ACTIVE,o),r.colorMask.setMask(15)),this._maskStackHash[n]=o}destroy(){this._renderer=null,this._maskStackHash=null,this._maskHash=null}}oh.extension={type:[A.WebGLPipes,A.WebGPUPipes],name:"stencilMask"};const ge="source-over";function W_(){const i=Zc(),e=Object.create(null);return e.inherit=ge,e.none=ge,e.normal="source-over",e.add="lighter",e.multiply=i?"multiply":ge,e.screen=i?"screen":ge,e.overlay=i?"overlay":ge,e.darken=i?"darken":ge,e.lighten=i?"lighten":ge,e["color-dodge"]=i?"color-dodge":ge,e["color-burn"]=i?"color-burn":ge,e["hard-light"]=i?"hard-light":ge,e["soft-light"]=i?"soft-light":ge,e.difference=i?"difference":ge,e.exclusion=i?"exclusion":ge,e.saturation=i?"saturation":ge,e.color=i?"color":ge,e.luminosity=i?"luminosity":ge,e["linear-burn"]=i?"color-burn":ge,e["linear-dodge"]=i?"color-dodge":ge,e["linear-light"]=i?"hard-light":ge,e["pin-light"]=i?"hard-light":ge,e["vivid-light"]=i?"hard-light":ge,e["hard-mix"]=ge,e.negation=i?"difference":ge,e["normal-npm"]=e.normal,e["add-npm"]=e.add,e["screen-npm"]=e.screen,e.erase="destination-out",e.subtract=ge,e.divide=ge,e.min=ge,e.max=ge,e}const H_=new H;class ah{constructor(e){this.activeResolution=1,this.smoothProperty="imageSmoothingEnabled",this.blendModes=W_(),this._activeBlendMode="normal",this._projTransform=null,this._outerBlend=!1,this._warnedBlendModes=new Set,this._renderer=e}resolutionChange(e){this.activeResolution=e}init(){const e=this._renderer.background.alpha<1;if(this.rootContext=this._renderer.canvas.getContext("2d",{alpha:e}),this.activeContext=this.rootContext,this.activeResolution=this._renderer.resolution,!this.rootContext.imageSmoothingEnabled){const t=this.rootContext;t.webkitImageSmoothingEnabled?this.smoothProperty="webkitImageSmoothingEnabled":t.mozImageSmoothingEnabled?this.smoothProperty="mozImageSmoothingEnabled":t.oImageSmoothingEnabled?this.smoothProperty="oImageSmoothingEnabled":t.msImageSmoothingEnabled&&(this.smoothProperty="msImageSmoothingEnabled")}}setContextTransform(e,t,s,r){var c;const n=r?H.IDENTITY:((c=this._renderer.globalUniforms.globalUniformData)==null?void 0:c.worldTransformMatrix)||H.IDENTITY;let o=H_;o.copyFrom(n),o.append(e);const a=this._projTransform,l=this.activeResolution;if(s=s||l,a){const h=H.shared;h.copyFrom(o),h.prepend(a),o=h}t?this.activeContext.setTransform(o.a*s,o.b*s,o.c*s,o.d*s,o.tx*l|0,o.ty*l|0):this.activeContext.setTransform(o.a*s,o.b*s,o.c*s,o.d*s,o.tx*l,o.ty*l)}clear(e,t){const s=this.activeContext,r=this._renderer;if(s.clearRect(0,0,r.width,r.height),e){const n=Pe.shared.setValue(e);s.globalAlpha=t??n.alpha,s.fillStyle=n.toHex(),s.fillRect(0,0,r.width,r.height),s.globalAlpha=1}}setBlendMode(e){if(this._activeBlendMode===e)return;this._activeBlendMode=e,this._outerBlend=!1;const t=this.blendModes[e];if(!t){this._warnedBlendModes.has(e)||(console.warn(`CanvasRenderer: blend mode "${e}" is not supported in Canvas2D; falling back to "source-over".`),this._warnedBlendModes.add(e)),this.activeContext.globalCompositeOperation="source-over";return}this.activeContext.globalCompositeOperation=t}destroy(){this.rootContext=null,this.activeContext=null,this._warnedBlendModes.clear()}}ah.extension={type:[A.CanvasSystem],name:"canvasContext"};class lh{constructor(){this.maxTextures=16,this.maxBatchableTextures=16,this.maxUniformBindings=0}init(){}}lh.extension={type:[A.CanvasSystem],name:"limits"};class Qn{constructor(e){this._renderer=e}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}addRenderable(e,t){this._renderer.renderPipes.batch.break(t),t.add(e)}execute(e){e.isRenderable&&e.render(this._renderer)}destroy(){this._renderer=null}}Qn.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"customRender"};function eo(i,e){const t=i.instructionSet,s=t.instructions;for(let r=0;r<t.instructionSize;r++){const n=s[r];e[n.renderPipeId].execute(n)}}class to{constructor(e){this._renderer=e}addRenderGroup(e,t){e.isCachedAsTexture?this._addRenderableCacheAsTexture(e,t):this._addRenderableDirect(e,t)}execute(e){e.isRenderable&&(e.isCachedAsTexture?this._executeCacheAsTexture(e):this._executeDirect(e))}destroy(){this._renderer=null}_addRenderableDirect(e,t){this._renderer.renderPipes.batch.break(t),e._batchableRenderGroup&&(Le.return(e._batchableRenderGroup),e._batchableRenderGroup=null),t.add(e)}_addRenderableCacheAsTexture(e,t){const s=e._batchableRenderGroup??(e._batchableRenderGroup=Le.get(Qc));s.renderable=e.root,s.transform=e.root.relativeGroupTransform,s.texture=e.texture,s.bounds=e._textureBounds,t.add(e),this._renderer.renderPipes.blendMode.pushBlendMode(e,e.root.groupBlendMode,t),this._renderer.renderPipes.batch.addToBatch(s,t),this._renderer.renderPipes.blendMode.popBlendMode(t)}_executeCacheAsTexture(e){if(e.textureNeedsUpdate){e.textureNeedsUpdate=!1;const t=new H().translate(-e._textureBounds.x,-e._textureBounds.y);this._renderer.renderTarget.push(e.texture,!0,null,e.texture.frame),this._renderer.globalUniforms.push({worldTransformMatrix:t,worldColor:4294967295,offset:{x:0,y:0}}),eo(e,this._renderer.renderPipes),this._renderer.renderTarget.finishRenderPass(),this._renderer.renderTarget.pop(),this._renderer.globalUniforms.pop()}e._batchableRenderGroup._batcher.updateElement(e._batchableRenderGroup),e._batchableRenderGroup._batcher.geometry.buffers[0].update()}_executeDirect(e){this._renderer.globalUniforms.push({worldTransformMatrix:e.inverseParentTextureTransform,worldColor:e.worldColorAlpha}),eo(e,this._renderer.renderPipes),this._renderer.globalUniforms.pop()}}to.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"renderGroup"};const V_="#808080",ar=new H,z_=new H,$_=new H,so=new H;function j_(i,e,t){i.beginPath();for(let s=0;s<t.length;s+=3){const r=t[s]*2,n=t[s+1]*2,o=t[s+2]*2;i.moveTo(e[r],e[r+1]),i.lineTo(e[n],e[n+1]),i.lineTo(e[o],e[o+1]),i.closePath()}i.fill()}function X_(i){return`#${(i&16777215).toString(16).padStart(6,"0")}`}function Y_(i,e,t,s,r,n){n=Math.max(0,Math.min(n,Math.min(s,r)/2)),i.moveTo(e+n,t),i.lineTo(e+s-n,t),i.quadraticCurveTo(e+s,t,e+s,t+n),i.lineTo(e+s,t+r-n),i.quadraticCurveTo(e+s,t+r,e+s-n,t+r),i.lineTo(e+n,t+r),i.quadraticCurveTo(e,t+r,e,t+r-n),i.lineTo(e,t+n),i.quadraticCurveTo(e,t,e+n,t)}function lr(i,e){switch(e.type){case"rectangle":{const t=e;i.rect(t.x,t.y,t.width,t.height);break}case"roundedRectangle":{const t=e;Y_(i,t.x,t.y,t.width,t.height,t.radius);break}case"circle":{const t=e;i.arc(t.x,t.y,t.radius,0,Math.PI*2);break}case"ellipse":{const t=e;i.ellipse?i.ellipse(t.x,t.y,t.halfWidth,t.halfHeight,0,0,Math.PI*2):(i.save(),i.translate(t.x,t.y),i.scale(t.halfWidth,t.halfHeight),i.arc(0,0,1,0,Math.PI*2),i.restore());break}case"triangle":{const t=e;i.moveTo(t.x,t.y),i.lineTo(t.x2,t.y2),i.lineTo(t.x3,t.y3),i.closePath();break}case"polygon":default:{const t=e,s=t.points;if(!(s!=null&&s.length))break;i.moveTo(s[0],s[1]);for(let r=2;r<s.length;r+=2)i.lineTo(s[r],s[r+1]);t.closePath&&i.closePath();break}}}function q_(i,e){if(!(e!=null&&e.length))return!1;for(let t=0;t<e.length;t++){const s=e[t];if(!(s!=null&&s.shape))continue;const r=s.transform,n=r&&!r.isIdentity();n&&(i.save(),i.transform(r.a,r.b,r.c,r.d,r.tx,r.ty)),lr(i,s.shape),n&&i.restore()}return!0}function K_(i,e,t,s){const r=i.fill;if(r instanceof As){r.buildGradient();const o=r.texture;if(o){const a=ne.getTintedPattern(o,e),l=t?so.copyFrom(t).scale(o.source.pixelWidth,o.source.pixelHeight):so.copyFrom(r.transform);return s&&!i.textureSpace&&l.append(s),ne.applyPatternTransform(a,l),a}}if(r instanceof Oc){const o=ne.getTintedPattern(r.texture,e);return ne.applyPatternTransform(o,r.transform),o}const n=i.texture;if(n&&n!==j.WHITE){if(!n.source.resource)return V_;const o=ne.getTintedPattern(n,e),a=t?so.copyFrom(t).scale(n.source.pixelWidth,n.source.pixelHeight):i.matrix;return ne.applyPatternTransform(o,a),o}return X_(e)}class ch{constructor(){this.shader=null}contextChange(e){}execute(e,t){var C,E,S,w,R,M,D;const s=e.renderer,r=s.canvasContext,n=r.activeContext,o=t.groupTransform,a=((C=s.globalUniforms.globalUniformData)==null?void 0:C.worldColor)??4294967295,l=t.groupColorAlpha,c=(a>>>24&255)/255,h=(l>>>24&255)/255,u=((E=s.filter)==null?void 0:E.alphaMultiplier)??1,p=c*h*u;if(p<=0)return;const d=a&16777215,g=l&16777215,_=_s(gs(g,d)),b=s._roundPixels|t._roundPixels;n.save(),r.setContextTransform(o,b===1),r.setBlendMode(t.groupBlendMode);const v=t.context.instructions;for(let G=0;G<v.length;G++){const k=v[G];if(k.action==="texture"){const q=k.data,N=q.image,K=N?ne.getCanvasSource(N):null;if(!K)continue;const Z=q.alpha*p;if(Z<=0)continue;const $=gs(q.style,_);n.globalAlpha=Z;let ae=K;$!==16777215&&(ae=ne.getTintedCanvas({texture:N},$));const xe=N.frame,Se=N.source._resolution??N.source.resolution??1;let F=xe.x*Se,fe=xe.y*Se;const le=xe.width*Se,L=xe.height*Se;ae!==K&&(F=0,fe=0);const me=q.transform,Y=me&&!me.isIdentity(),se=N.rotate;Y||se?(ar.copyFrom(o),Y&&ar.append(me),se&&re.matrixAppendRotationInv(ar,se,q.dx,q.dy,q.dw,q.dh),r.setContextTransform(ar,b===1)):r.setContextTransform(o,b===1),n.drawImage(ae,F,fe,ae===K?le:ae.width,ae===K?L:ae.height,se?0:q.dx,se?0:q.dy,q.dw,q.dh),(Y||se)&&r.setContextTransform(o,b===1);continue}const O=k.data,V=(S=O==null?void 0:O.path)==null?void 0:S.shapePath;if(!((w=V==null?void 0:V.shapePrimitives)!=null&&w.length))continue;const X=O.style,z=gs(X.color,_),de=X.alpha*p;if(de<=0)continue;const B=k.action==="stroke";if(n.globalAlpha=de,B){const q=X;n.lineWidth=q.width,n.lineCap=q.cap,n.lineJoin=q.join,n.miterLimit=q.miterLimit}const U=V.shapePrimitives;if(!B&&((D=(M=(R=O.hole)==null?void 0:R.shapePath)==null?void 0:M.shapePrimitives)!=null&&D.length)){const q=U[U.length-1];q.holes=O.hole.shapePath.shapePrimitives}for(let q=0;q<U.length;q++){const N=U[q];if(!(N!=null&&N.shape))continue;const K=N.transform,Z=K&&!K.isIdentity(),$=X.texture&&X.texture!==j.WHITE,ae=X.textureSpace==="global"?K:null,xe=$?xc(z_,X,N.shape,ae):null,Se=Z?$_.copyFrom(o).append(K):o,F=K_(X,z,xe,Se);if(Z&&(n.save(),n.transform(K.a,K.b,K.c,K.d,K.tx,K.ty)),B){const fe=X;if(fe.alignment!==.5&&!fe.pixelLine){const L=[],me=[],Y=[],se=ui[N.shape.type];if(se!=null&&se.build(N.shape,L)){const we=N.shape.closePath??!0;gc(L,fe,!1,we,me,Y),n.fillStyle=F,j_(n,me,Y)}else n.strokeStyle=F,n.beginPath(),lr(n,N.shape),n.stroke()}else n.strokeStyle=F,n.beginPath(),lr(n,N.shape),n.stroke()}else n.fillStyle=F,n.beginPath(),lr(n,N.shape),q_(n,N.holes)?n.fill("evenodd"):n.fill();Z&&n.restore()}}n.restore()}destroy(){this.shader=null}}ch.extension={type:[A.CanvasPipesAdaptor],name:"graphics"};class io{constructor(e){this._renderer=e}addRenderable(e,t){const s=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,s),this._renderer.renderPipes.batch.addToBatch(s,t)}updateRenderable(e){const t=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,t),t._batcher.updateElement(t)}validateRenderable(e){const t=this._getGpuSprite(e);return!t._batcher.checkAndUpdateTexture(t,e._texture)}_updateBatchableSprite(e,t){t.bounds=e.visualBounds,t.texture=e._texture}_getGpuSprite(e){return e._gpuData[this._renderer.uid]||this._initGPUSprite(e)}_initGPUSprite(e){const t=new Qc;return t.renderable=e,t.transform=e.groupTransform,t.texture=e._texture,t.bounds=e.visualBounds,t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,t}destroy(){this._renderer=null}}io.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"sprite"};const _i={};Q.handle(A.BlendMode,i=>{if(!i.name)throw new Error("BlendMode extension must have a name property");_i[i.name]=i.ref},i=>{delete _i[i.name]});class ro{constructor(e){this._blendModeStack=[],this._isAdvanced=!1,this._filterHash=Object.create(null),this._renderer=e,this._renderer.runners.prerender.add(this)}prerender(){this._activeBlendMode="normal",this._isAdvanced=!1}pushBlendMode(e,t,s){this._blendModeStack.push(t),this.setBlendMode(e,t,s)}popBlendMode(e){this._blendModeStack.pop();const t=this._blendModeStack[this._activeBlendMode.length-1]??"normal";this.setBlendMode(null,t,e)}setBlendMode(e,t,s){var n;const r=e instanceof Jr;if(this._activeBlendMode===t){this._isAdvanced&&e&&!r&&((n=this._renderableList)==null||n.push(e));return}this._isAdvanced&&this._endAdvancedBlendMode(s),this._activeBlendMode=t,e&&(this._isAdvanced=!!_i[t],this._isAdvanced&&this._beginAdvancedBlendMode(e,s))}_beginAdvancedBlendMode(e,t){this._renderer.renderPipes.batch.break(t);const s=this._activeBlendMode;if(!_i[s]){ie(`Unable to assign BlendMode: '${s}'. You may want to include: import 'pixi.js/advanced-blend-modes'`);return}const r=this._ensureFilterEffect(s),n=e instanceof Jr,o={renderPipeId:"filter",action:"pushFilter",filterEffect:r,renderables:n?null:[e],container:n?e.root:null,canBundle:!1};this._renderableList=o.renderables,t.add(o)}_ensureFilterEffect(e){let t=this._filterHash[e];return t||(t=this._filterHash[e]=new Li,t.filters=[new _i[e]]),t}_endAdvancedBlendMode(e){this._isAdvanced=!1,this._renderableList=null,this._renderer.renderPipes.batch.break(e),e.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}buildStart(){this._isAdvanced=!1}buildEnd(e){this._isAdvanced&&this._endAdvancedBlendMode(e)}destroy(){this._renderer=null,this._renderableList=null;for(const e in this._filterHash)this._filterHash[e].destroy();this._filterHash=null}}ro.extension={type:[A.WebGLPipes,A.WebGPUPipes,A.CanvasPipes],name:"blendMode"};function no(i,e){e||(e=0);for(let t=e;t<i.length&&i[t];t++)i[t]=null}const Z_=new Ve,hh=js|zi|tn;function uh(i,e=!1){J_(i);const t=i.childrenToUpdate,s=i.updateTick++;for(const r in t){const n=Number(r),o=t[r],a=o.list,l=o.index;for(let c=0;c<l;c++){const h=a[c];h.parentRenderGroup===i&&h.relativeRenderGroupDepth===n&&dh(h,s,0)}no(a,l),o.index=0}if(e)for(let r=0;r<i.renderGroupChildren.length;r++)uh(i.renderGroupChildren[r],e)}function J_(i){const e=i.root;let t;if(i.renderGroupParent){const s=i.renderGroupParent;i.worldTransform.appendFrom(e.relativeGroupTransform,s.worldTransform),i.worldColor=Wi(e.groupColor,s.worldColor),t=e.groupAlpha*s.worldAlpha}else i.worldTransform.copyFrom(e.localTransform),i.worldColor=e.localColor,t=e.localAlpha;t=t<0?0:t>1?1:t,i.worldAlpha=t,i.worldColorAlpha=i.worldColor+((t*255|0)<<24)}function dh(i,e,t){if(e===i.updateTick)return;i.updateTick=e,i.didChange=!1;const s=i.localTransform;i.updateLocalTransform();const r=i.parent;if(r&&!r.renderGroup?(t|=i._updateFlags,i.relativeGroupTransform.appendFrom(s,r.relativeGroupTransform),t&hh&&fh(i,r,t)):(t=i._updateFlags,i.relativeGroupTransform.copyFrom(s),t&hh&&fh(i,Z_,t)),!i.renderGroup){const n=i.children,o=n.length;for(let c=0;c<o;c++)dh(n[c],e,t);const a=i.parentRenderGroup,l=i;l.renderPipeId&&!a.structureDidChange&&a.updateRenderable(l)}}function fh(i,e,t){if(t&zi){i.groupColor=Wi(i.localColor,e.groupColor);let s=i.localAlpha*e.groupAlpha;s=s<0?0:s>1?1:s,i.groupAlpha=s,i.groupColorAlpha=i.groupColor+((s*255|0)<<24)}t&tn&&(i.groupBlendMode=i.localBlendMode==="inherit"?e.groupBlendMode:i.localBlendMode),t&js&&(i.globalDisplayStatus=i.localDisplayStatus&e.globalDisplayStatus),i._updateFlags=0}function Q_(i,e){const{list:t}=i.childrenRenderablesToUpdate;let s=!1;for(let r=0;r<i.childrenRenderablesToUpdate.index;r++){const n=t[r];if(s=e[n.renderPipeId].validateRenderable(n),s)break}return i.structureDidChange=s,s}const ey=new H;class ph{constructor(e){this._renderer=e}render({container:e,transform:t}){const s=e.parent,r=e.renderGroup.renderGroupParent;e.parent=null,e.renderGroup.renderGroupParent=null;const n=this._renderer,o=ey;t&&(o.copyFrom(e.renderGroup.localTransform),e.renderGroup.localTransform.copyFrom(t));const a=n.renderPipes;this._updateCachedRenderGroups(e.renderGroup,null),this._updateRenderGroups(e.renderGroup),n.globalUniforms.start({worldTransformMatrix:t?e.renderGroup.localTransform:e.renderGroup.worldTransform,worldColor:e.renderGroup.worldColorAlpha}),eo(e.renderGroup,a),a.uniformBatch&&a.uniformBatch.renderEnd(),t&&e.renderGroup.localTransform.copyFrom(o),e.parent=s,e.renderGroup.renderGroupParent=r}destroy(){this._renderer=null}_updateCachedRenderGroups(e,t){if(e._parentCacheAsTextureRenderGroup=t,e.isCachedAsTexture){if(!e.textureNeedsUpdate)return;t=e}for(let s=e.renderGroupChildren.length-1;s>=0;s--)this._updateCachedRenderGroups(e.renderGroupChildren[s],t);if(e.invalidateMatrices(),e.isCachedAsTexture){if(e.textureNeedsUpdate){const s=e.root.getLocalBounds(),r=this._renderer,n=e.textureOptions.resolution||r.view.resolution,o=e.textureOptions.antialias??r.view.antialias,a=e.textureOptions.scaleMode??"linear",l=e.texture;s.ceil(),e.texture&&Qe.returnTexture(e.texture,!0);const c=Qe.getOptimalTexture(s.width,s.height,n,o);c._source.style=new Fr({scaleMode:a}),e.texture=c,e._textureBounds||(e._textureBounds=new Ye),e._textureBounds.copyFrom(s),l!==e.texture&&e.renderGroupParent&&(e.renderGroupParent.structureDidChange=!0)}}else e.texture&&(Qe.returnTexture(e.texture,!0),e.texture=null)}_updateRenderGroups(e){const t=this._renderer,s=t.renderPipes;if(e.runOnRender(t),e.instructionSet.renderPipes=s,e.structureDidChange?no(e.childrenRenderablesToUpdate.list,0):Q_(e,s),uh(e),e.structureDidChange?(e.structureDidChange=!1,this._buildInstructions(e,t)):this._updateRenderables(e),e.childrenRenderablesToUpdate.index=0,t.renderPipes.batch.upload(e.instructionSet),!(e.isCachedAsTexture&&!e.textureNeedsUpdate))for(let r=0;r<e.renderGroupChildren.length;r++)this._updateRenderGroups(e.renderGroupChildren[r])}_updateRenderables(e){const{list:t,index:s}=e.childrenRenderablesToUpdate;for(let r=0;r<s;r++){const n=t[r];n.didViewUpdate&&e.updateRenderable(n)}no(t,s)}_buildInstructions(e,t){const s=e.root,r=e.instructionSet;r.reset();const n=t.renderPipes?t:t.batch.renderer,o=n.renderPipes;o.batch.buildStart(r),o.blendMode.buildStart(),o.colorMask.buildStart(),s.sortableChildren&&s.sortChildren(),s.collectRenderablesWithEffects(r,n,null),o.batch.buildEnd(r),o.blendMode.buildEnd(r)}}ph.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"renderGroup"};const oo=class _f{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new Pe(0),this.color=this._backgroundColor,this.alpha=1}init(e){e={..._f.defaultOptions,...e},this.clearBeforeRender=e.clearBeforeRender,this.color=e.background||e.backgroundColor||this._backgroundColor,this.alpha=e.backgroundAlpha,this._backgroundColor.setAlpha(e.backgroundAlpha)}get color(){return this._backgroundColor}set color(e){Pe.shared.setValue(e).alpha<1&&this._backgroundColor.alpha===1&&ie("Cannot set a transparent background on an opaque canvas. To enable transparency, set backgroundAlpha < 1 when initializing your Application."),this._backgroundColor.setValue(e)}get alpha(){return this._backgroundColor.alpha}set alpha(e){this._backgroundColor.setAlpha(e)}get colorRgba(){return this._backgroundColor.toArray()}destroy(){}};oo.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"background",priority:0},oo.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0};let ty=oo;const ao={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},lo=class yf{constructor(e){this._renderer=e}_normalizeOptions(e,t={}){return e instanceof Ve||e instanceof j?{target:e,...t}:{...t,...e}}async image(e){const t=pe.get().createImage();return t.src=await this.base64(e),t}async base64(e){e=this._normalizeOptions(e,yf.defaultImageOptions);const{format:t,quality:s}=e,r=this.canvas(e);if(r.toBlob!==void 0)return new Promise((n,o)=>{r.toBlob(a=>{if(!a){o(new Error("ICanvas.toBlob failed!"));return}const l=new FileReader;l.onload=()=>n(l.result),l.onerror=o,l.readAsDataURL(a)},ao[t],s)});if(r.toDataURL!==void 0)return r.toDataURL(ao[t],s);if(r.convertToBlob!==void 0){const n=await r.convertToBlob({type:ao[t],quality:s});return new Promise((o,a)=>{const l=new FileReader;l.onload=()=>o(l.result),l.onerror=a,l.readAsDataURL(n)})}throw new Error("Extract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented")}canvas(e){e=this._normalizeOptions(e);const t=e.target,s=this._renderer;if(t instanceof j)return s.texture.generateCanvas(t);const r=s.textureGenerator.generateTexture(e),n=s.texture.generateCanvas(r);return r.destroy(!0),n}pixels(e){e=this._normalizeOptions(e);const t=e.target,s=this._renderer,r=t instanceof j?t:s.textureGenerator.generateTexture(e),n=s.texture.getPixels(r);return t instanceof Ve&&r.destroy(!0),n}texture(e){return e=this._normalizeOptions(e),e.target instanceof j?e.target:this._renderer.textureGenerator.generateTexture(e)}download(e){e=this._normalizeOptions(e);const t=this.canvas(e),s=document.createElement("a");s.download=e.filename??"image.png",s.href=t.toDataURL("image/png"),document.body.appendChild(s),s.click(),document.body.removeChild(s)}log(e){const t=e.width??200;e=this._normalizeOptions(e);const s=this.canvas(e),r=s.toDataURL();console.log(`[Pixi Texture] ${s.width}px ${s.height}px`);const n=["font-size: 1px;",`padding: ${t}px 300px;`,`background: url(${r}) no-repeat;`,"background-size: contain;"].join(" ");console.log("%c ",n)}destroy(){this._renderer=null}};lo.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"extract"},lo.defaultImageOptions={format:"png",quality:1};let sy=lo;class co extends j{static create(e){const{dynamic:t,...s}=e;return new co({source:new De(s),dynamic:t??!1})}resize(e,t,s){return this.source.resize(e,t,s),this}}const iy=new Ce,ry=new Ye,ny=[0,0,0,0];class mh{constructor(e){this._renderer=e}generateTexture(e){var c;e instanceof Ve&&(e={target:e,frame:void 0,textureSourceOptions:{},resolution:void 0});const t=e.resolution||this._renderer.resolution,s=e.antialias||this._renderer.view.antialias,r=e.target;let n=e.clearColor;n?n=Array.isArray(n)&&n.length===4?n:Pe.shared.setValue(n).toArray():n=ny;const o=((c=e.frame)==null?void 0:c.copyTo(iy))||Kr(r,ry).rectangle;o.width=Math.max(o.width,1/t)|0,o.height=Math.max(o.height,1/t)|0;const a=co.create({...e.textureSourceOptions,width:o.width,height:o.height,resolution:t,antialias:s}),l=H.shared.translate(-o.x,-o.y);return this._renderer.render({container:r,transform:l,target:a,clearColor:n}),a.source.updateMipmaps(),a}destroy(){this._renderer=null}}mh.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"textureGenerator"};function oy(i){let e=!1;for(const s in i)if(i[s]==null){e=!0;break}if(!e)return i;const t=Object.create(null);for(const s in i){const r=i[s];r&&(t[s]=r)}return t}function ay(i){let e=0;for(let t=0;t<i.length;t++)i[t]==null?e++:i[t-e]=i[t];return i.length-=e,i}const ho=class bf{constructor(e){this._managedResources=[],this._managedResourceHashes=[],this._managedCollections=[],this._ready=!1,this._renderer=e}init(e){e={...bf.defaultOptions,...e},this.maxUnusedTime=e.gcMaxUnusedTime,this._frequency=e.gcFrequency,this.enabled=e.gcActive,this.now=performance.now()}get enabled(){return!!this._handler}set enabled(e){this.enabled!==e&&(e?(this._handler=this._renderer.scheduler.repeat(()=>{this._ready=!0},this._frequency,!1),this._collectionsHandler=this._renderer.scheduler.repeat(()=>{for(const t of this._managedCollections){const{context:s,collection:r,type:n}=t;n==="hash"?s[r]=oy(s[r]):s[r]=ay(s[r])}},this._frequency)):(this._renderer.scheduler.cancel(this._handler),this._renderer.scheduler.cancel(this._collectionsHandler),this._handler=0,this._collectionsHandler=0))}prerender({container:e}){this.now=performance.now(),e.renderGroup.gcTick=this._renderer.tick++,this._updateInstructionGCTick(e.renderGroup,e.renderGroup.gcTick)}postrender(){!this._ready||!this.enabled||(this.run(),this._ready=!1)}_updateInstructionGCTick(e,t){e.instructionSet.gcTick=t,e.gcTick=t;for(const s of e.renderGroupChildren)this._updateInstructionGCTick(s,t)}addCollection(e,t,s){this._managedCollections.push({context:e,collection:t,type:s})}addResource(e,t){var r,n;if(e._gcLastUsed!==-1){e._gcLastUsed=this.now,(r=e._onTouch)==null||r.call(e,this.now);return}const s=this._managedResources.length;e._gcData={index:s,type:t},e._gcLastUsed=this.now,(n=e._onTouch)==null||n.call(e,this.now),e.once("unload",this.removeResource,this),this._managedResources.push(e)}removeResource(e){const t=e._gcData;if(!t)return;const s=t.index,r=this._managedResources.length-1;if(s!==r){const n=this._managedResources[r];this._managedResources[s]=n,n._gcData.index=s}this._managedResources.length--,e._gcData=null,e._gcLastUsed=-1}addResourceHash(e,t,s,r=0){this._managedResourceHashes.push({context:e,hash:t,type:s,priority:r}),this._managedResourceHashes.sort((n,o)=>n.priority-o.priority)}run(){const e=performance.now(),t=this._managedResourceHashes;for(const r of t)this.runOnHash(r,e);let s=0;for(let r=0;r<this._managedResources.length;r++){const n=this._managedResources[r];s=this.runOnResource(n,e,s)}this._managedResources.length=s}updateRenderableGCTick(e,t){var n,o;const s=e.renderGroup??e.parentRenderGroup,r=((n=s==null?void 0:s.instructionSet)==null?void 0:n.gcTick)??-1;((s==null?void 0:s.gcTick)??0)===r&&(e._gcLastUsed=t,(o=e._onTouch)==null||o.call(e,t))}runOnResource(e,t,s){const r=e._gcData;return r.type==="renderable"&&this.updateRenderableGCTick(e,t),t-e._gcLastUsed<this.maxUnusedTime||!e.autoGarbageCollect?(this._managedResources[s]=e,r.index=s,s++):(e.unload(),e._gcData=null,e._gcLastUsed=-1,e.off("unload",this.removeResource,this)),s}_createHashClone(e,t){const s=Object.create(null);for(const r in e){if(r===t)break;e[r]!==null&&(s[r]=e[r])}return s}runOnHash(e,t){var c;const{context:s,hash:r,type:n}=e,o=s[r];let a=null,l=0;for(const h in o){const u=o[h];if(u===null){l++,l===1e4&&!a&&(a=this._createHashClone(o,h));continue}if(u._gcLastUsed===-1){u._gcLastUsed=t,(c=u._onTouch)==null||c.call(u,t),a&&(a[h]=u);continue}if(n==="renderable"&&this.updateRenderableGCTick(u,t),!(t-u._gcLastUsed<this.maxUnusedTime)&&u.autoGarbageCollect){if(a||(l+1!==1e4?(o[h]=null,l++):a=this._createHashClone(o,h)),n==="renderable"){const d=u,g=d.renderGroup??d.parentRenderGroup;g&&(g.structureDidChange=!0)}u.unload(),u._gcData=null,u._gcLastUsed=-1}else a&&(a[h]=u)}a&&(s[r]=a)}destroy(){this.enabled=!1,this._managedResources.forEach(e=>{e.off("unload",this.removeResource,this)}),this._managedResources.length=0,this._managedResourceHashes.length=0,this._managedCollections.length=0,this._renderer=null}};ho.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"gc",priority:0},ho.defaultOptions={gcActive:!0,gcMaxUnusedTime:6e4,gcFrequency:3e4};let ly=ho;class gh{constructor(e){this._stackIndex=0,this._globalUniformDataStack=[],this._uniformsPool=[],this._activeUniforms=[],this._bindGroupPool=[],this._activeBindGroups=[],this._renderer=e}reset(){this._stackIndex=0;for(let e=0;e<this._activeUniforms.length;e++)this._uniformsPool.push(this._activeUniforms[e]);for(let e=0;e<this._activeBindGroups.length;e++)this._bindGroupPool.push(this._activeBindGroups[e]);this._activeUniforms.length=0,this._activeBindGroups.length=0}start(e){this.reset(),this.push(e)}bind({size:e,projectionMatrix:t,worldTransformMatrix:s,worldColor:r,offset:n}){const o=this._renderer.renderTarget.renderTarget,a=this._stackIndex?this._globalUniformDataStack[this._stackIndex-1]:{worldTransformMatrix:new H,worldColor:4294967295,offset:new ye},l={projectionMatrix:t||this._renderer.renderTarget.projectionMatrix,resolution:e||o.size,worldTransformMatrix:s||a.worldTransformMatrix,worldColor:r||a.worldColor,offset:n||a.offset,bindGroup:null},c=this._uniformsPool.pop()||this._createUniforms();this._activeUniforms.push(c);const h=c.uniforms;h.uProjectionMatrix=l.projectionMatrix,h.uResolution=l.resolution,h.uWorldTransformMatrix.copyFrom(l.worldTransformMatrix),h.uWorldTransformMatrix.tx-=l.offset.x,h.uWorldTransformMatrix.ty-=l.offset.y,Yc(l.worldColor,h.uWorldColorAlpha,0),c.update();let u;this._renderer.renderPipes.uniformBatch?u=this._renderer.renderPipes.uniformBatch.getUniformBindGroup(c,!1):(u=this._bindGroupPool.pop()||new Nt,this._activeBindGroups.push(u),u.setResource(c,0)),l.bindGroup=u,this._currentGlobalUniformData=l}push(e){this.bind(e),this._globalUniformDataStack[this._stackIndex++]=this._currentGlobalUniformData}pop(){this._currentGlobalUniformData=this._globalUniformDataStack[--this._stackIndex-1],this._renderer.type===_t.WEBGL&&this._currentGlobalUniformData.bindGroup.resources[0].update()}get bindGroup(){return this._currentGlobalUniformData.bindGroup}get globalUniformData(){return this._currentGlobalUniformData}get uniformGroup(){return this._currentGlobalUniformData.bindGroup.resources[0]}_createUniforms(){return new gt({uProjectionMatrix:{value:new H,type:"mat3x3<f32>"},uWorldTransformMatrix:{value:new H,type:"mat3x3<f32>"},uWorldColorAlpha:{value:new Float32Array(4),type:"vec4<f32>"},uResolution:{value:[0,0],type:"vec2<f32>"}},{isStatic:!0})}destroy(){this._renderer=null,this._globalUniformDataStack.length=0,this._uniformsPool.length=0,this._activeUniforms.length=0,this._bindGroupPool.length=0,this._activeBindGroups.length=0,this._currentGlobalUniformData=null}}gh.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"globalUniforms"};let cy=1;class _h{constructor(){this._tasks=[],this._offset=0}init(){at.system.add(this._update,this)}repeat(e,t,s=!0){const r=cy++;let n=0;return s&&(this._offset+=1e3,n=this._offset),this._tasks.push({func:e,duration:t,start:performance.now(),offset:n,last:performance.now(),repeat:!0,id:r}),r}cancel(e){for(let t=0;t<this._tasks.length;t++)if(this._tasks[t].id===e){this._tasks.splice(t,1);return}}_update(){const e=performance.now();for(let t=0;t<this._tasks.length;t++){const s=this._tasks[t];if(e-s.offset-s.last>=s.duration){const r=e-s.start;s.func(r),s.last=e}}}destroy(){at.system.remove(this._update,this),this._tasks.length=0}}_h.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"scheduler",priority:0};let yh=!1;function hy(i){if(!yh){if(pe.get().getNavigator().userAgent.toLowerCase().indexOf("chrome")>-1){const e=[`%c %c %c %c %c PixiJS %c v${Qi} (${i}) http://www.pixijs.com/
|
|
559
559
|
|
|
560
|
-
`,"background: #E72264; padding:5px 0;","background: #6CA2EA; padding:5px 0;","background: #B5D33D; padding:5px 0;","background: #FED23F; padding:5px 0;","color: #FFFFFF; background: #E72264; padding:5px 0;","color: #E72264; background: #FFFFFF; padding:5px 0;"];globalThis.console.log(...e)}else globalThis.console&&globalThis.console.log(`PixiJS ${Qi} - ${i} - http://www.pixijs.com/`);yh=!0}}class uo{constructor(e){this._renderer=e}init(e){if(e.hello){let t=this._renderer.name;this._renderer.type===_t.WEBGL&&(t+=` ${this._renderer.context.webGLVersion}`),cy(t)}}}uo.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"hello",priority:-2},uo.defaultOptions={hello:!1};const fo=class vf{constructor(e){this._renderer=e}init(e){e={...vf.defaultOptions,...e},this.maxUnusedTime=e.renderableGCMaxUnusedTime}get enabled(){return ee("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled}set enabled(e){ee("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled=e}addManagedHash(e,t){ee("8.15.0","RenderableGCSystem.addManagedHash is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(e,t,"hash")}addManagedArray(e,t){ee("8.15.0","RenderableGCSystem.addManagedArray is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(e,t,"array")}addRenderable(e){ee("8.15.0","RenderableGCSystem.addRenderable is deprecated, please use the GCSystem instead."),this._renderer.gc.addResource(e,"renderable")}run(){ee("8.15.0","RenderableGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};fo.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"renderableGC",priority:0},fo.defaultOptions={renderableGCActive:!0,renderableGCMaxUnusedTime:6e4,renderableGCFrequency:3e4};let hy=fo;const po=class kr{get count(){return this._renderer.tick}get checkCount(){return this._checkCount}set checkCount(e){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._checkCount=e}get maxIdle(){return this._renderer.gc.maxUnusedTime/1e3*60}set maxIdle(e){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.maxUnusedTime=e/60*1e3}get checkCountMax(){return Math.floor(this._renderer.gc._frequency/1e3)}set checkCountMax(e){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead.")}get active(){return this._renderer.gc.enabled}set active(e){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.enabled=e}constructor(e){this._renderer=e,this._checkCount=0}init(e){e.textureGCActive!==kr.defaultOptions.textureGCActive&&(this.active=e.textureGCActive),e.textureGCMaxIdle!==kr.defaultOptions.textureGCMaxIdle&&(this.maxIdle=e.textureGCMaxIdle),e.textureGCCheckCountMax!==kr.defaultOptions.textureGCCheckCountMax&&(this.checkCountMax=e.textureGCCheckCountMax)}run(){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};po.extension={type:[A.WebGLSystem,A.WebGPUSystem],name:"textureGC"},po.defaultOptions={textureGCActive:!0,textureGCAMaxIdle:null,textureGCMaxIdle:3600,textureGCCheckCountMax:600};let uy=po;const bh=class xf{constructor(e={}){if(this.uid=be("renderTarget"),this.colorTextures=[],this.dirtyId=0,this.isRoot=!1,this._size=new Float32Array(2),this._managedColorTextures=!1,e={...xf.defaultOptions,...e},this.stencil=e.stencil,this.depth=e.depth,this.isRoot=e.isRoot,typeof e.colorTextures=="number"){this._managedColorTextures=!0;for(let t=0;t<e.colorTextures;t++)this.colorTextures.push(new De({width:e.width,height:e.height,resolution:e.resolution,antialias:e.antialias}))}else{this.colorTextures=[...e.colorTextures.map(s=>s.source)];const t=this.colorTexture.source;this.resize(t.width,t.height,t._resolution)}this.colorTexture.source.on("resize",this.onSourceResize,this),(e.depthStencilTexture||this.stencil)&&(e.depthStencilTexture instanceof j||e.depthStencilTexture instanceof De?this.depthStencilTexture=e.depthStencilTexture.source:this.ensureDepthStencilTexture())}get size(){const e=this._size;return e[0]=this.pixelWidth,e[1]=this.pixelHeight,e}get width(){return this.colorTexture.source.width}get height(){return this.colorTexture.source.height}get pixelWidth(){return this.colorTexture.source.pixelWidth}get pixelHeight(){return this.colorTexture.source.pixelHeight}get resolution(){return this.colorTexture.source._resolution}get colorTexture(){return this.colorTextures[0]}onSourceResize(e){this.resize(e.width,e.height,e._resolution,!0)}ensureDepthStencilTexture(){this.depthStencilTexture||(this.depthStencilTexture=new De({width:this.width,height:this.height,resolution:this.resolution,format:"depth24plus-stencil8",autoGenerateMipmaps:!1,antialias:!1,mipLevelCount:1}))}resize(e,t,s=this.resolution,r=!1){this.dirtyId++,this.colorTextures.forEach((n,o)=>{r&&o===0||n.source.resize(e,t,s)}),this.depthStencilTexture&&this.depthStencilTexture.source.resize(e,t,s)}destroy(){this.colorTexture.source.off("resize",this.onSourceResize,this),this._managedColorTextures&&this.colorTextures.forEach(e=>{e.destroy()}),this.depthStencilTexture&&(this.depthStencilTexture.destroy(),delete this.depthStencilTexture)}};bh.defaultOptions={width:0,height:0,resolution:1,colorTextures:1,stencil:!1,depth:!1,antialias:!1,isRoot:!1};let mo=bh;const Rs=new Map;ms.register(Rs);function vh(i,e){if(!Rs.has(i)){const t=new j({source:new mt({resource:i,...e})}),s=()=>{Rs.get(i)===t&&Rs.delete(i)};t.once("destroy",s),t.source.once("destroy",s),Rs.set(i,t)}return Rs.get(i)}const go=class Cf{get autoDensity(){return this.texture.source.autoDensity}set autoDensity(e){this.texture.source.autoDensity=e}get resolution(){return this.texture.source._resolution}set resolution(e){this.texture.source.resize(this.texture.source.width,this.texture.source.height,e)}init(e){e={...Cf.defaultOptions,...e},e.view&&(ee(Be,"ViewSystem.view has been renamed to ViewSystem.canvas"),e.canvas=e.view),this.screen=new Ce(0,0,e.width,e.height),this.canvas=e.canvas||pe.get().createCanvas(),this.antialias=!!e.antialias,this.texture=vh(this.canvas,e),this.renderTarget=new mo({colorTextures:[this.texture],depth:!!e.depth,isRoot:!0}),this.texture.source.transparent=e.backgroundAlpha<1,this.resolution=e.resolution}resize(e,t,s){this.texture.source.resize(e,t,s),this.screen.width=this.texture.frame.width,this.screen.height=this.texture.frame.height}destroy(e=!1){(typeof e=="boolean"?e:!!(e!=null&&e.removeView))&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.texture.destroy()}};go.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"view",priority:0},go.defaultOptions={width:800,height:600,autoDensity:!1,antialias:!1};const _o=[ey,gh,uo,go,ph,ay,uy,mh,ty,Nl,hy,_h],xh=[ro,Zn,io,to,Jn,oh,ih,Qn];function dy(i,e,t,s,r,n){const o=n?1:-1;return i.identity(),i.a=1/s*2,i.d=o*(1/r*2),i.tx=-1-e*i.a,i.ty=-o-t*i.d,i}function fy(i){const e=i.colorTexture.source.resource;return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement&&document.body.contains(e)}class yo{constructor(e){this.rootViewPort=new Ce,this.viewport=new Ce,this.mipLevel=0,this.layer=0,this.onRenderTargetChange=new kl("onRenderTargetChange"),this.projectionMatrix=new H,this.defaultClearColor=[0,0,0,0],this._renderSurfaceToRenderTargetHash=new Map,this._gpuRenderTargetHash=Object.create(null),this._renderTargetStack=[],this._renderer=e,e.gc.addCollection(this,"_gpuRenderTargetHash","hash")}finishRenderPass(){this.adaptor.finishRenderPass(this.renderTarget)}renderStart({target:e,clear:t,clearColor:s,frame:r,mipLevel:n,layer:o}){var a,l;this._renderTargetStack.length=0,this.push(e,t,s,r,n??0,o??0),this.rootViewPort.copyFrom(this.viewport),this.rootRenderTarget=this.renderTarget,this.renderingToScreen=fy(this.rootRenderTarget),(l=(a=this.adaptor).prerender)==null||l.call(a,this.rootRenderTarget)}postrender(){var e,t;(t=(e=this.adaptor).postrender)==null||t.call(e,this.rootRenderTarget)}bind(e,t=!0,s,r,n=0,o=0){const a=this.getRenderTarget(e),l=this.renderTarget!==a;this.renderTarget=a,this.renderSurface=e;const c=this.getGpuRenderTarget(a);(a.pixelWidth!==c.width||a.pixelHeight!==c.height)&&(this.adaptor.resizeGpuRenderTarget(a),c.width=a.pixelWidth,c.height=a.pixelHeight);const h=a.colorTexture,u=this.viewport,p=h.arrayLayerCount||1;if((o|0)!==o&&(o|=0),o<0||o>=p)throw new Error(`[RenderTargetSystem] layer ${o} is out of bounds (arrayLayerCount=${p}).`);this.mipLevel=n|0,this.layer=o|0;const d=Math.max(h.pixelWidth>>n,1),g=Math.max(h.pixelHeight>>n,1);if(!r&&e instanceof j&&(r=e.frame),r){const _=h._resolution,b=1<<Math.max(n|0,0),v=r.x*_+.5|0,C=r.y*_+.5|0,E=r.width*_+.5|0,S=r.height*_+.5|0;let w=Math.floor(v/b),R=Math.floor(C/b),M=Math.ceil(E/b),D=Math.ceil(S/b);w=Math.min(Math.max(w,0),d-1),R=Math.min(Math.max(R,0),g-1),M=Math.min(Math.max(M,1),d-w),D=Math.min(Math.max(D,1),g-R),u.x=w,u.y=R,u.width=M,u.height=D}else u.x=0,u.y=0,u.width=d,u.height=g;return dy(this.projectionMatrix,0,0,u.width/h.resolution,u.height/h.resolution,!a.isRoot),this.adaptor.startRenderPass(a,t,s,u,n,o),l&&this.onRenderTargetChange.emit(a),a}clear(e,t=st.ALL,s,r=this.mipLevel,n=this.layer){t&&(e&&(e=this.getRenderTarget(e)),this.adaptor.clear(e||this.renderTarget,t,s,this.viewport,r,n))}contextChange(){this._gpuRenderTargetHash=Object.create(null)}push(e,t=st.ALL,s,r,n=0,o=0){const a=this.bind(e,t,s,r,n,o);return this._renderTargetStack.push({renderTarget:a,frame:r,mipLevel:n,layer:o}),a}pop(){this._renderTargetStack.pop();const e=this._renderTargetStack[this._renderTargetStack.length-1];this.bind(e.renderTarget,!1,null,e.frame,e.mipLevel,e.layer)}getRenderTarget(e){return e.isTexture&&(e=e.source),this._renderSurfaceToRenderTargetHash.get(e)??this._initRenderTarget(e)}copyToTexture(e,t,s,r,n){s.x<0&&(r.width+=s.x,n.x-=s.x,s.x=0),s.y<0&&(r.height+=s.y,n.y-=s.y,s.y=0);const{pixelWidth:o,pixelHeight:a}=e;return r.width=Math.min(r.width,o-s.x),r.height=Math.min(r.height,a-s.y),this.adaptor.copyToTexture(e,t,s,r,n)}ensureDepthStencil(){this.renderTarget.stencil||(this.renderTarget.stencil=!0,this.adaptor.startRenderPass(this.renderTarget,!1,null,this.viewport,0,this.layer))}destroy(){this._renderer=null,this._renderSurfaceToRenderTargetHash.forEach((e,t)=>{e!==t&&e.destroy()}),this._renderSurfaceToRenderTargetHash.clear(),this._gpuRenderTargetHash=Object.create(null)}_initRenderTarget(e){let t=null;return mt.test(e)&&(e=vh(e).source),e instanceof mo?t=e:e instanceof De&&(t=new mo({colorTextures:[e]}),e.source instanceof mt&&(t.isRoot=!0),e.once("destroy",()=>{t.destroy(),this._renderSurfaceToRenderTargetHash.delete(e);const s=this._gpuRenderTargetHash[t.uid];s&&(this._gpuRenderTargetHash[t.uid]=null,this.adaptor.destroyGpuRenderTarget(s))})),this._renderSurfaceToRenderTargetHash.set(e,t),t}getGpuRenderTarget(e){return this._gpuRenderTargetHash[e.uid]||(this._gpuRenderTargetHash[e.uid]=this.adaptor.initGpuRenderTarget(e))}resetState(){this.renderTarget=null,this.renderSurface=null}}class py{init(e,t){this._renderer=e,this._renderTargetSystem=t}initGpuRenderTarget(e){const t=e.colorTexture,{canvas:s,context:r}=this._ensureCanvas(t);return{canvas:s,context:r,width:s.width,height:s.height}}resizeGpuRenderTarget(e){const t=e.colorTexture,{canvas:s}=this._ensureCanvas(t);s.width=e.pixelWidth,s.height=e.pixelHeight}startRenderPass(e,t,s,r){const n=this._renderTargetSystem.getGpuRenderTarget(e);this._renderer.canvasContext.activeContext=n.context,this._renderer.canvasContext.activeResolution=e.resolution,t&&this.clear(e,t,s,r)}clear(e,t,s,r){const o=this._renderTargetSystem.getGpuRenderTarget(e).context,a=r||{x:0,y:0,width:e.pixelWidth,height:e.pixelHeight};if(o.setTransform(1,0,0,1,0,0),o.clearRect(a.x,a.y,a.width,a.height),s){const l=Pe.shared.setValue(s);l.alpha>0&&(o.globalAlpha=l.alpha,o.fillStyle=l.toHex(),o.fillRect(a.x,a.y,a.width,a.height),o.globalAlpha=1)}}finishRenderPass(){}copyToTexture(e,t,s,r,n){const a=this._renderTargetSystem.getGpuRenderTarget(e).canvas,l=t.source,{context:c}=this._ensureCanvas(l),h=(n==null?void 0:n.x)??0,u=(n==null?void 0:n.y)??0;return c.drawImage(a,s.x,s.y,r.width,r.height,h,u,r.width,r.height),l.update(),t}destroyGpuRenderTarget(e){}_ensureCanvas(e){let t=e.resource;(!t||!mt.test(t))&&(t=pe.get().createCanvas(e.pixelWidth,e.pixelHeight),e.resource=t),(t.width!==e.pixelWidth||t.height!==e.pixelHeight)&&(t.width=e.pixelWidth,t.height=e.pixelHeight);const s=t.getContext("2d");return{canvas:t,context:s}}}class Ch extends yo{constructor(e){super(e),this.adaptor=new py,this.adaptor.init(e,this)}}Ch.extension={type:[A.CanvasSystem],name:"renderTarget"};class Eh{constructor(e){}init(){}initSource(e){}generateCanvas(e){const t=pe.get().createCanvas(),s=t.getContext("2d"),r=ne.getCanvasSource(e);if(!r)return t;const n=e.frame,o=e.source._resolution??e.source.resolution??1,a=n.x*o,l=n.y*o,c=n.width*o,h=n.height*o;return t.width=Math.ceil(c),t.height=Math.ceil(h),s.drawImage(r,a,l,c,h,0,0,c,h),t}getPixels(e){const t=this.generateCanvas(e);return{pixels:t.getContext("2d",{willReadFrequently:!0}).getImageData(0,0,t.width,t.height).data,width:t.width,height:t.height}}destroy(){}}Eh.extension={type:[A.CanvasSystem],name:"texture"};const my=[..._o,ah,lh,Eh,Ch],gy=[ro,Zn,io,to,Jn,nh,sh,Qn],_y=[O_,ch],Sh=[],Th=[],Ah=[];Q.handleByNamedList(A.CanvasSystem,Sh),Q.handleByNamedList(A.CanvasPipes,Th),Q.handleByNamedList(A.CanvasPipesAdaptor,Ah),Q.add(...my,...gy,..._y);class yy extends ni{constructor(){const e={name:"canvas",type:_t.CANVAS,systems:Sh,renderPipes:Th,renderPipeAdaptors:Ah};super(e)}}const by=Object.freeze(Object.defineProperty({__proto__:null,CanvasRenderer:yy},Symbol.toStringTag,{value:"Module"}));var cr=(i=>(i[i.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",i[i.ARRAY_BUFFER=34962]="ARRAY_BUFFER",i[i.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",i))(cr||{});class vy{constructor(e,t){this._lastBindBaseLocation=-1,this._lastBindCallId=-1,this.buffer=e||null,this.updateID=-1,this.byteLength=-1,this.type=t}destroy(){this.buffer=null,this.updateID=-1,this.byteLength=-1,this.type=-1,this._lastBindBaseLocation=-1,this._lastBindCallId=-1}}class wh{constructor(e){this._boundBufferBases=Object.create(null),this._minBaseLocation=0,this._nextBindBaseIndex=this._minBaseLocation,this._bindCallId=0,this._renderer=e,this._managedBuffers=new Rt({renderer:e,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"glBuffer"})}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gl=null,this._boundBufferBases={}}contextChange(){this._gl=this._renderer.gl,this.destroyAll(!0),this._maxBindings=this._renderer.limits.maxUniformBindings}getGlBuffer(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]||this.createGLBuffer(e)}bind(e){const{_gl:t}=this,s=this.getGlBuffer(e);t.bindBuffer(s.type,s.buffer)}bindBufferBase(e,t){const{_gl:s}=this;this._boundBufferBases[t]!==e&&(this._boundBufferBases[t]=e,e._lastBindBaseLocation=t,s.bindBufferBase(s.UNIFORM_BUFFER,t,e.buffer))}nextBindBase(e){this._bindCallId++,this._minBaseLocation=0,e&&(this._boundBufferBases[0]=null,this._minBaseLocation=1,this._nextBindBaseIndex<1&&(this._nextBindBaseIndex=1))}freeLocationForBufferBase(e){let t=this.getLastBindBaseLocation(e);if(t>=this._minBaseLocation)return e._lastBindCallId=this._bindCallId,t;let s=0,r=this._nextBindBaseIndex;for(;s<2;){r>=this._maxBindings&&(r=this._minBaseLocation,s++);const n=this._boundBufferBases[r];if(n&&n._lastBindCallId===this._bindCallId){r++;continue}break}return t=r,this._nextBindBaseIndex=r+1,s>=2?-1:(e._lastBindCallId=this._bindCallId,this._boundBufferBases[t]=null,t)}getLastBindBaseLocation(e){const t=e._lastBindBaseLocation;return this._boundBufferBases[t]===e?t:-1}bindBufferRange(e,t,s,r){const{_gl:n}=this;s||(s=0),t||(t=0),this._boundBufferBases[t]=null,n.bindBufferRange(n.UNIFORM_BUFFER,t||0,e.buffer,s*256,r||256)}updateBuffer(e){const{_gl:t}=this,s=this.getGlBuffer(e);if(e._updateID===s.updateID)return s;s.updateID=e._updateID,t.bindBuffer(s.type,s.buffer);const r=e.data,n=e.descriptor.usage&Ee.STATIC?t.STATIC_DRAW:t.DYNAMIC_DRAW;return r?s.byteLength>=r.byteLength?t.bufferSubData(s.type,0,r,0,e._updateSize/r.BYTES_PER_ELEMENT):(s.byteLength=r.byteLength,t.bufferData(s.type,r,n)):(s.byteLength=e.descriptor.size,t.bufferData(s.type,s.byteLength,n)),s}destroyAll(e=!1){this._managedBuffers.removeAll(e)}onBufferUnload(e,t=!1){const s=e._gpuData[this._renderer.uid];s&&(t||this._gl.deleteBuffer(s.buffer))}createGLBuffer(e){const{_gl:t}=this;let s=cr.ARRAY_BUFFER;e.descriptor.usage&Ee.INDEX?s=cr.ELEMENT_ARRAY_BUFFER:e.descriptor.usage&Ee.UNIFORM&&(s=cr.UNIFORM_BUFFER);const r=new vy(t.createBuffer(),s);return e._gpuData[this._renderer.uid]=r,this._managedBuffers.add(e),r}resetState(){this._boundBufferBases=Object.create(null)}}wh.extension={type:[A.WebGLSystem],name:"buffer"};const bo=class Ef{constructor(e){this.supports={uint32Indices:!0,uniformBufferObject:!0,vertexArrayObject:!0,srgbTextures:!0,nonPowOf2wrapping:!0,msaa:!0,nonPowOf2mipmaps:!0},this._renderer=e,this.extensions=Object.create(null),this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this)}get isLost(){return!this.gl||this.gl.isContextLost()}contextChange(e){this.gl=e,this._renderer.gl=e}init(e){e={...Ef.defaultOptions,...e};let t=this.multiView=e.multiView;if(e.context&&t&&(ie("Renderer created with both a context and multiview enabled. Disabling multiView as both cannot work together."),t=!1),t?this.canvas=pe.get().createCanvas(this._renderer.canvas.width,this._renderer.canvas.height):this.canvas=this._renderer.view.canvas,e.context)this.initFromContext(e.context);else{const s=this._renderer.background.alpha<1,r=e.premultipliedAlpha??!0,n=e.antialias&&!this._renderer.backBuffer.useBackBuffer;this.createContext(e.preferWebGLVersion,{alpha:s,premultipliedAlpha:r,antialias:n,stencil:!0,preserveDrawingBuffer:e.preserveDrawingBuffer,powerPreference:e.powerPreference??"default"})}}ensureCanvasSize(e){if(!this.multiView){e!==this.canvas&&ie("multiView is disabled, but targetCanvas is not the main canvas");return}const{canvas:t}=this;(t.width<e.width||t.height<e.height)&&(t.width=Math.max(e.width,e.width),t.height=Math.max(e.height,e.height))}initFromContext(e){this.gl=e,this.webGLVersion=e instanceof pe.get().getWebGLRenderingContext()?1:2,this.getExtensions(),this.validateContext(e),this._renderer.runners.contextChange.emit(e);const t=this._renderer.view.canvas;t.addEventListener("webglcontextlost",this.handleContextLost,!1),t.addEventListener("webglcontextrestored",this.handleContextRestored,!1)}createContext(e,t){let s;const r=this.canvas;if(e===2&&(s=r.getContext("webgl2",t)),!s&&(s=r.getContext("webgl",t),!s))throw new Error("This browser does not support WebGL. Try using the canvas renderer");this.gl=s,this.initFromContext(this.gl)}getExtensions(){const{gl:e}=this,t={anisotropicFiltering:e.getExtension("EXT_texture_filter_anisotropic"),floatTextureLinear:e.getExtension("OES_texture_float_linear"),s3tc:e.getExtension("WEBGL_compressed_texture_s3tc"),s3tc_sRGB:e.getExtension("WEBGL_compressed_texture_s3tc_srgb"),etc:e.getExtension("WEBGL_compressed_texture_etc"),etc1:e.getExtension("WEBGL_compressed_texture_etc1"),pvrtc:e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),atc:e.getExtension("WEBGL_compressed_texture_atc"),astc:e.getExtension("WEBGL_compressed_texture_astc"),bptc:e.getExtension("EXT_texture_compression_bptc"),rgtc:e.getExtension("EXT_texture_compression_rgtc"),loseContext:e.getExtension("WEBGL_lose_context")};if(this.webGLVersion===1)this.extensions={...t,drawBuffers:e.getExtension("WEBGL_draw_buffers"),depthTexture:e.getExtension("WEBGL_depth_texture"),vertexArrayObject:e.getExtension("OES_vertex_array_object")||e.getExtension("MOZ_OES_vertex_array_object")||e.getExtension("WEBKIT_OES_vertex_array_object"),uint32ElementIndex:e.getExtension("OES_element_index_uint"),floatTexture:e.getExtension("OES_texture_float"),floatTextureLinear:e.getExtension("OES_texture_float_linear"),textureHalfFloat:e.getExtension("OES_texture_half_float"),textureHalfFloatLinear:e.getExtension("OES_texture_half_float_linear"),vertexAttribDivisorANGLE:e.getExtension("ANGLE_instanced_arrays"),srgb:e.getExtension("EXT_sRGB")};else{this.extensions={...t,colorBufferFloat:e.getExtension("EXT_color_buffer_float")};const s=e.getExtension("WEBGL_provoking_vertex");s&&s.provokingVertexWEBGL(s.FIRST_VERTEX_CONVENTION_WEBGL)}}handleContextLost(e){e.preventDefault(),this._contextLossForced&&(this._contextLossForced=!1,setTimeout(()=>{var t;this.gl.isContextLost()&&((t=this.extensions.loseContext)==null||t.restoreContext())},0))}handleContextRestored(){this.getExtensions(),this._renderer.runners.contextChange.emit(this.gl)}destroy(){var t;const e=this._renderer.view.canvas;this._renderer=null,e.removeEventListener("webglcontextlost",this.handleContextLost),e.removeEventListener("webglcontextrestored",this.handleContextRestored),this.gl.useProgram(null),(t=this.extensions.loseContext)==null||t.loseContext()}forceContextLoss(){var e;(e=this.extensions.loseContext)==null||e.loseContext(),this._contextLossForced=!0}validateContext(e){const t=e.getContextAttributes();t&&!t.stencil&&ie("Provided WebGL context does not have a stencil buffer, masks may not render correctly");const s=this.supports,r=this.webGLVersion===2,n=this.extensions;s.uint32Indices=r||!!n.uint32ElementIndex,s.uniformBufferObject=r,s.vertexArrayObject=r||!!n.vertexArrayObject,s.srgbTextures=r||!!n.srgb,s.nonPowOf2wrapping=r,s.nonPowOf2mipmaps=r,s.msaa=r,s.uint32Indices||ie("Provided WebGL context does not support 32 index buffer, large scenes may not render correctly")}};bo.extension={type:[A.WebGLSystem],name:"context"},bo.defaultOptions={context:null,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:void 0,preferWebGLVersion:2,multiView:!1};let xy=bo;function Ih(i,e){for(const t in i.attributes){const s=i.attributes[t],r=e[t];r?(s.format??(s.format=r.format),s.offset??(s.offset=r.offset),s.instance??(s.instance=r.instance)):ie(`Attribute ${t} is not present in the shader, but is present in the geometry. Unable to infer attribute details.`)}Cy(i)}function Cy(i){const{buffers:e,attributes:t}=i,s={},r={};for(const n in e){const o=e[n];s[o.uid]=0,r[o.uid]=0}for(const n in t){const o=t[n];s[o.buffer.uid]+=Js(o.format).stride}for(const n in t){const o=t[n];o.stride??(o.stride=s[o.buffer.uid]),o.start??(o.start=r[o.buffer.uid]),r[o.buffer.uid]+=Js(o.format).stride}}var vo=(i=>(i[i.RGBA=6408]="RGBA",i[i.RGB=6407]="RGB",i[i.RG=33319]="RG",i[i.RED=6403]="RED",i[i.RGBA_INTEGER=36249]="RGBA_INTEGER",i[i.RGB_INTEGER=36248]="RGB_INTEGER",i[i.RG_INTEGER=33320]="RG_INTEGER",i[i.RED_INTEGER=36244]="RED_INTEGER",i[i.ALPHA=6406]="ALPHA",i[i.LUMINANCE=6409]="LUMINANCE",i[i.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",i[i.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",i[i.DEPTH_STENCIL=34041]="DEPTH_STENCIL",i))(vo||{}),xo=(i=>(i[i.TEXTURE_2D=3553]="TEXTURE_2D",i[i.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",i[i.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",i[i.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",i[i.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",i[i.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",i[i.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",i[i.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",i[i.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",i))(xo||{}),he=(i=>(i[i.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",i[i.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",i[i.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",i[i.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",i[i.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",i[i.UNSIGNED_INT=5125]="UNSIGNED_INT",i[i.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",i[i.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",i[i.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",i[i.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",i[i.BYTE=5120]="BYTE",i[i.SHORT=5122]="SHORT",i[i.INT=5124]="INT",i[i.FLOAT=5126]="FLOAT",i[i.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",i[i.HALF_FLOAT=36193]="HALF_FLOAT",i))(he||{});const Rh={uint8x2:he.UNSIGNED_BYTE,uint8x4:he.UNSIGNED_BYTE,sint8x2:he.BYTE,sint8x4:he.BYTE,unorm8x2:he.UNSIGNED_BYTE,unorm8x4:he.UNSIGNED_BYTE,snorm8x2:he.BYTE,snorm8x4:he.BYTE,uint16x2:he.UNSIGNED_SHORT,uint16x4:he.UNSIGNED_SHORT,sint16x2:he.SHORT,sint16x4:he.SHORT,unorm16x2:he.UNSIGNED_SHORT,unorm16x4:he.UNSIGNED_SHORT,snorm16x2:he.SHORT,snorm16x4:he.SHORT,float16x2:he.HALF_FLOAT,float16x4:he.HALF_FLOAT,float32:he.FLOAT,float32x2:he.FLOAT,float32x3:he.FLOAT,float32x4:he.FLOAT,uint32:he.UNSIGNED_INT,uint32x2:he.UNSIGNED_INT,uint32x3:he.UNSIGNED_INT,uint32x4:he.UNSIGNED_INT,sint32:he.INT,sint32x2:he.INT,sint32x3:he.INT,sint32x4:he.INT};function Ey(i){return Rh[i]??Rh.float32}const Sy={"point-list":0,"line-list":1,"line-strip":3,"triangle-list":4,"triangle-strip":5};class Ty{constructor(){this.vaoCache=Object.create(null)}destroy(){this.vaoCache=Object.create(null)}}class Mh{constructor(e){this._renderer=e,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0,this._managedGeometries=new Rt({renderer:e,type:"resource",onUnload:this.onGeometryUnload.bind(this),name:"glGeometry"})}contextChange(){const e=this.gl=this._renderer.gl;if(!this._renderer.context.supports.vertexArrayObject)throw new Error("[PixiJS] Vertex Array Objects are not supported on this device");this.destroyAll(!0);const t=this._renderer.context.extensions.vertexArrayObject;t&&(e.createVertexArray=()=>t.createVertexArrayOES(),e.bindVertexArray=r=>t.bindVertexArrayOES(r),e.deleteVertexArray=r=>t.deleteVertexArrayOES(r));const s=this._renderer.context.extensions.vertexAttribDivisorANGLE;s&&(e.drawArraysInstanced=(r,n,o,a)=>{s.drawArraysInstancedANGLE(r,n,o,a)},e.drawElementsInstanced=(r,n,o,a,l)=>{s.drawElementsInstancedANGLE(r,n,o,a,l)},e.vertexAttribDivisor=(r,n)=>s.vertexAttribDivisorANGLE(r,n)),this._activeGeometry=null,this._activeVao=null}bind(e,t){const s=this.gl;this._activeGeometry=e;const r=this.getVao(e,t);this._activeVao!==r&&(this._activeVao=r,s.bindVertexArray(r)),this.updateBuffers()}resetState(){this.unbind()}updateBuffers(){const e=this._activeGeometry,t=this._renderer.buffer;for(let s=0;s<e.buffers.length;s++){const r=e.buffers[s];t.updateBuffer(r)}e._gcLastUsed=this._renderer.gc.now}checkCompatibility(e,t){const s=e.attributes,r=t._attributeData;for(const n in r)if(!s[n])throw new Error(`shader and geometry incompatible, geometry missing the "${n}" attribute`)}getSignature(e,t){const s=e.attributes,r=t._attributeData,n=["g",e.uid];for(const o in s)r[o]&&n.push(o,r[o].location);return n.join("-")}getVao(e,t){var s;return((s=e._gpuData[this._renderer.uid])==null?void 0:s.vaoCache[t._key])||this.initGeometryVao(e,t)}initGeometryVao(e,t,s=!0){const r=this._renderer.gl,n=this._renderer.buffer;this._renderer.shader._getProgramData(t),this.checkCompatibility(e,t);const o=this.getSignature(e,t);let a=e._gpuData[this._renderer.uid];a||(a=new Ty,e._gpuData[this._renderer.uid]=a,this._managedGeometries.add(e));const l=a.vaoCache;let c=l[o];if(c)return l[t._key]=c,c;Ih(e,t._attributeData);const h=e.buffers;c=r.createVertexArray(),r.bindVertexArray(c);for(let u=0;u<h.length;u++){const p=h[u];n.bind(p)}return this.activateVao(e,t),l[t._key]=c,l[o]=c,r.bindVertexArray(null),c}onGeometryUnload(e,t=!1){const s=e._gpuData[this._renderer.uid];if(!s)return;const r=s.vaoCache;if(!t)for(const n in r)this._activeVao!==r[n]&&this.resetState(),this.gl.deleteVertexArray(r[n])}destroyAll(e=!1){this._managedGeometries.removeAll(e)}activateVao(e,t){var a;const s=this._renderer.gl,r=this._renderer.buffer,n=e.attributes;e.indexBuffer&&r.bind(e.indexBuffer);let o=null;for(const l in n){const c=n[l],h=c.buffer,u=r.getGlBuffer(h),p=t._attributeData[l];if(p){o!==u&&(r.bind(h),o=u);const d=p.location;s.enableVertexAttribArray(d);const g=Js(c.format),_=Ey(c.format);if(((a=p.format)==null?void 0:a.substring(1,4))==="int"?s.vertexAttribIPointer(d,g.size,_,c.stride,c.offset):s.vertexAttribPointer(d,g.size,_,g.normalised,c.stride,c.offset),c.instance)if(this.hasInstance){const b=c.divisor??1;s.vertexAttribDivisor(d,b)}else throw new Error("geometry error, GPU Instancing is not supported on this device")}}}draw(e,t,s,r){const{gl:n}=this._renderer,o=this._activeGeometry,a=Sy[e||o.topology];if(r??(r=o.instanceCount),o.indexBuffer){const l=o.indexBuffer.data.BYTES_PER_ELEMENT,c=l===2?n.UNSIGNED_SHORT:n.UNSIGNED_INT;r!==1?n.drawElementsInstanced(a,t||o.indexBuffer.data.length,c,(s||0)*l,r):n.drawElements(a,t||o.indexBuffer.data.length,c,(s||0)*l)}else r!==1?n.drawArraysInstanced(a,s||0,t||o.getSize(),r):n.drawArrays(a,s||0,t||o.getSize());return this}unbind(){this.gl.bindVertexArray(null),this._activeVao=null,this._activeGeometry=null}destroy(){this._managedGeometries.destroy(),this._renderer=null,this.gl=null,this._activeVao=null,this._activeGeometry=null}}Mh.extension={type:[A.WebGLSystem],name:"geometry"};const Ay=new In({attributes:{aPosition:[-1,-1,3,-1,-1,3]}}),Co=class Sf{constructor(e){this.useBackBuffer=!1,this._useBackBufferThisRender=!1,this._renderer=e}init(e={}){const{useBackBuffer:t,antialias:s}={...Sf.defaultOptions,...e};this.useBackBuffer=t,this._antialias=s,this._renderer.context.supports.msaa||(ie("antialiasing, is not supported on when using the back buffer"),this._antialias=!1),this._state=It.for2d();const r=new Es({vertex:`
|
|
560
|
+
`,"background: #E72264; padding:5px 0;","background: #6CA2EA; padding:5px 0;","background: #B5D33D; padding:5px 0;","background: #FED23F; padding:5px 0;","color: #FFFFFF; background: #E72264; padding:5px 0;","color: #E72264; background: #FFFFFF; padding:5px 0;"];globalThis.console.log(...e)}else globalThis.console&&globalThis.console.log(`PixiJS ${Qi} - ${i} - http://www.pixijs.com/`);yh=!0}}class uo{constructor(e){this._renderer=e}init(e){if(e.hello){let t=this._renderer.name;this._renderer.type===_t.WEBGL&&(t+=` ${this._renderer.context.webGLVersion}`),hy(t)}}}uo.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"hello",priority:-2},uo.defaultOptions={hello:!1};const fo=class vf{constructor(e){this._renderer=e}init(e){e={...vf.defaultOptions,...e},this.maxUnusedTime=e.renderableGCMaxUnusedTime}get enabled(){return ee("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled}set enabled(e){ee("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled=e}addManagedHash(e,t){ee("8.15.0","RenderableGCSystem.addManagedHash is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(e,t,"hash")}addManagedArray(e,t){ee("8.15.0","RenderableGCSystem.addManagedArray is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(e,t,"array")}addRenderable(e){ee("8.15.0","RenderableGCSystem.addRenderable is deprecated, please use the GCSystem instead."),this._renderer.gc.addResource(e,"renderable")}run(){ee("8.15.0","RenderableGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};fo.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"renderableGC",priority:0},fo.defaultOptions={renderableGCActive:!0,renderableGCMaxUnusedTime:6e4,renderableGCFrequency:3e4};let uy=fo;const po=class kr{get count(){return this._renderer.tick}get checkCount(){return this._checkCount}set checkCount(e){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._checkCount=e}get maxIdle(){return this._renderer.gc.maxUnusedTime/1e3*60}set maxIdle(e){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.maxUnusedTime=e/60*1e3}get checkCountMax(){return Math.floor(this._renderer.gc._frequency/1e3)}set checkCountMax(e){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead.")}get active(){return this._renderer.gc.enabled}set active(e){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.enabled=e}constructor(e){this._renderer=e,this._checkCount=0}init(e){e.textureGCActive!==kr.defaultOptions.textureGCActive&&(this.active=e.textureGCActive),e.textureGCMaxIdle!==kr.defaultOptions.textureGCMaxIdle&&(this.maxIdle=e.textureGCMaxIdle),e.textureGCCheckCountMax!==kr.defaultOptions.textureGCCheckCountMax&&(this.checkCountMax=e.textureGCCheckCountMax)}run(){ee("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};po.extension={type:[A.WebGLSystem,A.WebGPUSystem],name:"textureGC"},po.defaultOptions={textureGCActive:!0,textureGCAMaxIdle:null,textureGCMaxIdle:3600,textureGCCheckCountMax:600};let dy=po;const bh=class xf{constructor(e={}){if(this.uid=be("renderTarget"),this.colorTextures=[],this.dirtyId=0,this.isRoot=!1,this._size=new Float32Array(2),this._managedColorTextures=!1,e={...xf.defaultOptions,...e},this.stencil=e.stencil,this.depth=e.depth,this.isRoot=e.isRoot,typeof e.colorTextures=="number"){this._managedColorTextures=!0;for(let t=0;t<e.colorTextures;t++)this.colorTextures.push(new De({width:e.width,height:e.height,resolution:e.resolution,antialias:e.antialias}))}else{this.colorTextures=[...e.colorTextures.map(s=>s.source)];const t=this.colorTexture.source;this.resize(t.width,t.height,t._resolution)}this.colorTexture.source.on("resize",this.onSourceResize,this),(e.depthStencilTexture||this.stencil)&&(e.depthStencilTexture instanceof j||e.depthStencilTexture instanceof De?this.depthStencilTexture=e.depthStencilTexture.source:this.ensureDepthStencilTexture())}get size(){const e=this._size;return e[0]=this.pixelWidth,e[1]=this.pixelHeight,e}get width(){return this.colorTexture.source.width}get height(){return this.colorTexture.source.height}get pixelWidth(){return this.colorTexture.source.pixelWidth}get pixelHeight(){return this.colorTexture.source.pixelHeight}get resolution(){return this.colorTexture.source._resolution}get colorTexture(){return this.colorTextures[0]}onSourceResize(e){this.resize(e.width,e.height,e._resolution,!0)}ensureDepthStencilTexture(){this.depthStencilTexture||(this.depthStencilTexture=new De({width:this.width,height:this.height,resolution:this.resolution,format:"depth24plus-stencil8",autoGenerateMipmaps:!1,antialias:!1,mipLevelCount:1}))}resize(e,t,s=this.resolution,r=!1){this.dirtyId++,this.colorTextures.forEach((n,o)=>{r&&o===0||n.source.resize(e,t,s)}),this.depthStencilTexture&&this.depthStencilTexture.source.resize(e,t,s)}destroy(){this.colorTexture.source.off("resize",this.onSourceResize,this),this._managedColorTextures&&this.colorTextures.forEach(e=>{e.destroy()}),this.depthStencilTexture&&(this.depthStencilTexture.destroy(),delete this.depthStencilTexture)}};bh.defaultOptions={width:0,height:0,resolution:1,colorTextures:1,stencil:!1,depth:!1,antialias:!1,isRoot:!1};let mo=bh;const Rs=new Map;ms.register(Rs);function vh(i,e){if(!Rs.has(i)){const t=new j({source:new mt({resource:i,...e})}),s=()=>{Rs.get(i)===t&&Rs.delete(i)};t.once("destroy",s),t.source.once("destroy",s),Rs.set(i,t)}return Rs.get(i)}const go=class Cf{get autoDensity(){return this.texture.source.autoDensity}set autoDensity(e){this.texture.source.autoDensity=e}get resolution(){return this.texture.source._resolution}set resolution(e){this.texture.source.resize(this.texture.source.width,this.texture.source.height,e)}init(e){e={...Cf.defaultOptions,...e},e.view&&(ee(Be,"ViewSystem.view has been renamed to ViewSystem.canvas"),e.canvas=e.view),this.screen=new Ce(0,0,e.width,e.height),this.canvas=e.canvas||pe.get().createCanvas(),this.antialias=!!e.antialias,this.texture=vh(this.canvas,e),this.renderTarget=new mo({colorTextures:[this.texture],depth:!!e.depth,isRoot:!0}),this.texture.source.transparent=e.backgroundAlpha<1,this.resolution=e.resolution}resize(e,t,s){this.texture.source.resize(e,t,s),this.screen.width=this.texture.frame.width,this.screen.height=this.texture.frame.height}destroy(e=!1){(typeof e=="boolean"?e:!!(e!=null&&e.removeView))&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.texture.destroy()}};go.extension={type:[A.WebGLSystem,A.WebGPUSystem,A.CanvasSystem],name:"view",priority:0},go.defaultOptions={width:800,height:600,autoDensity:!1,antialias:!1};const _o=[ty,gh,uo,go,ph,ly,dy,mh,sy,Nl,uy,_h],xh=[ro,Zn,io,to,Jn,oh,ih,Qn];function fy(i,e,t,s,r,n){const o=n?1:-1;return i.identity(),i.a=1/s*2,i.d=o*(1/r*2),i.tx=-1-e*i.a,i.ty=-o-t*i.d,i}function py(i){const e=i.colorTexture.source.resource;return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement&&document.body.contains(e)}class yo{constructor(e){this.rootViewPort=new Ce,this.viewport=new Ce,this.mipLevel=0,this.layer=0,this.onRenderTargetChange=new kl("onRenderTargetChange"),this.projectionMatrix=new H,this.defaultClearColor=[0,0,0,0],this._renderSurfaceToRenderTargetHash=new Map,this._gpuRenderTargetHash=Object.create(null),this._renderTargetStack=[],this._renderer=e,e.gc.addCollection(this,"_gpuRenderTargetHash","hash")}finishRenderPass(){this.adaptor.finishRenderPass(this.renderTarget)}renderStart({target:e,clear:t,clearColor:s,frame:r,mipLevel:n,layer:o}){var a,l;this._renderTargetStack.length=0,this.push(e,t,s,r,n??0,o??0),this.rootViewPort.copyFrom(this.viewport),this.rootRenderTarget=this.renderTarget,this.renderingToScreen=py(this.rootRenderTarget),(l=(a=this.adaptor).prerender)==null||l.call(a,this.rootRenderTarget)}postrender(){var e,t;(t=(e=this.adaptor).postrender)==null||t.call(e,this.rootRenderTarget)}bind(e,t=!0,s,r,n=0,o=0){const a=this.getRenderTarget(e),l=this.renderTarget!==a;this.renderTarget=a,this.renderSurface=e;const c=this.getGpuRenderTarget(a);(a.pixelWidth!==c.width||a.pixelHeight!==c.height)&&(this.adaptor.resizeGpuRenderTarget(a),c.width=a.pixelWidth,c.height=a.pixelHeight);const h=a.colorTexture,u=this.viewport,p=h.arrayLayerCount||1;if((o|0)!==o&&(o|=0),o<0||o>=p)throw new Error(`[RenderTargetSystem] layer ${o} is out of bounds (arrayLayerCount=${p}).`);this.mipLevel=n|0,this.layer=o|0;const d=Math.max(h.pixelWidth>>n,1),g=Math.max(h.pixelHeight>>n,1);if(!r&&e instanceof j&&(r=e.frame),r){const _=h._resolution,b=1<<Math.max(n|0,0),v=r.x*_+.5|0,C=r.y*_+.5|0,E=r.width*_+.5|0,S=r.height*_+.5|0;let w=Math.floor(v/b),R=Math.floor(C/b),M=Math.ceil(E/b),D=Math.ceil(S/b);w=Math.min(Math.max(w,0),d-1),R=Math.min(Math.max(R,0),g-1),M=Math.min(Math.max(M,1),d-w),D=Math.min(Math.max(D,1),g-R),u.x=w,u.y=R,u.width=M,u.height=D}else u.x=0,u.y=0,u.width=d,u.height=g;return fy(this.projectionMatrix,0,0,u.width/h.resolution,u.height/h.resolution,!a.isRoot),this.adaptor.startRenderPass(a,t,s,u,n,o),l&&this.onRenderTargetChange.emit(a),a}clear(e,t=st.ALL,s,r=this.mipLevel,n=this.layer){t&&(e&&(e=this.getRenderTarget(e)),this.adaptor.clear(e||this.renderTarget,t,s,this.viewport,r,n))}contextChange(){this._gpuRenderTargetHash=Object.create(null)}push(e,t=st.ALL,s,r,n=0,o=0){const a=this.bind(e,t,s,r,n,o);return this._renderTargetStack.push({renderTarget:a,frame:r,mipLevel:n,layer:o}),a}pop(){this._renderTargetStack.pop();const e=this._renderTargetStack[this._renderTargetStack.length-1];this.bind(e.renderTarget,!1,null,e.frame,e.mipLevel,e.layer)}getRenderTarget(e){return e.isTexture&&(e=e.source),this._renderSurfaceToRenderTargetHash.get(e)??this._initRenderTarget(e)}copyToTexture(e,t,s,r,n){s.x<0&&(r.width+=s.x,n.x-=s.x,s.x=0),s.y<0&&(r.height+=s.y,n.y-=s.y,s.y=0);const{pixelWidth:o,pixelHeight:a}=e;return r.width=Math.min(r.width,o-s.x),r.height=Math.min(r.height,a-s.y),this.adaptor.copyToTexture(e,t,s,r,n)}ensureDepthStencil(){this.renderTarget.stencil||(this.renderTarget.stencil=!0,this.adaptor.startRenderPass(this.renderTarget,!1,null,this.viewport,0,this.layer))}destroy(){this._renderer=null,this._renderSurfaceToRenderTargetHash.forEach((e,t)=>{e!==t&&e.destroy()}),this._renderSurfaceToRenderTargetHash.clear(),this._gpuRenderTargetHash=Object.create(null)}_initRenderTarget(e){let t=null;return mt.test(e)&&(e=vh(e).source),e instanceof mo?t=e:e instanceof De&&(t=new mo({colorTextures:[e]}),e.source instanceof mt&&(t.isRoot=!0),e.once("destroy",()=>{t.destroy(),this._renderSurfaceToRenderTargetHash.delete(e);const s=this._gpuRenderTargetHash[t.uid];s&&(this._gpuRenderTargetHash[t.uid]=null,this.adaptor.destroyGpuRenderTarget(s))})),this._renderSurfaceToRenderTargetHash.set(e,t),t}getGpuRenderTarget(e){return this._gpuRenderTargetHash[e.uid]||(this._gpuRenderTargetHash[e.uid]=this.adaptor.initGpuRenderTarget(e))}resetState(){this.renderTarget=null,this.renderSurface=null}}class my{init(e,t){this._renderer=e,this._renderTargetSystem=t}initGpuRenderTarget(e){const t=e.colorTexture,{canvas:s,context:r}=this._ensureCanvas(t);return{canvas:s,context:r,width:s.width,height:s.height}}resizeGpuRenderTarget(e){const t=e.colorTexture,{canvas:s}=this._ensureCanvas(t);s.width=e.pixelWidth,s.height=e.pixelHeight}startRenderPass(e,t,s,r){const n=this._renderTargetSystem.getGpuRenderTarget(e);this._renderer.canvasContext.activeContext=n.context,this._renderer.canvasContext.activeResolution=e.resolution,t&&this.clear(e,t,s,r)}clear(e,t,s,r){const o=this._renderTargetSystem.getGpuRenderTarget(e).context,a=r||{x:0,y:0,width:e.pixelWidth,height:e.pixelHeight};if(o.setTransform(1,0,0,1,0,0),o.clearRect(a.x,a.y,a.width,a.height),s){const l=Pe.shared.setValue(s);l.alpha>0&&(o.globalAlpha=l.alpha,o.fillStyle=l.toHex(),o.fillRect(a.x,a.y,a.width,a.height),o.globalAlpha=1)}}finishRenderPass(){}copyToTexture(e,t,s,r,n){const a=this._renderTargetSystem.getGpuRenderTarget(e).canvas,l=t.source,{context:c}=this._ensureCanvas(l),h=(n==null?void 0:n.x)??0,u=(n==null?void 0:n.y)??0;return c.drawImage(a,s.x,s.y,r.width,r.height,h,u,r.width,r.height),l.update(),t}destroyGpuRenderTarget(e){}_ensureCanvas(e){let t=e.resource;(!t||!mt.test(t))&&(t=pe.get().createCanvas(e.pixelWidth,e.pixelHeight),e.resource=t),(t.width!==e.pixelWidth||t.height!==e.pixelHeight)&&(t.width=e.pixelWidth,t.height=e.pixelHeight);const s=t.getContext("2d");return{canvas:t,context:s}}}class Ch extends yo{constructor(e){super(e),this.adaptor=new my,this.adaptor.init(e,this)}}Ch.extension={type:[A.CanvasSystem],name:"renderTarget"};class Eh{constructor(e){}init(){}initSource(e){}generateCanvas(e){const t=pe.get().createCanvas(),s=t.getContext("2d"),r=ne.getCanvasSource(e);if(!r)return t;const n=e.frame,o=e.source._resolution??e.source.resolution??1,a=n.x*o,l=n.y*o,c=n.width*o,h=n.height*o;return t.width=Math.ceil(c),t.height=Math.ceil(h),s.drawImage(r,a,l,c,h,0,0,c,h),t}getPixels(e){const t=this.generateCanvas(e);return{pixels:t.getContext("2d",{willReadFrequently:!0}).getImageData(0,0,t.width,t.height).data,width:t.width,height:t.height}}destroy(){}}Eh.extension={type:[A.CanvasSystem],name:"texture"};const gy=[..._o,ah,lh,Eh,Ch],_y=[ro,Zn,io,to,Jn,nh,sh,Qn],yy=[B_,ch],Sh=[],Th=[],Ah=[];Q.handleByNamedList(A.CanvasSystem,Sh),Q.handleByNamedList(A.CanvasPipes,Th),Q.handleByNamedList(A.CanvasPipesAdaptor,Ah),Q.add(...gy,..._y,...yy);class by extends ni{constructor(){const e={name:"canvas",type:_t.CANVAS,systems:Sh,renderPipes:Th,renderPipeAdaptors:Ah};super(e)}}const vy=Object.freeze(Object.defineProperty({__proto__:null,CanvasRenderer:by},Symbol.toStringTag,{value:"Module"}));var cr=(i=>(i[i.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",i[i.ARRAY_BUFFER=34962]="ARRAY_BUFFER",i[i.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",i))(cr||{});class xy{constructor(e,t){this._lastBindBaseLocation=-1,this._lastBindCallId=-1,this.buffer=e||null,this.updateID=-1,this.byteLength=-1,this.type=t}destroy(){this.buffer=null,this.updateID=-1,this.byteLength=-1,this.type=-1,this._lastBindBaseLocation=-1,this._lastBindCallId=-1}}class wh{constructor(e){this._boundBufferBases=Object.create(null),this._minBaseLocation=0,this._nextBindBaseIndex=this._minBaseLocation,this._bindCallId=0,this._renderer=e,this._managedBuffers=new Rt({renderer:e,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"glBuffer"})}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gl=null,this._boundBufferBases={}}contextChange(){this._gl=this._renderer.gl,this.destroyAll(!0),this._maxBindings=this._renderer.limits.maxUniformBindings}getGlBuffer(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]||this.createGLBuffer(e)}bind(e){const{_gl:t}=this,s=this.getGlBuffer(e);t.bindBuffer(s.type,s.buffer)}bindBufferBase(e,t){const{_gl:s}=this;this._boundBufferBases[t]!==e&&(this._boundBufferBases[t]=e,e._lastBindBaseLocation=t,s.bindBufferBase(s.UNIFORM_BUFFER,t,e.buffer))}nextBindBase(e){this._bindCallId++,this._minBaseLocation=0,e&&(this._boundBufferBases[0]=null,this._minBaseLocation=1,this._nextBindBaseIndex<1&&(this._nextBindBaseIndex=1))}freeLocationForBufferBase(e){let t=this.getLastBindBaseLocation(e);if(t>=this._minBaseLocation)return e._lastBindCallId=this._bindCallId,t;let s=0,r=this._nextBindBaseIndex;for(;s<2;){r>=this._maxBindings&&(r=this._minBaseLocation,s++);const n=this._boundBufferBases[r];if(n&&n._lastBindCallId===this._bindCallId){r++;continue}break}return t=r,this._nextBindBaseIndex=r+1,s>=2?-1:(e._lastBindCallId=this._bindCallId,this._boundBufferBases[t]=null,t)}getLastBindBaseLocation(e){const t=e._lastBindBaseLocation;return this._boundBufferBases[t]===e?t:-1}bindBufferRange(e,t,s,r){const{_gl:n}=this;s||(s=0),t||(t=0),this._boundBufferBases[t]=null,n.bindBufferRange(n.UNIFORM_BUFFER,t||0,e.buffer,s*256,r||256)}updateBuffer(e){const{_gl:t}=this,s=this.getGlBuffer(e);if(e._updateID===s.updateID)return s;s.updateID=e._updateID,t.bindBuffer(s.type,s.buffer);const r=e.data,n=e.descriptor.usage&Ee.STATIC?t.STATIC_DRAW:t.DYNAMIC_DRAW;return r?s.byteLength>=r.byteLength?t.bufferSubData(s.type,0,r,0,e._updateSize/r.BYTES_PER_ELEMENT):(s.byteLength=r.byteLength,t.bufferData(s.type,r,n)):(s.byteLength=e.descriptor.size,t.bufferData(s.type,s.byteLength,n)),s}destroyAll(e=!1){this._managedBuffers.removeAll(e)}onBufferUnload(e,t=!1){const s=e._gpuData[this._renderer.uid];s&&(t||this._gl.deleteBuffer(s.buffer))}createGLBuffer(e){const{_gl:t}=this;let s=cr.ARRAY_BUFFER;e.descriptor.usage&Ee.INDEX?s=cr.ELEMENT_ARRAY_BUFFER:e.descriptor.usage&Ee.UNIFORM&&(s=cr.UNIFORM_BUFFER);const r=new xy(t.createBuffer(),s);return e._gpuData[this._renderer.uid]=r,this._managedBuffers.add(e),r}resetState(){this._boundBufferBases=Object.create(null)}}wh.extension={type:[A.WebGLSystem],name:"buffer"};const bo=class Ef{constructor(e){this.supports={uint32Indices:!0,uniformBufferObject:!0,vertexArrayObject:!0,srgbTextures:!0,nonPowOf2wrapping:!0,msaa:!0,nonPowOf2mipmaps:!0},this._renderer=e,this.extensions=Object.create(null),this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this)}get isLost(){return!this.gl||this.gl.isContextLost()}contextChange(e){this.gl=e,this._renderer.gl=e}init(e){e={...Ef.defaultOptions,...e};let t=this.multiView=e.multiView;if(e.context&&t&&(ie("Renderer created with both a context and multiview enabled. Disabling multiView as both cannot work together."),t=!1),t?this.canvas=pe.get().createCanvas(this._renderer.canvas.width,this._renderer.canvas.height):this.canvas=this._renderer.view.canvas,e.context)this.initFromContext(e.context);else{const s=this._renderer.background.alpha<1,r=e.premultipliedAlpha??!0,n=e.antialias&&!this._renderer.backBuffer.useBackBuffer;this.createContext(e.preferWebGLVersion,{alpha:s,premultipliedAlpha:r,antialias:n,stencil:!0,preserveDrawingBuffer:e.preserveDrawingBuffer,powerPreference:e.powerPreference??"default"})}}ensureCanvasSize(e){if(!this.multiView){e!==this.canvas&&ie("multiView is disabled, but targetCanvas is not the main canvas");return}const{canvas:t}=this;(t.width<e.width||t.height<e.height)&&(t.width=Math.max(e.width,e.width),t.height=Math.max(e.height,e.height))}initFromContext(e){this.gl=e,this.webGLVersion=e instanceof pe.get().getWebGLRenderingContext()?1:2,this.getExtensions(),this.validateContext(e),this._renderer.runners.contextChange.emit(e);const t=this._renderer.view.canvas;t.addEventListener("webglcontextlost",this.handleContextLost,!1),t.addEventListener("webglcontextrestored",this.handleContextRestored,!1)}createContext(e,t){let s;const r=this.canvas;if(e===2&&(s=r.getContext("webgl2",t)),!s&&(s=r.getContext("webgl",t),!s))throw new Error("This browser does not support WebGL. Try using the canvas renderer");this.gl=s,this.initFromContext(this.gl)}getExtensions(){const{gl:e}=this,t={anisotropicFiltering:e.getExtension("EXT_texture_filter_anisotropic"),floatTextureLinear:e.getExtension("OES_texture_float_linear"),s3tc:e.getExtension("WEBGL_compressed_texture_s3tc"),s3tc_sRGB:e.getExtension("WEBGL_compressed_texture_s3tc_srgb"),etc:e.getExtension("WEBGL_compressed_texture_etc"),etc1:e.getExtension("WEBGL_compressed_texture_etc1"),pvrtc:e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),atc:e.getExtension("WEBGL_compressed_texture_atc"),astc:e.getExtension("WEBGL_compressed_texture_astc"),bptc:e.getExtension("EXT_texture_compression_bptc"),rgtc:e.getExtension("EXT_texture_compression_rgtc"),loseContext:e.getExtension("WEBGL_lose_context")};if(this.webGLVersion===1)this.extensions={...t,drawBuffers:e.getExtension("WEBGL_draw_buffers"),depthTexture:e.getExtension("WEBGL_depth_texture"),vertexArrayObject:e.getExtension("OES_vertex_array_object")||e.getExtension("MOZ_OES_vertex_array_object")||e.getExtension("WEBKIT_OES_vertex_array_object"),uint32ElementIndex:e.getExtension("OES_element_index_uint"),floatTexture:e.getExtension("OES_texture_float"),floatTextureLinear:e.getExtension("OES_texture_float_linear"),textureHalfFloat:e.getExtension("OES_texture_half_float"),textureHalfFloatLinear:e.getExtension("OES_texture_half_float_linear"),vertexAttribDivisorANGLE:e.getExtension("ANGLE_instanced_arrays"),srgb:e.getExtension("EXT_sRGB")};else{this.extensions={...t,colorBufferFloat:e.getExtension("EXT_color_buffer_float")};const s=e.getExtension("WEBGL_provoking_vertex");s&&s.provokingVertexWEBGL(s.FIRST_VERTEX_CONVENTION_WEBGL)}}handleContextLost(e){e.preventDefault(),this._contextLossForced&&(this._contextLossForced=!1,setTimeout(()=>{var t;this.gl.isContextLost()&&((t=this.extensions.loseContext)==null||t.restoreContext())},0))}handleContextRestored(){this.getExtensions(),this._renderer.runners.contextChange.emit(this.gl)}destroy(){var t;const e=this._renderer.view.canvas;this._renderer=null,e.removeEventListener("webglcontextlost",this.handleContextLost),e.removeEventListener("webglcontextrestored",this.handleContextRestored),this.gl.useProgram(null),(t=this.extensions.loseContext)==null||t.loseContext()}forceContextLoss(){var e;(e=this.extensions.loseContext)==null||e.loseContext(),this._contextLossForced=!0}validateContext(e){const t=e.getContextAttributes();t&&!t.stencil&&ie("Provided WebGL context does not have a stencil buffer, masks may not render correctly");const s=this.supports,r=this.webGLVersion===2,n=this.extensions;s.uint32Indices=r||!!n.uint32ElementIndex,s.uniformBufferObject=r,s.vertexArrayObject=r||!!n.vertexArrayObject,s.srgbTextures=r||!!n.srgb,s.nonPowOf2wrapping=r,s.nonPowOf2mipmaps=r,s.msaa=r,s.uint32Indices||ie("Provided WebGL context does not support 32 index buffer, large scenes may not render correctly")}};bo.extension={type:[A.WebGLSystem],name:"context"},bo.defaultOptions={context:null,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:void 0,preferWebGLVersion:2,multiView:!1};let Cy=bo;function Ih(i,e){for(const t in i.attributes){const s=i.attributes[t],r=e[t];r?(s.format??(s.format=r.format),s.offset??(s.offset=r.offset),s.instance??(s.instance=r.instance)):ie(`Attribute ${t} is not present in the shader, but is present in the geometry. Unable to infer attribute details.`)}Ey(i)}function Ey(i){const{buffers:e,attributes:t}=i,s={},r={};for(const n in e){const o=e[n];s[o.uid]=0,r[o.uid]=0}for(const n in t){const o=t[n];s[o.buffer.uid]+=Js(o.format).stride}for(const n in t){const o=t[n];o.stride??(o.stride=s[o.buffer.uid]),o.start??(o.start=r[o.buffer.uid]),r[o.buffer.uid]+=Js(o.format).stride}}var vo=(i=>(i[i.RGBA=6408]="RGBA",i[i.RGB=6407]="RGB",i[i.RG=33319]="RG",i[i.RED=6403]="RED",i[i.RGBA_INTEGER=36249]="RGBA_INTEGER",i[i.RGB_INTEGER=36248]="RGB_INTEGER",i[i.RG_INTEGER=33320]="RG_INTEGER",i[i.RED_INTEGER=36244]="RED_INTEGER",i[i.ALPHA=6406]="ALPHA",i[i.LUMINANCE=6409]="LUMINANCE",i[i.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",i[i.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",i[i.DEPTH_STENCIL=34041]="DEPTH_STENCIL",i))(vo||{}),xo=(i=>(i[i.TEXTURE_2D=3553]="TEXTURE_2D",i[i.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",i[i.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",i[i.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",i[i.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",i[i.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",i[i.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",i[i.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",i[i.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",i))(xo||{}),he=(i=>(i[i.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",i[i.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",i[i.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",i[i.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",i[i.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",i[i.UNSIGNED_INT=5125]="UNSIGNED_INT",i[i.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",i[i.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",i[i.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",i[i.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",i[i.BYTE=5120]="BYTE",i[i.SHORT=5122]="SHORT",i[i.INT=5124]="INT",i[i.FLOAT=5126]="FLOAT",i[i.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",i[i.HALF_FLOAT=36193]="HALF_FLOAT",i))(he||{});const Rh={uint8x2:he.UNSIGNED_BYTE,uint8x4:he.UNSIGNED_BYTE,sint8x2:he.BYTE,sint8x4:he.BYTE,unorm8x2:he.UNSIGNED_BYTE,unorm8x4:he.UNSIGNED_BYTE,snorm8x2:he.BYTE,snorm8x4:he.BYTE,uint16x2:he.UNSIGNED_SHORT,uint16x4:he.UNSIGNED_SHORT,sint16x2:he.SHORT,sint16x4:he.SHORT,unorm16x2:he.UNSIGNED_SHORT,unorm16x4:he.UNSIGNED_SHORT,snorm16x2:he.SHORT,snorm16x4:he.SHORT,float16x2:he.HALF_FLOAT,float16x4:he.HALF_FLOAT,float32:he.FLOAT,float32x2:he.FLOAT,float32x3:he.FLOAT,float32x4:he.FLOAT,uint32:he.UNSIGNED_INT,uint32x2:he.UNSIGNED_INT,uint32x3:he.UNSIGNED_INT,uint32x4:he.UNSIGNED_INT,sint32:he.INT,sint32x2:he.INT,sint32x3:he.INT,sint32x4:he.INT};function Sy(i){return Rh[i]??Rh.float32}const Ty={"point-list":0,"line-list":1,"line-strip":3,"triangle-list":4,"triangle-strip":5};class Ay{constructor(){this.vaoCache=Object.create(null)}destroy(){this.vaoCache=Object.create(null)}}class Mh{constructor(e){this._renderer=e,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0,this._managedGeometries=new Rt({renderer:e,type:"resource",onUnload:this.onGeometryUnload.bind(this),name:"glGeometry"})}contextChange(){const e=this.gl=this._renderer.gl;if(!this._renderer.context.supports.vertexArrayObject)throw new Error("[PixiJS] Vertex Array Objects are not supported on this device");this.destroyAll(!0);const t=this._renderer.context.extensions.vertexArrayObject;t&&(e.createVertexArray=()=>t.createVertexArrayOES(),e.bindVertexArray=r=>t.bindVertexArrayOES(r),e.deleteVertexArray=r=>t.deleteVertexArrayOES(r));const s=this._renderer.context.extensions.vertexAttribDivisorANGLE;s&&(e.drawArraysInstanced=(r,n,o,a)=>{s.drawArraysInstancedANGLE(r,n,o,a)},e.drawElementsInstanced=(r,n,o,a,l)=>{s.drawElementsInstancedANGLE(r,n,o,a,l)},e.vertexAttribDivisor=(r,n)=>s.vertexAttribDivisorANGLE(r,n)),this._activeGeometry=null,this._activeVao=null}bind(e,t){const s=this.gl;this._activeGeometry=e;const r=this.getVao(e,t);this._activeVao!==r&&(this._activeVao=r,s.bindVertexArray(r)),this.updateBuffers()}resetState(){this.unbind()}updateBuffers(){const e=this._activeGeometry,t=this._renderer.buffer;for(let s=0;s<e.buffers.length;s++){const r=e.buffers[s];t.updateBuffer(r)}e._gcLastUsed=this._renderer.gc.now}checkCompatibility(e,t){const s=e.attributes,r=t._attributeData;for(const n in r)if(!s[n])throw new Error(`shader and geometry incompatible, geometry missing the "${n}" attribute`)}getSignature(e,t){const s=e.attributes,r=t._attributeData,n=["g",e.uid];for(const o in s)r[o]&&n.push(o,r[o].location);return n.join("-")}getVao(e,t){var s;return((s=e._gpuData[this._renderer.uid])==null?void 0:s.vaoCache[t._key])||this.initGeometryVao(e,t)}initGeometryVao(e,t,s=!0){const r=this._renderer.gl,n=this._renderer.buffer;this._renderer.shader._getProgramData(t),this.checkCompatibility(e,t);const o=this.getSignature(e,t);let a=e._gpuData[this._renderer.uid];a||(a=new Ay,e._gpuData[this._renderer.uid]=a,this._managedGeometries.add(e));const l=a.vaoCache;let c=l[o];if(c)return l[t._key]=c,c;Ih(e,t._attributeData);const h=e.buffers;c=r.createVertexArray(),r.bindVertexArray(c);for(let u=0;u<h.length;u++){const p=h[u];n.bind(p)}return this.activateVao(e,t),l[t._key]=c,l[o]=c,r.bindVertexArray(null),c}onGeometryUnload(e,t=!1){const s=e._gpuData[this._renderer.uid];if(!s)return;const r=s.vaoCache;if(!t)for(const n in r)this._activeVao!==r[n]&&this.resetState(),this.gl.deleteVertexArray(r[n])}destroyAll(e=!1){this._managedGeometries.removeAll(e)}activateVao(e,t){var a;const s=this._renderer.gl,r=this._renderer.buffer,n=e.attributes;e.indexBuffer&&r.bind(e.indexBuffer);let o=null;for(const l in n){const c=n[l],h=c.buffer,u=r.getGlBuffer(h),p=t._attributeData[l];if(p){o!==u&&(r.bind(h),o=u);const d=p.location;s.enableVertexAttribArray(d);const g=Js(c.format),_=Sy(c.format);if(((a=p.format)==null?void 0:a.substring(1,4))==="int"?s.vertexAttribIPointer(d,g.size,_,c.stride,c.offset):s.vertexAttribPointer(d,g.size,_,g.normalised,c.stride,c.offset),c.instance)if(this.hasInstance){const b=c.divisor??1;s.vertexAttribDivisor(d,b)}else throw new Error("geometry error, GPU Instancing is not supported on this device")}}}draw(e,t,s,r){const{gl:n}=this._renderer,o=this._activeGeometry,a=Ty[e||o.topology];if(r??(r=o.instanceCount),o.indexBuffer){const l=o.indexBuffer.data.BYTES_PER_ELEMENT,c=l===2?n.UNSIGNED_SHORT:n.UNSIGNED_INT;r!==1?n.drawElementsInstanced(a,t||o.indexBuffer.data.length,c,(s||0)*l,r):n.drawElements(a,t||o.indexBuffer.data.length,c,(s||0)*l)}else r!==1?n.drawArraysInstanced(a,s||0,t||o.getSize(),r):n.drawArrays(a,s||0,t||o.getSize());return this}unbind(){this.gl.bindVertexArray(null),this._activeVao=null,this._activeGeometry=null}destroy(){this._managedGeometries.destroy(),this._renderer=null,this.gl=null,this._activeVao=null,this._activeGeometry=null}}Mh.extension={type:[A.WebGLSystem],name:"geometry"};const wy=new In({attributes:{aPosition:[-1,-1,3,-1,-1,3]}}),Co=class Sf{constructor(e){this.useBackBuffer=!1,this._useBackBufferThisRender=!1,this._renderer=e}init(e={}){const{useBackBuffer:t,antialias:s}={...Sf.defaultOptions,...e};this.useBackBuffer=t,this._antialias=s,this._renderer.context.supports.msaa||(ie("antialiasing, is not supported on when using the back buffer"),this._antialias=!1),this._state=It.for2d();const r=new Es({vertex:`
|
|
561
561
|
attribute vec2 aPosition;
|
|
562
562
|
out vec2 vUv;
|
|
563
563
|
|
|
@@ -576,7 +576,7 @@ fn mainFragment(
|
|
|
576
576
|
|
|
577
577
|
void main() {
|
|
578
578
|
finalColor = texture(uTexture, vUv);
|
|
579
|
-
}`,name:"big-triangle"});this._bigTriangleShader=new wt({glProgram:r,resources:{uTexture:j.WHITE.source}})}renderStart(e){const t=this._renderer.renderTarget.getRenderTarget(e.target);if(this._useBackBufferThisRender=this.useBackBuffer&&!!t.isRoot,this._useBackBufferThisRender){const s=this._renderer.renderTarget.getRenderTarget(e.target);this._targetTexture=s.colorTexture,e.target=this._getBackBufferTexture(s.colorTexture)}}renderEnd(){this._presentBackBuffer()}_presentBackBuffer(){const e=this._renderer;e.renderTarget.finishRenderPass(),this._useBackBufferThisRender&&(e.renderTarget.bind(this._targetTexture,!1),this._bigTriangleShader.resources.uTexture=this._backBufferTexture.source,e.encoder.draw({geometry:
|
|
579
|
+
}`,name:"big-triangle"});this._bigTriangleShader=new wt({glProgram:r,resources:{uTexture:j.WHITE.source}})}renderStart(e){const t=this._renderer.renderTarget.getRenderTarget(e.target);if(this._useBackBufferThisRender=this.useBackBuffer&&!!t.isRoot,this._useBackBufferThisRender){const s=this._renderer.renderTarget.getRenderTarget(e.target);this._targetTexture=s.colorTexture,e.target=this._getBackBufferTexture(s.colorTexture)}}renderEnd(){this._presentBackBuffer()}_presentBackBuffer(){const e=this._renderer;e.renderTarget.finishRenderPass(),this._useBackBufferThisRender&&(e.renderTarget.bind(this._targetTexture,!1),this._bigTriangleShader.resources.uTexture=this._backBufferTexture.source,e.encoder.draw({geometry:wy,shader:this._bigTriangleShader,state:this._state}))}_getBackBufferTexture(e){return this._backBufferTexture=this._backBufferTexture||new j({source:new De({width:e.width,height:e.height,resolution:e._resolution,antialias:this._antialias})}),this._backBufferTexture.source.resize(e.width,e.height,e._resolution),this._backBufferTexture}destroy(){this._backBufferTexture&&(this._backBufferTexture.destroy(),this._backBufferTexture=null)}};Co.extension={type:[A.WebGLSystem],name:"backBuffer",priority:1},Co.defaultOptions={useBackBuffer:!1};let Iy=Co;class Ph{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.gl.colorMask(!!(e&8),!!(e&4),!!(e&2),!!(e&1)))}}Ph.extension={type:[A.WebGLSystem],name:"colorMask"};class kh{constructor(e){this.commandFinished=Promise.resolve(),this._renderer=e}setGeometry(e,t){this._renderer.geometry.bind(e,t.glProgram)}finishRenderPass(){}draw(e){const t=this._renderer,{geometry:s,shader:r,state:n,skipSync:o,topology:a,size:l,start:c,instanceCount:h}=e;t.shader.bind(r,o),t.geometry.bind(s,t.shader._activeProgram),n&&t.state.set(n),t.geometry.draw(a,l,c,h??s.instanceCount)}destroy(){this._renderer=null}}kh.extension={type:[A.WebGLSystem],name:"encoder"};class Oh{constructor(e){this._renderer=e}contextChange(){const e=this._renderer.gl;this.maxTextures=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),this.maxBatchableTextures=$l(this.maxTextures,e);const t=this._renderer.context.webGLVersion===2;this.maxUniformBindings=t?e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS):0}destroy(){}}Oh.extension={type:[A.WebGLSystem],name:"limits"};class Ry{constructor(){this.width=-1,this.height=-1,this.msaa=!1,this._attachedMipLevel=0,this._attachedLayer=0,this.msaaRenderBuffer=[]}}const Ft=[];Ft[ke.NONE]=void 0,Ft[ke.DISABLED]={stencilWriteMask:0,stencilReadMask:0},Ft[ke.RENDERING_MASK_ADD]={stencilFront:{compare:"equal",passOp:"increment-clamp"},stencilBack:{compare:"equal",passOp:"increment-clamp"}},Ft[ke.RENDERING_MASK_REMOVE]={stencilFront:{compare:"equal",passOp:"decrement-clamp"},stencilBack:{compare:"equal",passOp:"decrement-clamp"}},Ft[ke.MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:"equal",passOp:"keep"},stencilBack:{compare:"equal",passOp:"keep"}},Ft[ke.INVERSE_MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:"not-equal",passOp:"keep"},stencilBack:{compare:"not-equal",passOp:"keep"}};class Bh{constructor(e){this._stencilCache={enabled:!1,stencilReference:0,stencilMode:ke.NONE},this._renderTargetStencilState=Object.create(null),e.renderTarget.onRenderTargetChange.add(this)}contextChange(e){this._gl=e,this._comparisonFuncMapping={always:e.ALWAYS,never:e.NEVER,equal:e.EQUAL,"not-equal":e.NOTEQUAL,less:e.LESS,"less-equal":e.LEQUAL,greater:e.GREATER,"greater-equal":e.GEQUAL},this._stencilOpsMapping={keep:e.KEEP,zero:e.ZERO,replace:e.REPLACE,invert:e.INVERT,"increment-clamp":e.INCR,"decrement-clamp":e.DECR,"increment-wrap":e.INCR_WRAP,"decrement-wrap":e.DECR_WRAP},this.resetState()}onRenderTargetChange(e){if(this._activeRenderTarget===e)return;this._activeRenderTarget=e;let t=this._renderTargetStencilState[e.uid];t||(t=this._renderTargetStencilState[e.uid]={stencilMode:ke.DISABLED,stencilReference:0}),this.setStencilMode(t.stencilMode,t.stencilReference)}resetState(){this._stencilCache.enabled=!1,this._stencilCache.stencilMode=ke.NONE,this._stencilCache.stencilReference=0}setStencilMode(e,t){const s=this._renderTargetStencilState[this._activeRenderTarget.uid],r=this._gl,n=Ft[e],o=this._stencilCache;if(s.stencilMode=e,s.stencilReference=t,e===ke.DISABLED){this._stencilCache.enabled&&(this._stencilCache.enabled=!1,r.disable(r.STENCIL_TEST));return}this._stencilCache.enabled||(this._stencilCache.enabled=!0,r.enable(r.STENCIL_TEST)),(e!==o.stencilMode||o.stencilReference!==t)&&(o.stencilMode=e,o.stencilReference=t,r.stencilFunc(this._comparisonFuncMapping[n.stencilBack.compare],t,255),r.stencilOp(r.KEEP,r.KEEP,this._stencilOpsMapping[n.stencilBack.passOp]))}}Bh.extension={type:[A.WebGLSystem],name:"stencil"};class Dh{constructor(e){this._syncFunctionHash=Object.create(null),this._adaptor=e,this._systemCheck()}_systemCheck(){if(!Tl())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}ensureUniformGroup(e){const t=this.getUniformGroupData(e);e.buffer||(e.buffer=new Ut({data:new Float32Array(t.layout.size/4),usage:Ee.UNIFORM|Ee.COPY_DST}))}getUniformGroupData(e){return this._syncFunctionHash[e._signature]||this._initUniformGroup(e)}_initUniformGroup(e){const t=e._signature;let s=this._syncFunctionHash[t];if(!s){const r=Object.keys(e.uniformStructures).map(a=>e.uniformStructures[a]),n=this._adaptor.createUboElements(r),o=this._generateUboSync(n.uboElements);s=this._syncFunctionHash[t]={layout:n,syncFunction:o}}return this._syncFunctionHash[t]}_generateUboSync(e){return this._adaptor.generateUboSync(e)}syncUniformGroup(e,t,s){const r=this.getUniformGroupData(e);e.buffer||(e.buffer=new Ut({data:new Float32Array(r.layout.size/4),usage:Ee.UNIFORM|Ee.COPY_DST}));let n=null;return t||(t=e.buffer.data,n=e.buffer.dataInt32),s||(s=0),r.syncFunction(e.uniforms,t,n,s),!0}updateUniformGroup(e){if(e.isStatic&&!e._dirtyId)return!1;e._dirtyId=0;const t=this.syncUniformGroup(e);return e.buffer.update(),t}destroy(){this._syncFunctionHash=null}}const Nh={f32:4,i32:4,"vec2<f32>":8,"vec3<f32>":12,"vec4<f32>":16,"vec2<i32>":8,"vec3<i32>":12,"vec4<i32>":16,"mat2x2<f32>":32,"mat3x3<f32>":48,"mat4x4<f32>":64};function My(i){const e=i.map(n=>({data:n,offset:0,size:0})),t=16;let s=0,r=0;for(let n=0;n<e.length;n++){const o=e[n];if(s=Nh[o.data.type],!s)throw new Error(`Unknown type ${o.data.type}`);o.data.size>1&&(s=Math.max(s,t)*o.data.size);const a=s===12?16:s;o.size=s;const l=r%t;l>0&&t-l<a?r+=(t-l)%16:r+=(s-l%s)%s,o.offset=r,r+=s}return r=Math.ceil(r/16)*16,{uboElements:e,size:r}}const os=[{type:"mat3x3<f32>",test:i=>i.value.a!==void 0,ubo:`
|
|
580
580
|
var matrix = uv[name].toArray(true);
|
|
581
581
|
data[offset] = matrix[0];
|
|
582
582
|
data[offset + 1] = matrix[1];
|
|
@@ -699,12 +699,12 @@ fn mainFragment(
|
|
|
699
699
|
data[offset + 10] = v[8];`,"mat4x4<f32>":`
|
|
700
700
|
for (let i = 0; i < 16; i++) {
|
|
701
701
|
data[offset + i] = v[i];
|
|
702
|
-
}`,"mat3x2<f32>":Ms(3,2),"mat4x2<f32>":Ms(4,2),"mat2x3<f32>":Ms(2,3),"mat4x3<f32>":Ms(4,3),"mat2x4<f32>":Ms(2,4),"mat3x4<f32>":Ms(3,4)},
|
|
702
|
+
}`,"mat3x2<f32>":Ms(3,2),"mat4x2<f32>":Ms(4,2),"mat2x3<f32>":Ms(2,3),"mat4x3<f32>":Ms(4,3),"mat2x4<f32>":Ms(2,4),"mat3x4<f32>":Ms(3,4)},Py={...Gh,"mat2x2<f32>":`
|
|
703
703
|
data[offset] = v[0];
|
|
704
704
|
data[offset + 1] = v[1];
|
|
705
705
|
data[offset + 2] = v[2];
|
|
706
706
|
data[offset + 3] = v[3];
|
|
707
|
-
`};function
|
|
707
|
+
`};function ky(i,e){const t=Math.max(Nh[i.data.type]/16,1),s=i.data.value.length/i.data.size,r=(4-s%4)%4,n=i.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
|
|
708
708
|
v = uv.${i.data.name};
|
|
709
709
|
offset += ${e};
|
|
710
710
|
|
|
@@ -720,7 +720,7 @@ fn mainFragment(
|
|
|
720
720
|
}
|
|
721
721
|
${r!==0?`arrayOffset += ${r};`:""}
|
|
722
722
|
}
|
|
723
|
-
`}function
|
|
723
|
+
`}function Oy(i){return Uh(i,"uboStd40",ky,Gh)}class Fh extends Dh{constructor(){super({createUboElements:My,generateUboSync:Oy})}}Fh.extension={type:[A.WebGLSystem],name:"ubo"};class By{constructor(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new Ce}init(e,t){this._renderer=e,this._renderTargetSystem=t,e.runners.contextChange.add(this)}contextChange(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new Ce;const e=this._renderer.gl;this._drawBuffersCache=[];for(let t=1;t<=16;t++)this._drawBuffersCache[t]=Array.from({length:t},(s,r)=>e.COLOR_ATTACHMENT0+r)}copyToTexture(e,t,s,r,n){const o=this._renderTargetSystem,a=this._renderer,l=o.getGpuRenderTarget(e),c=a.gl;return this.finishRenderPass(e),c.bindFramebuffer(c.FRAMEBUFFER,l.resolveTargetFramebuffer),a.texture.bind(t,0),c.copyTexSubImage2D(c.TEXTURE_2D,0,n.x,n.y,s.x,s.y,r.width,r.height),t}startRenderPass(e,t=!0,s,r,n=0,o=0){const a=this._renderTargetSystem,l=e.colorTexture,c=a.getGpuRenderTarget(e);if(o!==0&&this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to array layers requires WebGL2.");if(n>0){if(c.msaa)throw new Error("[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.");if(this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to mip levels requires WebGL2.")}let h=r.y;e.isRoot&&(h=l.pixelHeight-r.height-r.y),e.colorTextures.forEach(d=>{this._renderer.texture.unbind(d)});const u=this._renderer.gl;u.bindFramebuffer(u.FRAMEBUFFER,c.framebuffer),!e.isRoot&&(c._attachedMipLevel!==n||c._attachedLayer!==o)&&(e.colorTextures.forEach((d,g)=>{const _=this._renderer.texture.getGlSource(d);if(_.target===u.TEXTURE_2D){if(o!==0)throw new Error("[RenderTargetSystem] layer must be 0 when rendering to 2D textures in WebGL.");u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0+g,u.TEXTURE_2D,_.texture,n)}else if(_.target===u.TEXTURE_2D_ARRAY){if(this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to 2D array textures requires WebGL2.");u.framebufferTextureLayer(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0+g,_.texture,n,o)}else if(_.target===u.TEXTURE_CUBE_MAP){if(o<0||o>5)throw new Error("[RenderTargetSystem] Cube map layer must be between 0 and 5.");u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0+g,u.TEXTURE_CUBE_MAP_POSITIVE_X+o,_.texture,n)}else throw new Error("[RenderTargetSystem] Unsupported texture target for render-to-layer in WebGL.")}),c._attachedMipLevel=n,c._attachedLayer=o),e.colorTextures.length>1&&this._setDrawBuffers(e,u);const p=this._viewPortCache;(p.x!==r.x||p.y!==h||p.width!==r.width||p.height!==r.height)&&(p.x=r.x,p.y=h,p.width=r.width,p.height=r.height,u.viewport(r.x,h,r.width,r.height)),!c.depthStencilRenderBuffer&&(e.stencil||e.depth)&&this._initStencil(c),this.clear(e,t,s)}finishRenderPass(e){const s=this._renderTargetSystem.getGpuRenderTarget(e);if(!s.msaa)return;const r=this._renderer.gl;r.bindFramebuffer(r.FRAMEBUFFER,s.resolveTargetFramebuffer),r.bindFramebuffer(r.READ_FRAMEBUFFER,s.framebuffer),r.blitFramebuffer(0,0,s.width,s.height,0,0,s.width,s.height,r.COLOR_BUFFER_BIT,r.NEAREST),r.bindFramebuffer(r.FRAMEBUFFER,s.framebuffer)}initGpuRenderTarget(e){const s=this._renderer.gl,r=new Ry;return r._attachedMipLevel=0,r._attachedLayer=0,e.colorTexture instanceof mt?(this._renderer.context.ensureCanvasSize(e.colorTexture.resource),r.framebuffer=null,r):(this._initColor(e,r),s.bindFramebuffer(s.FRAMEBUFFER,null),r)}destroyGpuRenderTarget(e){const t=this._renderer.gl;e.framebuffer&&(t.deleteFramebuffer(e.framebuffer),e.framebuffer=null),e.resolveTargetFramebuffer&&(t.deleteFramebuffer(e.resolveTargetFramebuffer),e.resolveTargetFramebuffer=null),e.depthStencilRenderBuffer&&(t.deleteRenderbuffer(e.depthStencilRenderBuffer),e.depthStencilRenderBuffer=null),e.msaaRenderBuffer.forEach(s=>{t.deleteRenderbuffer(s)}),e.msaaRenderBuffer=null}clear(e,t,s,r,n=0,o=0){if(!t)return;if(o!==0)throw new Error("[RenderTargetSystem] Clearing array layers is not supported in WebGL renderer.");const a=this._renderTargetSystem;typeof t=="boolean"&&(t=t?st.ALL:st.NONE);const l=this._renderer.gl;if(t&st.COLOR){s??(s=a.defaultClearColor);const c=this._clearColorCache,h=s;(c[0]!==h[0]||c[1]!==h[1]||c[2]!==h[2]||c[3]!==h[3])&&(c[0]=h[0],c[1]=h[1],c[2]=h[2],c[3]=h[3],l.clearColor(h[0],h[1],h[2],h[3]))}l.clear(t)}resizeGpuRenderTarget(e){if(e.isRoot)return;const s=this._renderTargetSystem.getGpuRenderTarget(e);this._resizeColor(e,s),(e.stencil||e.depth)&&this._resizeStencil(s)}_initColor(e,t){const s=this._renderer,r=s.gl,n=r.createFramebuffer();if(t.resolveTargetFramebuffer=n,r.bindFramebuffer(r.FRAMEBUFFER,n),t.width=e.colorTexture.source.pixelWidth,t.height=e.colorTexture.source.pixelHeight,e.colorTextures.forEach((a,l)=>{const c=a.source;c.antialias&&(s.context.supports.msaa?t.msaa=!0:ie("[RenderTexture] Antialiasing on textures is not supported in WebGL1")),s.texture.bindSource(c,0);const h=s.texture.getGlSource(c),u=h.texture;if(h.target===r.TEXTURE_2D)r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+l,r.TEXTURE_2D,u,0);else if(h.target===r.TEXTURE_2D_ARRAY){if(s.context.webGLVersion<2)throw new Error("[RenderTargetSystem] TEXTURE_2D_ARRAY requires WebGL2.");r.framebufferTextureLayer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+l,u,0,0)}else if(h.target===r.TEXTURE_CUBE_MAP)r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+l,r.TEXTURE_CUBE_MAP_POSITIVE_X,u,0);else throw new Error("[RenderTargetSystem] Unsupported texture target for framebuffer attachment.")}),t.msaa){const a=r.createFramebuffer();t.framebuffer=a,r.bindFramebuffer(r.FRAMEBUFFER,a),e.colorTextures.forEach((l,c)=>{const h=r.createRenderbuffer();t.msaaRenderBuffer[c]=h})}else t.framebuffer=n;this._resizeColor(e,t)}_resizeColor(e,t){const s=e.colorTexture.source;if(t.width=s.pixelWidth,t.height=s.pixelHeight,t._attachedMipLevel=0,t._attachedLayer=0,e.colorTextures.forEach((r,n)=>{n!==0&&r.source.resize(s.width,s.height,s._resolution)}),t.msaa){const r=this._renderer,n=r.gl,o=t.framebuffer;n.bindFramebuffer(n.FRAMEBUFFER,o),e.colorTextures.forEach((a,l)=>{const c=a.source;r.texture.bindSource(c,0);const u=r.texture.getGlSource(c).internalFormat,p=t.msaaRenderBuffer[l];n.bindRenderbuffer(n.RENDERBUFFER,p),n.renderbufferStorageMultisample(n.RENDERBUFFER,4,u,c.pixelWidth,c.pixelHeight),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+l,n.RENDERBUFFER,p)})}}_initStencil(e){if(e.framebuffer===null)return;const t=this._renderer.gl,s=t.createRenderbuffer();e.depthStencilRenderBuffer=s,t.bindRenderbuffer(t.RENDERBUFFER,s),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,s),this._resizeStencil(e)}_resizeStencil(e){const t=this._renderer.gl;t.bindRenderbuffer(t.RENDERBUFFER,e.depthStencilRenderBuffer),e.msaa?t.renderbufferStorageMultisample(t.RENDERBUFFER,4,t.DEPTH24_STENCIL8,e.width,e.height):t.renderbufferStorage(t.RENDERBUFFER,this._renderer.context.webGLVersion===2?t.DEPTH24_STENCIL8:t.DEPTH_STENCIL,e.width,e.height)}prerender(e){const t=e.colorTexture.resource;this._renderer.context.multiView&&mt.test(t)&&this._renderer.context.ensureCanvasSize(t)}postrender(e){if(this._renderer.context.multiView&&mt.test(e.colorTexture.resource)){const t=this._renderer.context.canvas,s=e.colorTexture;s.context2D.drawImage(t,0,s.pixelHeight-t.height)}}_setDrawBuffers(e,t){const s=e.colorTextures.length,r=this._drawBuffersCache[s];if(this._renderer.context.webGLVersion===1){const n=this._renderer.context.extensions.drawBuffers;n?n.drawBuffersWEBGL(r):ie("[RenderTexture] This WebGL1 context does not support rendering to multiple targets")}else t.drawBuffers(r)}}class Lh extends yo{constructor(e){super(e),this.adaptor=new By,this.adaptor.init(e,this)}}Lh.extension={type:[A.WebGLSystem],name:"renderTarget"};class Eo extends lt{constructor({buffer:e,offset:t,size:s}){super(),this.uid=be("buffer"),this._resourceType="bufferResource",this._touched=0,this._resourceId=be("resource"),this._bufferResource=!0,this.destroyed=!1,this.buffer=e,this.offset=t|0,this.size=s,this.buffer.on("change",this.onBufferChange,this)}onBufferChange(){this._resourceId=be("resource"),this.emit("change",this)}destroy(e=!1){this.destroyed=!0,e&&this.buffer.destroy(),this.emit("change",this),this.buffer=null,this.removeAllListeners()}}function Dy(i,e){const t=[],s=[`
|
|
724
724
|
var g = s.groups;
|
|
725
725
|
var sS = r.shader;
|
|
726
726
|
var p = s.glProgram;
|
|
@@ -747,10 +747,10 @@ fn mainFragment(
|
|
|
747
747
|
`)),e._gl.uniform1i(d.location,n),t.push(`
|
|
748
748
|
tS.bind(resources[${h}], ${n});
|
|
749
749
|
`),n++)}}}const a=[...s,...t].join(`
|
|
750
|
-
`);return new Function("r","s","sD",a)}class
|
|
750
|
+
`);return new Function("r","s","sD",a)}class Ny{constructor(e,t){this.program=e,this.uniformData=t,this.uniformGroups={},this.uniformDirtyGroups={},this.uniformBlockBindings={}}destroy(){this.uniformData=null,this.uniformGroups=null,this.uniformDirtyGroups=null,this.uniformBlockBindings=null,this.program=null}}function Wh(i,e,t){const s=i.createShader(e);return i.shaderSource(s,t),i.compileShader(s),s}function So(i){const e=new Array(i);for(let t=0;t<e.length;t++)e[t]=!1;return e}function Hh(i,e){switch(i){case"float":return 0;case"vec2":return new Float32Array(2*e);case"vec3":return new Float32Array(3*e);case"vec4":return new Float32Array(4*e);case"int":case"uint":case"sampler2D":case"sampler2DArray":return 0;case"ivec2":return new Int32Array(2*e);case"ivec3":return new Int32Array(3*e);case"ivec4":return new Int32Array(4*e);case"uvec2":return new Uint32Array(2*e);case"uvec3":return new Uint32Array(3*e);case"uvec4":return new Uint32Array(4*e);case"bool":return!1;case"bvec2":return So(2*e);case"bvec3":return So(3*e);case"bvec4":return So(4*e);case"mat2":return new Float32Array([1,0,0,1]);case"mat3":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}let hr=null;const Vh={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",UNSIGNED_INT:"uint",UNSIGNED_INT_VEC2:"uvec2",UNSIGNED_INT_VEC3:"uvec3",UNSIGNED_INT_VEC4:"uvec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",INT_SAMPLER_2D:"sampler2D",UNSIGNED_INT_SAMPLER_2D:"sampler2D",SAMPLER_CUBE:"samplerCube",INT_SAMPLER_CUBE:"samplerCube",UNSIGNED_INT_SAMPLER_CUBE:"samplerCube",SAMPLER_2D_ARRAY:"sampler2DArray",INT_SAMPLER_2D_ARRAY:"sampler2DArray",UNSIGNED_INT_SAMPLER_2D_ARRAY:"sampler2DArray"},Uy={float:"float32",vec2:"float32x2",vec3:"float32x3",vec4:"float32x4",int:"sint32",ivec2:"sint32x2",ivec3:"sint32x3",ivec4:"sint32x4",uint:"uint32",uvec2:"uint32x2",uvec3:"uint32x3",uvec4:"uint32x4",bool:"uint32",bvec2:"uint32x2",bvec3:"uint32x3",bvec4:"uint32x4"};function zh(i,e){if(!hr){const t=Object.keys(Vh);hr={};for(let s=0;s<t.length;++s){const r=t[s];hr[i[r]]=Vh[r]}}return hr[e]}function Gy(i,e){const t=zh(i,e);return Uy[t]||"float32"}function Fy(i,e,t=!1){const s={},r=e.getProgramParameter(i,e.ACTIVE_ATTRIBUTES);for(let o=0;o<r;o++){const a=e.getActiveAttrib(i,o);if(a.name.startsWith("gl_"))continue;const l=Gy(e,a.type);s[a.name]={location:0,format:l,stride:Js(l).stride,offset:0,instance:!1,start:0}}const n=Object.keys(s);if(t){n.sort((o,a)=>o>a?1:-1);for(let o=0;o<n.length;o++)s[n[o]].location=o,e.bindAttribLocation(i,o,n[o]);e.linkProgram(i)}else for(let o=0;o<n.length;o++)s[n[o]].location=e.getAttribLocation(i,n[o]);return s}function Ly(i,e){if(!e.ACTIVE_UNIFORM_BLOCKS)return{};const t={},s=e.getProgramParameter(i,e.ACTIVE_UNIFORM_BLOCKS);for(let r=0;r<s;r++){const n=e.getActiveUniformBlockName(i,r),o=e.getUniformBlockIndex(i,n),a=e.getActiveUniformBlockParameter(i,r,e.UNIFORM_BLOCK_DATA_SIZE);t[n]={name:n,index:o,size:a}}return t}function Wy(i,e){const t={},s=e.getProgramParameter(i,e.ACTIVE_UNIFORMS);for(let r=0;r<s;r++){const n=e.getActiveUniform(i,r),o=n.name.replace(/\[.*?\]$/,""),a=!!n.name.match(/\[.*?\]$/),l=zh(e,n.type);t[o]={name:o,index:r,type:l,size:n.size,isArray:a,value:Hh(l,n.size)}}return t}function $h(i,e){const t=i.getShaderSource(e).split(`
|
|
751
751
|
`).map((c,h)=>`${h}: ${c}`),s=i.getShaderInfoLog(e),r=s.split(`
|
|
752
752
|
`),n={},o=r.map(c=>parseFloat(c.replace(/^ERROR\: 0\:([\d]+)\:.*$/,"$1"))).filter(c=>c&&!n[c]?(n[c]=!0,!0):!1),a=[""];o.forEach(c=>{t[c-1]=`%c${t[c-1]}%c`,a.push("background: #FF0000; color:#FFFFFF; font-size: 10px","font-size: 10px")});const l=t.join(`
|
|
753
|
-
`);a[0]=l,console.error(s),console.groupCollapsed("click to view full shader code"),console.warn(...a),console.groupEnd()}function
|
|
753
|
+
`);a[0]=l,console.error(s),console.groupCollapsed("click to view full shader code"),console.warn(...a),console.groupEnd()}function Hy(i,e,t,s){i.getProgramParameter(e,i.LINK_STATUS)||(i.getShaderParameter(t,i.COMPILE_STATUS)||$h(i,t),i.getShaderParameter(s,i.COMPILE_STATUS)||$h(i,s),console.error("PixiJS Error: Could not initialize shader."),i.getProgramInfoLog(e)!==""&&console.warn("PixiJS Warning: gl.getProgramInfoLog()",i.getProgramInfoLog(e)))}function Vy(i,e){const t=Wh(i,i.VERTEX_SHADER,e.vertex),s=Wh(i,i.FRAGMENT_SHADER,e.fragment),r=i.createProgram();i.attachShader(r,t),i.attachShader(r,s);const n=e.transformFeedbackVaryings;n&&(typeof i.transformFeedbackVaryings!="function"?ie("TransformFeedback is not supported but TransformFeedbackVaryings are given."):i.transformFeedbackVaryings(r,n.names,n.bufferMode==="separate"?i.SEPARATE_ATTRIBS:i.INTERLEAVED_ATTRIBS)),i.linkProgram(r),i.getProgramParameter(r,i.LINK_STATUS)||Hy(i,r,t,s),e._attributeData=Fy(r,i,!/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m.test(e.vertex)),e._uniformData=Wy(r,i),e._uniformBlockData=Ly(r,i),i.deleteShader(t),i.deleteShader(s);const o={};for(const l in e._uniformData){const c=e._uniformData[l];o[l]={location:i.getUniformLocation(r,l),value:Hh(c.type,c.size)}}return new Ny(r,o)}const ur={textureCount:0,blockIndex:0};class jh{constructor(e){this._activeProgram=null,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._renderer=e}contextChange(e){this._gl=e,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._activeProgram=null}bind(e,t){if(this._setProgram(e.glProgram),t)return;ur.textureCount=0,ur.blockIndex=0;let s=this._shaderSyncFunctions[e.glProgram._key];s||(s=this._shaderSyncFunctions[e.glProgram._key]=this._generateShaderSync(e,this)),this._renderer.buffer.nextBindBase(!!e.glProgram.transformFeedbackVaryings),s(this._renderer,e,ur)}updateUniformGroup(e){this._renderer.uniformGroup.updateUniformGroup(e,this._activeProgram,ur)}bindUniformBlock(e,t,s=0){const r=this._renderer.buffer,n=this._getProgramData(this._activeProgram),o=e._bufferResource;o||this._renderer.ubo.updateUniformGroup(e);const a=e.buffer,l=r.updateBuffer(a),c=r.freeLocationForBufferBase(l);if(o){const{offset:u,size:p}=e;u===0&&p===a.data.byteLength?r.bindBufferBase(l,c):r.bindBufferRange(l,c,u)}else r.getLastBindBaseLocation(l)!==c&&r.bindBufferBase(l,c);const h=this._activeProgram._uniformBlockData[t].index;n.uniformBlockBindings[s]!==c&&(n.uniformBlockBindings[s]=c,this._renderer.gl.uniformBlockBinding(n.program,h,c))}_setProgram(e){if(this._activeProgram===e)return;this._activeProgram=e;const t=this._getProgramData(e);this._gl.useProgram(t.program)}_getProgramData(e){return this._programDataHash[e._key]||this._createProgramData(e)}_createProgramData(e){const t=e._key;return this._programDataHash[t]=Vy(this._gl,e),this._programDataHash[t]}destroy(){for(const e of Object.keys(this._programDataHash))this._programDataHash[e].destroy();this._programDataHash=null,this._shaderSyncFunctions=null,this._activeProgram=null,this._renderer=null,this._gl=null}_generateShaderSync(e,t){return Dy(e,t)}resetState(){this._activeProgram=null}}jh.extension={type:[A.WebGLSystem],name:"shader"};const zy={f32:`if (cv !== v) {
|
|
754
754
|
cu.value = v;
|
|
755
755
|
gl.uniform1f(location, v);
|
|
756
756
|
}`,"vec2<f32>":`if (cv[0] !== v[0] || cv[1] !== v[1]) {
|
|
@@ -822,7 +822,7 @@ fn mainFragment(
|
|
|
822
822
|
cv[2] = v[2];
|
|
823
823
|
cv[3] = v[3];
|
|
824
824
|
gl.uniform4i(location, v[0], v[1], v[2], v[3]);
|
|
825
|
-
}`,"mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);"}
|
|
825
|
+
}`,"mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);"},$y={f32:"gl.uniform1fv(location, v);","vec2<f32>":"gl.uniform2fv(location, v);","vec3<f32>":"gl.uniform3fv(location, v);","vec4<f32>":"gl.uniform4fv(location, v);","mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);",i32:"gl.uniform1iv(location, v);","vec2<i32>":"gl.uniform2iv(location, v);","vec3<i32>":"gl.uniform3iv(location, v);","vec4<i32>":"gl.uniform4iv(location, v);",u32:"gl.uniform1iv(location, v);","vec2<u32>":"gl.uniform2iv(location, v);","vec3<u32>":"gl.uniform3iv(location, v);","vec4<u32>":"gl.uniform4iv(location, v);",bool:"gl.uniform1iv(location, v);","vec2<bool>":"gl.uniform2iv(location, v);","vec3<bool>":"gl.uniform3iv(location, v);","vec4<bool>":"gl.uniform4iv(location, v);"};function jy(i,e){const t=[`
|
|
826
826
|
var v = null;
|
|
827
827
|
var cv = null;
|
|
828
828
|
var cu = null;
|
|
@@ -835,12 +835,12 @@ fn mainFragment(
|
|
|
835
835
|
renderer.shader.updateUniformGroup(uv.${s});
|
|
836
836
|
`):i.uniforms[s]instanceof Eo&&t.push(`
|
|
837
837
|
renderer.shader.bindBufferResource(uv.${s}, "${s}");
|
|
838
|
-
`);continue}const r=i.uniformStructures[s];let n=!1;for(let o=0;o<os.length;o++){const a=os[o];if(r.type===a.type&&a.test(r)){t.push(`name = "${s}";`,os[o].uniform),n=!0;break}}if(!n){const a=(r.size===1?
|
|
838
|
+
`);continue}const r=i.uniformStructures[s];let n=!1;for(let o=0;o<os.length;o++){const a=os[o];if(r.type===a.type&&a.test(r)){t.push(`name = "${s}";`,os[o].uniform),n=!0;break}}if(!n){const a=(r.size===1?zy:$y)[r.type].replace("location",`ud["${s}"].location`);t.push(`
|
|
839
839
|
cu = ud["${s}"];
|
|
840
840
|
cv = cu.value;
|
|
841
841
|
v = uv["${s}"];
|
|
842
842
|
${a};`)}}return new Function("ud","uv","renderer","syncData",t.join(`
|
|
843
|
-
`))}class Xh{constructor(e){this._cache={},this._uniformGroupSyncHash={},this._renderer=e,this.gl=null,this._cache={}}contextChange(e){this.gl=e}updateUniformGroup(e,t,s){const r=this._renderer.shader._getProgramData(t);(!e.isStatic||e._dirtyId!==r.uniformDirtyGroups[e.uid])&&(r.uniformDirtyGroups[e.uid]=e._dirtyId,this._getUniformSyncFunction(e,t)(r.uniformData,e.uniforms,this._renderer,s))}_getUniformSyncFunction(e,t){var s;return((s=this._uniformGroupSyncHash[e._signature])==null?void 0:s[t._key])||this._createUniformSyncFunction(e,t)}_createUniformSyncFunction(e,t){const s=this._uniformGroupSyncHash[e._signature]||(this._uniformGroupSyncHash[e._signature]={}),r=this._getSignature(e,t._uniformData,"u");return this._cache[r]||(this._cache[r]=this._generateUniformsSync(e,t._uniformData)),s[t._key]=this._cache[r],s[t._key]}_generateUniformsSync(e,t){return $y(e,t)}_getSignature(e,t,s){const r=e.uniforms,n=[`${s}-`];for(const o in r)n.push(o),t[o]&&n.push(t[o].type);return n.join("-")}destroy(){this._renderer=null,this._cache=null}}Xh.extension={type:[A.WebGLSystem],name:"uniformGroup"};function jy(i){const e={};if(e.normal=[i.ONE,i.ONE_MINUS_SRC_ALPHA],e.add=[i.ONE,i.ONE],e.multiply=[i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA],e.screen=[i.ONE,i.ONE_MINUS_SRC_COLOR,i.ONE,i.ONE_MINUS_SRC_ALPHA],e.none=[0,0],e["normal-npm"]=[i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA],e["add-npm"]=[i.SRC_ALPHA,i.ONE,i.ONE,i.ONE],e["screen-npm"]=[i.SRC_ALPHA,i.ONE_MINUS_SRC_COLOR,i.ONE,i.ONE_MINUS_SRC_ALPHA],e.erase=[i.ZERO,i.ONE_MINUS_SRC_ALPHA],!(i instanceof pe.get().getWebGLRenderingContext()))e.min=[i.ONE,i.ONE,i.ONE,i.ONE,i.MIN,i.MIN],e.max=[i.ONE,i.ONE,i.ONE,i.ONE,i.MAX,i.MAX];else{const s=i.getExtension("EXT_blend_minmax");s&&(e.min=[i.ONE,i.ONE,i.ONE,i.ONE,s.MIN_EXT,s.MIN_EXT],e.max=[i.ONE,i.ONE,i.ONE,i.ONE,s.MAX_EXT,s.MAX_EXT])}return e}const Xy=0,Yy=1,qy=2,Ky=3,Zy=4,Jy=5,Yh=class na{constructor(e){this._invertFrontFace=!1,this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode="none",this._blendEq=!1,this.map=[],this.map[Xy]=this.setBlend,this.map[Yy]=this.setOffset,this.map[qy]=this.setCullFace,this.map[Ky]=this.setDepthTest,this.map[Zy]=this.setFrontFace,this.map[Jy]=this.setDepthMask,this.checks=[],this.defaultState=It.for2d(),e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){this._invertFrontFace=!e.isRoot,this._cullFace?this.setFrontFace(this._frontFace):this._frontFaceDirty=!0}contextChange(e){this.gl=e,this.blendModesMap=jy(e),this.resetState()}set(e){if(e||(e=this.defaultState),this.stateId!==e.data){let t=this.stateId^e.data,s=0;for(;t;)t&1&&this.map[s].call(this,!!(e.data&1<<s)),t>>=1,s++;this.stateId=e.data}for(let t=0;t<this.checks.length;t++)this.checks[t](this,e)}forceState(e){e||(e=this.defaultState);for(let t=0;t<this.map.length;t++)this.map[t].call(this,!!(e.data&1<<t));for(let t=0;t<this.checks.length;t++)this.checks[t](this,e);this.stateId=e.data}setBlend(e){this._updateCheck(na._checkBlendMode,e),this.gl[e?"enable":"disable"](this.gl.BLEND)}setOffset(e){this._updateCheck(na._checkPolygonOffset,e),this.gl[e?"enable":"disable"](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(e){this.gl[e?"enable":"disable"](this.gl.DEPTH_TEST)}setDepthMask(e){this.gl.depthMask(e)}setCullFace(e){this._cullFace=e,this.gl[e?"enable":"disable"](this.gl.CULL_FACE),this._cullFace&&this._frontFaceDirty&&this.setFrontFace(this._frontFace)}setFrontFace(e){this._frontFace=e,this._frontFaceDirty=!1;const t=this._invertFrontFace?!e:e;this._glFrontFace!==t&&(this._glFrontFace=t,this.gl.frontFace(this.gl[t?"CW":"CCW"]))}setBlendMode(e){if(this.blendModesMap[e]||(e="normal"),e===this.blendMode)return;this.blendMode=e;const t=this.blendModesMap[e],s=this.gl;t.length===2?s.blendFunc(t[0],t[1]):s.blendFuncSeparate(t[0],t[1],t[2],t[3]),t.length===6?(this._blendEq=!0,s.blendEquationSeparate(t[4],t[5])):this._blendEq&&(this._blendEq=!1,s.blendEquationSeparate(s.FUNC_ADD,s.FUNC_ADD))}setPolygonOffset(e,t){this.gl.polygonOffset(e,t)}resetState(){this._glFrontFace=!1,this._frontFace=!1,this._cullFace=!1,this._frontFaceDirty=!1,this._invertFrontFace=!1,this.gl.frontFace(this.gl.CCW),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode="",this.setBlendMode("normal")}_updateCheck(e,t){const s=this.checks.indexOf(e);t&&s===-1?this.checks.push(e):!t&&s!==-1&&this.checks.splice(s,1)}static _checkBlendMode(e,t){e.setBlendMode(t.blendMode)}static _checkPolygonOffset(e,t){e.setPolygonOffset(1,t.polygonOffset)}destroy(){this.gl=null,this.checks.length=0}};Yh.extension={type:[A.WebGLSystem],name:"state"};let Qy=Yh;class eb{constructor(e){this.target=xo.TEXTURE_2D,this._layerInitMask=0,this.texture=e,this.width=-1,this.height=-1,this.type=he.UNSIGNED_BYTE,this.internalFormat=vo.RGBA,this.format=vo.RGBA,this.samplerType=0}destroy(){}}const tb={id:"buffer",upload(i,e,t,s,r,n=!1){const o=r||e.target;!n&&e.width===i.width&&e.height===i.height?t.texSubImage2D(o,0,0,0,i.width,i.height,e.format,e.type,i.resource):t.texImage2D(o,0,e.internalFormat,i.width,i.height,0,e.format,e.type,i.resource),e.width=i.width,e.height=i.height}},sb={"bc1-rgba-unorm":!0,"bc1-rgba-unorm-srgb":!0,"bc2-rgba-unorm":!0,"bc2-rgba-unorm-srgb":!0,"bc3-rgba-unorm":!0,"bc3-rgba-unorm-srgb":!0,"bc4-r-unorm":!0,"bc4-r-snorm":!0,"bc5-rg-unorm":!0,"bc5-rg-snorm":!0,"bc6h-rgb-ufloat":!0,"bc6h-rgb-float":!0,"bc7-rgba-unorm":!0,"bc7-rgba-unorm-srgb":!0,"etc2-rgb8unorm":!0,"etc2-rgb8unorm-srgb":!0,"etc2-rgb8a1unorm":!0,"etc2-rgb8a1unorm-srgb":!0,"etc2-rgba8unorm":!0,"etc2-rgba8unorm-srgb":!0,"eac-r11unorm":!0,"eac-r11snorm":!0,"eac-rg11unorm":!0,"eac-rg11snorm":!0,"astc-4x4-unorm":!0,"astc-4x4-unorm-srgb":!0,"astc-5x4-unorm":!0,"astc-5x4-unorm-srgb":!0,"astc-5x5-unorm":!0,"astc-5x5-unorm-srgb":!0,"astc-6x5-unorm":!0,"astc-6x5-unorm-srgb":!0,"astc-6x6-unorm":!0,"astc-6x6-unorm-srgb":!0,"astc-8x5-unorm":!0,"astc-8x5-unorm-srgb":!0,"astc-8x6-unorm":!0,"astc-8x6-unorm-srgb":!0,"astc-8x8-unorm":!0,"astc-8x8-unorm-srgb":!0,"astc-10x5-unorm":!0,"astc-10x5-unorm-srgb":!0,"astc-10x6-unorm":!0,"astc-10x6-unorm-srgb":!0,"astc-10x8-unorm":!0,"astc-10x8-unorm-srgb":!0,"astc-10x10-unorm":!0,"astc-10x10-unorm-srgb":!0,"astc-12x10-unorm":!0,"astc-12x10-unorm-srgb":!0,"astc-12x12-unorm":!0,"astc-12x12-unorm-srgb":!0},ib={id:"compressed",upload(i,e,t,s,r,n){const o=r??e.target;t.pixelStorei(t.UNPACK_ALIGNMENT,4);let a=i.pixelWidth,l=i.pixelHeight;const c=!!sb[i.format];for(let h=0;h<i.resource.length;h++){const u=i.resource[h];c?t.compressedTexImage2D(o,h,e.internalFormat,a,l,0,u):t.texImage2D(o,h,e.internalFormat,a,l,0,e.format,e.type,u),a=Math.max(a>>1,1),l=Math.max(l>>1,1)}}},qh=["right","left","top","bottom","front","back"];function rb(i){return{id:"cube",upload(e,t,s,r){const n=e.faces;for(let o=0;o<qh.length;o++){const a=qh[o],l=n[a];(i[l.uploadMethodId]||i.image).upload(l,t,s,r,xo.TEXTURE_CUBE_MAP_POSITIVE_X+o,(t._layerInitMask&1<<o)===0),t._layerInitMask|=1<<o}t.width=e.pixelWidth,t.height=e.pixelHeight}}}const Kh={id:"image",upload(i,e,t,s,r,n=!1){const o=r||e.target,a=i.pixelWidth,l=i.pixelHeight,c=i.resourceWidth,h=i.resourceHeight,u=s===2,p=n||e.width!==a||e.height!==l,d=c>=a&&h>=l,g=i.resource;(u?nb:ob)(t,o,e,a,l,c,h,g,p,d),e.width=a,e.height=l}};function nb(i,e,t,s,r,n,o,a,l,c){if(!c){l&&i.texImage2D(e,0,t.internalFormat,s,r,0,t.format,t.type,null),i.texSubImage2D(e,0,0,0,n,o,t.format,t.type,a);return}if(!l){i.texSubImage2D(e,0,0,0,t.format,t.type,a);return}i.texImage2D(e,0,t.internalFormat,s,r,0,t.format,t.type,a)}function ob(i,e,t,s,r,n,o,a,l,c){if(!c){l&&i.texImage2D(e,0,t.internalFormat,s,r,0,t.format,t.type,null),i.texSubImage2D(e,0,0,0,t.format,t.type,a);return}if(!l){i.texSubImage2D(e,0,0,0,t.format,t.type,a);return}i.texImage2D(e,0,t.internalFormat,t.format,t.type,a)}const ab=k_(),lb={id:"video",upload(i,e,t,s,r,n=ab){if(!i.isValid){const o=r??e.target;t.texImage2D(o,0,e.internalFormat,1,1,0,e.format,e.type,null);return}Kh.upload(i,e,t,s,r,n)}},Zh={linear:9729,nearest:9728},cb={linear:{linear:9987,nearest:9985},nearest:{linear:9986,nearest:9984}},To={"clamp-to-edge":33071,repeat:10497,"mirror-repeat":33648},hb={never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519};function Jh(i,e,t,s,r,n,o,a){const l=n;if(!a||i.addressModeU!=="repeat"||i.addressModeV!=="repeat"||i.addressModeW!=="repeat"){const c=To[o?"clamp-to-edge":i.addressModeU],h=To[o?"clamp-to-edge":i.addressModeV],u=To[o?"clamp-to-edge":i.addressModeW];e[r](l,e.TEXTURE_WRAP_S,c),e[r](l,e.TEXTURE_WRAP_T,h),e.TEXTURE_WRAP_R&&e[r](l,e.TEXTURE_WRAP_R,u)}if((!a||i.magFilter!=="linear")&&e[r](l,e.TEXTURE_MAG_FILTER,Zh[i.magFilter]),t){if(!a||i.mipmapFilter!=="linear"){const c=cb[i.minFilter][i.mipmapFilter];e[r](l,e.TEXTURE_MIN_FILTER,c)}}else e[r](l,e.TEXTURE_MIN_FILTER,Zh[i.minFilter]);if(s&&i.maxAnisotropy>1){const c=Math.min(i.maxAnisotropy,e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT));e[r](l,s.TEXTURE_MAX_ANISOTROPY_EXT,c)}i.compare&&e[r](l,e.TEXTURE_COMPARE_FUNC,hb[i.compare])}function ub(i){return{r8unorm:i.RED,r8snorm:i.RED,r8uint:i.RED,r8sint:i.RED,r16uint:i.RED,r16sint:i.RED,r16float:i.RED,rg8unorm:i.RG,rg8snorm:i.RG,rg8uint:i.RG,rg8sint:i.RG,r32uint:i.RED,r32sint:i.RED,r32float:i.RED,rg16uint:i.RG,rg16sint:i.RG,rg16float:i.RG,rgba8unorm:i.RGBA,"rgba8unorm-srgb":i.RGBA,rgba8snorm:i.RGBA,rgba8uint:i.RGBA,rgba8sint:i.RGBA,bgra8unorm:i.RGBA,"bgra8unorm-srgb":i.RGBA,rgb9e5ufloat:i.RGB,rgb10a2unorm:i.RGBA,rg11b10ufloat:i.RGB,rg32uint:i.RG,rg32sint:i.RG,rg32float:i.RG,rgba16uint:i.RGBA,rgba16sint:i.RGBA,rgba16float:i.RGBA,rgba32uint:i.RGBA,rgba32sint:i.RGBA,rgba32float:i.RGBA,stencil8:i.STENCIL_INDEX8,depth16unorm:i.DEPTH_COMPONENT,depth24plus:i.DEPTH_COMPONENT,"depth24plus-stencil8":i.DEPTH_STENCIL,depth32float:i.DEPTH_COMPONENT,"depth32float-stencil8":i.DEPTH_STENCIL}}function db(i,e){let t={},s=i.RGBA;return i instanceof pe.get().getWebGLRenderingContext()?e.srgb&&(t={"rgba8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT}):(t={"rgba8unorm-srgb":i.SRGB8_ALPHA8,"bgra8unorm-srgb":i.SRGB8_ALPHA8},s=i.RGBA8),{r8unorm:i.R8,r8snorm:i.R8_SNORM,r8uint:i.R8UI,r8sint:i.R8I,r16uint:i.R16UI,r16sint:i.R16I,r16float:i.R16F,rg8unorm:i.RG8,rg8snorm:i.RG8_SNORM,rg8uint:i.RG8UI,rg8sint:i.RG8I,r32uint:i.R32UI,r32sint:i.R32I,r32float:i.R32F,rg16uint:i.RG16UI,rg16sint:i.RG16I,rg16float:i.RG16F,rgba8unorm:i.RGBA,...t,rgba8snorm:i.RGBA8_SNORM,rgba8uint:i.RGBA8UI,rgba8sint:i.RGBA8I,bgra8unorm:s,rgb9e5ufloat:i.RGB9_E5,rgb10a2unorm:i.RGB10_A2,rg11b10ufloat:i.R11F_G11F_B10F,rg32uint:i.RG32UI,rg32sint:i.RG32I,rg32float:i.RG32F,rgba16uint:i.RGBA16UI,rgba16sint:i.RGBA16I,rgba16float:i.RGBA16F,rgba32uint:i.RGBA32UI,rgba32sint:i.RGBA32I,rgba32float:i.RGBA32F,stencil8:i.STENCIL_INDEX8,depth16unorm:i.DEPTH_COMPONENT16,depth24plus:i.DEPTH_COMPONENT24,"depth24plus-stencil8":i.DEPTH24_STENCIL8,depth32float:i.DEPTH_COMPONENT32F,"depth32float-stencil8":i.DEPTH32F_STENCIL8,...e.s3tc?{"bc1-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT1_EXT,"bc2-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT3_EXT,"bc3-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT5_EXT}:{},...e.s3tc_sRGB?{"bc1-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,"bc2-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,"bc3-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}:{},...e.rgtc?{"bc4-r-unorm":e.rgtc.COMPRESSED_RED_RGTC1_EXT,"bc4-r-snorm":e.rgtc.COMPRESSED_SIGNED_RED_RGTC1_EXT,"bc5-rg-unorm":e.rgtc.COMPRESSED_RED_GREEN_RGTC2_EXT,"bc5-rg-snorm":e.rgtc.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}:{},...e.bptc?{"bc6h-rgb-float":e.bptc.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT,"bc6h-rgb-ufloat":e.bptc.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT,"bc7-rgba-unorm":e.bptc.COMPRESSED_RGBA_BPTC_UNORM_EXT,"bc7-rgba-unorm-srgb":e.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT}:{},...e.etc?{"etc2-rgb8unorm":e.etc.COMPRESSED_RGB8_ETC2,"etc2-rgb8unorm-srgb":e.etc.COMPRESSED_SRGB8_ETC2,"etc2-rgb8a1unorm":e.etc.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgb8a1unorm-srgb":e.etc.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgba8unorm":e.etc.COMPRESSED_RGBA8_ETC2_EAC,"etc2-rgba8unorm-srgb":e.etc.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,"eac-r11unorm":e.etc.COMPRESSED_R11_EAC,"eac-rg11unorm":e.etc.COMPRESSED_SIGNED_RG11_EAC}:{},...e.astc?{"astc-4x4-unorm":e.astc.COMPRESSED_RGBA_ASTC_4x4_KHR,"astc-4x4-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,"astc-5x4-unorm":e.astc.COMPRESSED_RGBA_ASTC_5x4_KHR,"astc-5x4-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,"astc-5x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_5x5_KHR,"astc-5x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,"astc-6x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_6x5_KHR,"astc-6x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,"astc-6x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_6x6_KHR,"astc-6x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,"astc-8x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x5_KHR,"astc-8x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,"astc-8x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x6_KHR,"astc-8x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,"astc-8x8-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x8_KHR,"astc-8x8-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,"astc-10x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x5_KHR,"astc-10x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,"astc-10x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x6_KHR,"astc-10x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,"astc-10x8-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x8_KHR,"astc-10x8-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,"astc-10x10-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x10_KHR,"astc-10x10-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,"astc-12x10-unorm":e.astc.COMPRESSED_RGBA_ASTC_12x10_KHR,"astc-12x10-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,"astc-12x12-unorm":e.astc.COMPRESSED_RGBA_ASTC_12x12_KHR,"astc-12x12-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR}:{}}}function fb(i){return{r8unorm:i.UNSIGNED_BYTE,r8snorm:i.BYTE,r8uint:i.UNSIGNED_BYTE,r8sint:i.BYTE,r16uint:i.UNSIGNED_SHORT,r16sint:i.SHORT,r16float:i.HALF_FLOAT,rg8unorm:i.UNSIGNED_BYTE,rg8snorm:i.BYTE,rg8uint:i.UNSIGNED_BYTE,rg8sint:i.BYTE,r32uint:i.UNSIGNED_INT,r32sint:i.INT,r32float:i.FLOAT,rg16uint:i.UNSIGNED_SHORT,rg16sint:i.SHORT,rg16float:i.HALF_FLOAT,rgba8unorm:i.UNSIGNED_BYTE,"rgba8unorm-srgb":i.UNSIGNED_BYTE,rgba8snorm:i.BYTE,rgba8uint:i.UNSIGNED_BYTE,rgba8sint:i.BYTE,bgra8unorm:i.UNSIGNED_BYTE,"bgra8unorm-srgb":i.UNSIGNED_BYTE,rgb9e5ufloat:i.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:i.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:i.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:i.UNSIGNED_INT,rg32sint:i.INT,rg32float:i.FLOAT,rgba16uint:i.UNSIGNED_SHORT,rgba16sint:i.SHORT,rgba16float:i.HALF_FLOAT,rgba32uint:i.UNSIGNED_INT,rgba32sint:i.INT,rgba32float:i.FLOAT,stencil8:i.UNSIGNED_BYTE,depth16unorm:i.UNSIGNED_SHORT,depth24plus:i.UNSIGNED_INT,"depth24plus-stencil8":i.UNSIGNED_INT_24_8,depth32float:i.FLOAT,"depth32float-stencil8":i.FLOAT_32_UNSIGNED_INT_24_8_REV}}function pb(i){return{"2d":i.TEXTURE_2D,cube:i.TEXTURE_CUBE_MAP,"1d":null,"3d":(i==null?void 0:i.TEXTURE_3D)||null,"2d-array":(i==null?void 0:i.TEXTURE_2D_ARRAY)||null,"cube-array":(i==null?void 0:i.TEXTURE_CUBE_MAP_ARRAY)||null}}const mb=4;class Qh{constructor(e){this._glSamplers=Object.create(null),this._boundTextures=[],this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1,this._useSeparateSamplers=!1,this._renderer=e,this._managedTextures=new Rt({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"glTexture"});const t={image:Kh,buffer:tb,video:lb,compressed:ib};this._uploads={...t,cube:rb(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gl=e,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=db(e,this._renderer.context.extensions),this._mapFormatToType=fb(e),this._mapFormatToFormat=ub(e),this._mapViewDimensionToGlTarget=pb(e)),this._managedTextures.removeAll(!0),this._glSamplers=Object.create(null),this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1;for(let t=0;t<16;t++)this.bind(j.EMPTY,t)}initSource(e){this.bind(e)}bind(e,t=0){const s=e.source;e?(this.bindSource(s,t),this._useSeparateSamplers&&this._bindSampler(s.style,t)):(this.bindSource(null,t),this._useSeparateSamplers&&this._bindSampler(null,t))}bindSource(e,t=0){const s=this._gl;if(e._gcLastUsed=this._renderer.gc.now,this._boundTextures[t]!==e){this._boundTextures[t]=e,this._activateLocation(t),e||(e=j.EMPTY.source);const r=this.getGlSource(e);s.bindTexture(r.target,r.texture)}}_bindSampler(e,t=0){const s=this._gl;if(!e){this._boundSamplers[t]=null,s.bindSampler(t,null);return}const r=this._getGlSampler(e);this._boundSamplers[t]!==r&&(this._boundSamplers[t]=r,s.bindSampler(t,r))}unbind(e){const t=e.source,s=this._boundTextures,r=this._gl;for(let n=0;n<s.length;n++)if(s[n]===t){this._activateLocation(n);const o=this.getGlSource(t);r.bindTexture(o.target,null),s[n]=null}}_activateLocation(e){this._activeTextureLocation!==e&&(this._activeTextureLocation=e,this._gl.activeTexture(this._gl.TEXTURE0+e))}_initSource(e){const t=this._gl,s=new eb(t.createTexture());if(s.type=this._mapFormatToType[e.format],s.internalFormat=this._mapFormatToInternalFormat[e.format],s.format=this._mapFormatToFormat[e.format],s.target=this._mapViewDimensionToGlTarget[e.viewDimension],s.target===null)throw new Error(`Unsupported view dimension: ${e.viewDimension} with this webgl version: ${this._renderer.context.webGLVersion}`);if(e.uploadMethodId==="cube"&&(s.target=t.TEXTURE_CUBE_MAP),e.autoGenerateMipmaps&&(this._renderer.context.supports.nonPowOf2mipmaps||e.isPowerOfTwo)){const n=Math.max(e.width,e.height);e.mipLevelCount=Math.floor(Math.log2(n))+1}return e._gpuData[this._renderer.uid]=s,this._managedTextures.add(e)&&(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceUpdate,this),e.on("styleChange",this.onStyleChange,this),e.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(e),this.updateStyle(e,!1),s}onStyleChange(e){this.updateStyle(e,!1)}updateStyle(e,t){const s=this._gl,r=this.getGlSource(e);s.bindTexture(r.target,r.texture),this._boundTextures[this._activeTextureLocation]=e,Jh(e.style,s,e.mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"texParameteri",r.target,!this._renderer.context.supports.nonPowOf2wrapping&&!e.isPowerOfTwo,t)}onSourceUnload(e,t=!1){const s=e._gpuData[this._renderer.uid];s&&(t||(this.unbind(e),this._gl.deleteTexture(s.texture)),e.off("update",this.onSourceUpdate,this),e.off("resize",this.onSourceUpdate,this),e.off("styleChange",this.onStyleChange,this),e.off("updateMipmaps",this.onUpdateMipmaps,this))}onSourceUpdate(e){const t=this._gl,s=this.getGlSource(e);t.bindTexture(s.target,s.texture),this._boundTextures[this._activeTextureLocation]=e;const r=e.alphaMode==="premultiply-alpha-on-upload";if(this._premultiplyAlpha!==r&&(this._premultiplyAlpha=r,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,r)),this._uploads[e.uploadMethodId])this._uploads[e.uploadMethodId].upload(e,s,t,this._renderer.context.webGLVersion);else if(s.target===t.TEXTURE_2D)this._initEmptyTexture2D(s,e);else if(s.target===t.TEXTURE_2D_ARRAY)this._initEmptyTexture2DArray(s,e);else if(s.target===t.TEXTURE_CUBE_MAP)this._initEmptyTextureCube(s,e);else throw new Error("[GlTextureSystem] Unsupported texture target for empty allocation.");this._applyMipRange(s,e),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e,!1)}onUpdateMipmaps(e,t=!0){t&&this.bindSource(e,0);const s=this.getGlSource(e);this._gl.generateMipmap(s.target)}_initEmptyTexture2D(e,t){const s=this._gl;s.texImage2D(s.TEXTURE_2D,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let r=Math.max(t.pixelWidth>>1,1),n=Math.max(t.pixelHeight>>1,1);for(let o=1;o<t.mipLevelCount;o++)s.texImage2D(s.TEXTURE_2D,o,e.internalFormat,r,n,0,e.format,e.type,null),r=Math.max(r>>1,1),n=Math.max(n>>1,1)}_initEmptyTexture2DArray(e,t){if(this._renderer.context.webGLVersion!==2)throw new Error("[GlTextureSystem] TEXTURE_2D_ARRAY requires WebGL2.");const s=this._gl,r=Math.max(t.arrayLayerCount|0,1);s.texImage3D(s.TEXTURE_2D_ARRAY,0,e.internalFormat,t.pixelWidth,t.pixelHeight,r,0,e.format,e.type,null);let n=Math.max(t.pixelWidth>>1,1),o=Math.max(t.pixelHeight>>1,1);for(let a=1;a<t.mipLevelCount;a++)s.texImage3D(s.TEXTURE_2D_ARRAY,a,e.internalFormat,n,o,r,0,e.format,e.type,null),n=Math.max(n>>1,1),o=Math.max(o>>1,1)}_initEmptyTextureCube(e,t){const s=this._gl,r=6;for(let a=0;a<r;a++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+a,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let n=Math.max(t.pixelWidth>>1,1),o=Math.max(t.pixelHeight>>1,1);for(let a=1;a<t.mipLevelCount;a++){for(let l=0;l<r;l++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,a,e.internalFormat,n,o,0,e.format,e.type,null);n=Math.max(n>>1,1),o=Math.max(o>>1,1)}}_applyMipRange(e,t){if(this._renderer.context.webGLVersion!==2)return;const s=this._gl,r=Math.max((t.mipLevelCount|0)-1,0);s.texParameteri(e.target,s.TEXTURE_BASE_LEVEL,0),s.texParameteri(e.target,s.TEXTURE_MAX_LEVEL,r)}_initSampler(e){const t=this._gl,s=this._gl.createSampler();return this._glSamplers[e._resourceId]=s,Jh(e,t,this._boundTextures[this._activeTextureLocation].mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"samplerParameteri",s,!1,!0),this._glSamplers[e._resourceId]}_getGlSampler(e){return this._glSamplers[e._resourceId]||this._initSampler(e)}getGlSource(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]||this._initSource(e)}generateCanvas(e){const{pixels:t,width:s,height:r}=this.getPixels(e),n=pe.get().createCanvas();n.width=s,n.height=r;const o=n.getContext("2d");if(o){const a=o.createImageData(s,r);a.data.set(t),o.putImageData(a,0,0)}return n}getPixels(e){const t=e.source.resolution,s=e.frame,r=Math.max(Math.round(s.width*t),1),n=Math.max(Math.round(s.height*t),1),o=new Uint8Array(mb*r*n),a=this._renderer,l=a.renderTarget.getRenderTarget(e),c=a.renderTarget.getGpuRenderTarget(l),h=a.gl;return h.bindFramebuffer(h.FRAMEBUFFER,c.resolveTargetFramebuffer),h.readPixels(Math.round(s.x*t),Math.round(s.y*t),r,n,h.RGBA,h.UNSIGNED_BYTE,o),{pixels:new Uint8ClampedArray(o.buffer),width:r,height:n}}destroy(){this._managedTextures.destroy(),this._glSamplers=null,this._boundTextures=null,this._boundSamplers=null,this._mapFormatToInternalFormat=null,this._mapFormatToType=null,this._mapFormatToFormat=null,this._uploads=null,this._renderer=null}resetState(){this._activeTextureLocation=-1,this._boundTextures.fill(j.EMPTY.source),this._boundSamplers=Object.create(null);const e=this._gl;this._premultiplyAlpha=!1,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this._premultiplyAlpha)}}Qh.extension={type:[A.WebGLSystem],name:"texture"};class eu{contextChange(e){const t=new gt({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new H,type:"mat3x3<f32>"},uRound:{value:0,type:"f32"}}),s=e.limits.maxBatchableTextures,r=Pn({name:"graphics",bits:[nc,ac(s),Jc,Dn]});this.shader=new wt({glProgram:r,resources:{localUniforms:t,batchSamplers:cc(s)}})}execute(e,t){const s=t.context,r=s.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(s);r.groups[0]=n.globalUniforms.bindGroup,n.state.set(e.state),n.shader.bind(r),n.geometry.bind(a.geometry,r.glProgram);const c=l.instructions;for(let h=0;h<l.instructionSize;h++){const u=c[h];if(u.size){for(let p=0;p<u.textures.count;p++)n.texture.bind(u.textures.textures[p],p);n.geometry.draw(u.topology,u.size,u.start)}}}destroy(){this.shader.destroy(!0),this.shader=null}}eu.extension={type:[A.WebGLPipesAdaptor],name:"graphics"};class tu{init(){const e=Pn({name:"mesh",bits:[Jc,D_,Dn]});this._shader=new wt({glProgram:e,resources:{uTexture:j.EMPTY.source,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new H}}}})}execute(e,t){const s=e.renderer;let r=t._shader;if(r){if(!r.glProgram){ie("Mesh shader has no glProgram",t.shader);return}}else{r=this._shader;const n=t.texture,o=n.source;r.resources.uTexture=o,r.resources.uSampler=o.style,r.resources.textureUniforms.uniforms.uTextureMatrix=n.textureMatrix.mapCoord}r.groups[100]=s.globalUniforms.bindGroup,r.groups[101]=e.localUniformsBindGroup,s.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}tu.extension={type:[A.WebGLPipesAdaptor],name:"mesh"};const gb=[..._o,Fh,wy,xy,Oh,wh,Qh,Lh,Mh,Xh,jh,kh,Qy,Bh,Ph],_b=[...xh],yb=[eh,tu,eu],su=[],iu=[],ru=[];Q.handleByNamedList(A.WebGLSystem,su),Q.handleByNamedList(A.WebGLPipes,iu),Q.handleByNamedList(A.WebGLPipesAdaptor,ru),Q.add(...gb,..._b,...yb);class bb extends ni{constructor(){const e={name:"webgl",type:_t.WEBGL,systems:su,renderPipes:iu,renderPipeAdaptors:ru};super(e)}}const vb=Object.freeze(Object.defineProperty({__proto__:null,WebGLRenderer:bb},Symbol.toStringTag,{value:"Module"}));class nu{constructor(e){this._hash=Object.create(null),this._renderer=e}contextChange(e){this._gpu=e}getBindGroup(e,t,s){return e._updateKey(),this._hash[e._key]||this._createBindGroup(e,t,s)}_createBindGroup(e,t,s){const r=this._gpu.device,n=t.layout[s],o=[],a=this._renderer;for(const h in n){const u=e.resources[h]??e.resources[n[h]];let p;if(u._resourceType==="uniformGroup"){const d=u;a.ubo.updateUniformGroup(d);const g=d.buffer;p={buffer:a.buffer.getGPUBuffer(g),offset:0,size:g.descriptor.size}}else if(u._resourceType==="buffer"){const d=u;p={buffer:a.buffer.getGPUBuffer(d),offset:0,size:d.descriptor.size}}else if(u._resourceType==="bufferResource"){const d=u;p={buffer:a.buffer.getGPUBuffer(d.buffer),offset:d.offset,size:d.size}}else if(u._resourceType==="textureSampler"){const d=u;p=a.texture.getGpuSampler(d)}else if(u._resourceType==="textureSource"){const d=u;p=a.texture.getTextureView(d)}o.push({binding:n[h],resource:p})}const l=a.shader.getProgramData(t).bindGroups[s],c=r.createBindGroup({layout:l,entries:o});return this._hash[e._key]=c,c}destroy(){this._hash=null,this._renderer=null}}nu.extension={type:[A.WebGPUSystem],name:"bindGroup"};class xb{constructor(e){this.gpuBuffer=e}destroy(){this.gpuBuffer.destroy(),this.gpuBuffer=null}}class ou{constructor(e){this._renderer=e,this._managedBuffers=new Rt({renderer:e,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"gpuBuffer"})}contextChange(e){this._gpu=e}getGPUBuffer(e){var t;return e._gcLastUsed=this._renderer.gc.now,((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuBuffer)||this.createGPUBuffer(e)}updateBuffer(e){const t=this.getGPUBuffer(e),s=e.data;return e._updateID&&s&&(e._updateID=0,this._gpu.device.queue.writeBuffer(t,0,s.buffer,0,(e._updateSize||s.byteLength)+3&-4)),t}destroyAll(){this._managedBuffers.removeAll()}onBufferUnload(e){e.off("update",this.updateBuffer,this),e.off("change",this.onBufferChange,this)}createGPUBuffer(e){const t=this._gpu.device.createBuffer(e.descriptor);return e._updateID=0,e._resourceId=be("resource"),e.data&&(wn(e.data.buffer,t.getMappedRange(),e.data.byteOffset,e.data.byteLength),t.unmap()),e._gpuData[this._renderer.uid]=new xb(t),this._managedBuffers.add(e)&&(e.on("update",this.updateBuffer,this),e.on("change",this.onBufferChange,this)),t}onBufferChange(e){this._managedBuffers.remove(e),e._updateID=0,this.createGPUBuffer(e)}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gpu=null}}ou.extension={type:[A.WebGPUSystem],name:"buffer"};class Cb{constructor({minUniformOffsetAlignment:e}){this._minUniformOffsetAlignment=256,this.byteIndex=0,this._minUniformOffsetAlignment=e,this.data=new Float32Array(65535)}clear(){this.byteIndex=0}addEmptyGroup(e){if(e>this._minUniformOffsetAlignment/4)throw new Error(`UniformBufferBatch: array is too large: ${e*4}`);const t=this.byteIndex;let s=t+e*4;if(s=Math.ceil(s/this._minUniformOffsetAlignment)*this._minUniformOffsetAlignment,s>this.data.length*4)throw new Error("UniformBufferBatch: ubo batch got too big");return this.byteIndex=s,t}addGroup(e){const t=this.addEmptyGroup(e.length);for(let s=0;s<e.length;s++)this.data[t/4+s]=e[s];return t}destroy(){this.data=null}}class au{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.pipeline.setColorMask(e))}destroy(){this._renderer=null,this._colorMaskCache=null}}au.extension={type:[A.WebGPUSystem],name:"colorMask"};class Ao{constructor(e){this._renderer=e}async init(e){return this._initPromise?this._initPromise:(this._initPromise=(e.gpu?Promise.resolve(e.gpu):this._createDeviceAndAdaptor(e)).then(t=>{this.gpu=t,this._renderer.runners.contextChange.emit(this.gpu)}),this._initPromise)}contextChange(e){this._renderer.gpu=e}async _createDeviceAndAdaptor(e){const t=await pe.get().getNavigator().gpu.requestAdapter({powerPreference:e.powerPreference,forceFallbackAdapter:e.forceFallbackAdapter}),s=["texture-compression-bc","texture-compression-astc","texture-compression-etc2"].filter(n=>t.features.has(n)),r=await t.requestDevice({requiredFeatures:s});return{adapter:t,device:r}}destroy(){this.gpu=null,this._renderer=null}}Ao.extension={type:[A.WebGPUSystem],name:"device"},Ao.defaultOptions={powerPreference:void 0,forceFallbackAdapter:!1};class lu{constructor(e){this._boundBindGroup=Object.create(null),this._boundVertexBuffer=Object.create(null),this._renderer=e}renderStart(){this.commandFinished=new Promise(e=>{this._resolveCommandFinished=e}),this.commandEncoder=this._renderer.gpu.device.createCommandEncoder()}beginRenderPass(e){this.endRenderPass(),this._clearCache(),this.renderPassEncoder=this.commandEncoder.beginRenderPass(e.descriptor)}endRenderPass(){this.renderPassEncoder&&this.renderPassEncoder.end(),this.renderPassEncoder=null}setViewport(e){this.renderPassEncoder.setViewport(e.x,e.y,e.width,e.height,0,1)}setPipelineFromGeometryProgramAndState(e,t,s,r){const n=this._renderer.pipeline.getPipeline(e,t,s,r);this.setPipeline(n)}setPipeline(e){this._boundPipeline!==e&&(this._boundPipeline=e,this.renderPassEncoder.setPipeline(e))}_setVertexBuffer(e,t){this._boundVertexBuffer[e]!==t&&(this._boundVertexBuffer[e]=t,this.renderPassEncoder.setVertexBuffer(e,this._renderer.buffer.updateBuffer(t)))}_setIndexBuffer(e){if(this._boundIndexBuffer===e)return;this._boundIndexBuffer=e;const t=e.data.BYTES_PER_ELEMENT===2?"uint16":"uint32";this.renderPassEncoder.setIndexBuffer(this._renderer.buffer.updateBuffer(e),t)}resetBindGroup(e){this._boundBindGroup[e]=null}setBindGroup(e,t,s){if(this._boundBindGroup[e]===t)return;this._boundBindGroup[e]=t,t._touch(this._renderer.gc.now,this._renderer.tick);const r=this._renderer.bindGroup.getBindGroup(t,s,e);this.renderPassEncoder.setBindGroup(e,r)}setGeometry(e,t){const s=this._renderer.pipeline.getBufferNamesToBind(e,t);for(const r in s)this._setVertexBuffer(parseInt(r,10),e.attributes[s[r]].buffer);e.indexBuffer&&this._setIndexBuffer(e.indexBuffer)}_setShaderBindGroups(e,t){for(const s in e.groups){const r=e.groups[s];t||this._syncBindGroup(r),this.setBindGroup(s,r,e.gpuProgram)}}_syncBindGroup(e){for(const t in e.resources){const s=e.resources[t];s.isUniformGroup&&this._renderer.ubo.updateUniformGroup(s)}}draw(e){const{geometry:t,shader:s,state:r,topology:n,size:o,start:a,instanceCount:l,skipSync:c}=e;this.setPipelineFromGeometryProgramAndState(t,s.gpuProgram,r,n),this.setGeometry(t,s.gpuProgram),this._setShaderBindGroups(s,c),t.indexBuffer?this.renderPassEncoder.drawIndexed(o||t.indexBuffer.data.length,l??t.instanceCount,a||0):this.renderPassEncoder.draw(o||t.getSize(),l??t.instanceCount,a||0)}finishRenderPass(){this.renderPassEncoder&&(this.renderPassEncoder.end(),this.renderPassEncoder=null)}postrender(){this.finishRenderPass(),this._gpu.device.queue.submit([this.commandEncoder.finish()]),this._resolveCommandFinished(),this.commandEncoder=null}restoreRenderPass(){const e=this._renderer.renderTarget.adaptor.getDescriptor(this._renderer.renderTarget.renderTarget,!1,[0,0,0,1],this._renderer.renderTarget.mipLevel,this._renderer.renderTarget.layer);this.renderPassEncoder=this.commandEncoder.beginRenderPass(e);const t=this._boundPipeline,s={...this._boundVertexBuffer},r=this._boundIndexBuffer,n={...this._boundBindGroup};this._clearCache();const o=this._renderer.renderTarget.viewport;this.renderPassEncoder.setViewport(o.x,o.y,o.width,o.height,0,1),this.setPipeline(t);for(const a in s)this._setVertexBuffer(a,s[a]);for(const a in n)this.setBindGroup(a,n[a],null);this._setIndexBuffer(r)}_clearCache(){for(let e=0;e<16;e++)this._boundBindGroup[e]=null,this._boundVertexBuffer[e]=null;this._boundIndexBuffer=null,this._boundPipeline=null}destroy(){this._renderer=null,this._gpu=null,this._boundBindGroup=null,this._boundVertexBuffer=null,this._boundIndexBuffer=null,this._boundPipeline=null}contextChange(e){this._gpu=e}}lu.extension={type:[A.WebGPUSystem],name:"encoder",priority:1};class cu{constructor(e){this._renderer=e}contextChange(){this.maxTextures=this._renderer.device.gpu.device.limits.maxSampledTexturesPerShaderStage,this.maxBatchableTextures=this.maxTextures}destroy(){}}cu.extension={type:[A.WebGPUSystem],name:"limits"};class hu{constructor(e){this._renderTargetStencilState=Object.create(null),this._renderer=e,e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){let t=this._renderTargetStencilState[e.uid];t||(t=this._renderTargetStencilState[e.uid]={stencilMode:ke.DISABLED,stencilReference:0}),this._activeRenderTarget=e,this.setStencilMode(t.stencilMode,t.stencilReference)}setStencilMode(e,t){const s=this._renderTargetStencilState[this._activeRenderTarget.uid];s.stencilMode=e,s.stencilReference=t;const r=this._renderer;r.pipeline.setStencilMode(e),r.encoder.renderPassEncoder.setStencilReference(t)}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._activeRenderTarget=null,this._renderTargetStencilState=null}}hu.extension={type:[A.WebGPUSystem],name:"stencil"};const dr={i32:{align:4,size:4},u32:{align:4,size:4},f32:{align:4,size:4},f16:{align:2,size:2},"vec2<i32>":{align:8,size:8},"vec2<u32>":{align:8,size:8},"vec2<f32>":{align:8,size:8},"vec2<f16>":{align:4,size:4},"vec3<i32>":{align:16,size:12},"vec3<u32>":{align:16,size:12},"vec3<f32>":{align:16,size:12},"vec3<f16>":{align:8,size:6},"vec4<i32>":{align:16,size:16},"vec4<u32>":{align:16,size:16},"vec4<f32>":{align:16,size:16},"vec4<f16>":{align:8,size:8},"mat2x2<f32>":{align:8,size:16},"mat2x2<f16>":{align:4,size:8},"mat3x2<f32>":{align:8,size:24},"mat3x2<f16>":{align:4,size:12},"mat4x2<f32>":{align:8,size:32},"mat4x2<f16>":{align:4,size:16},"mat2x3<f32>":{align:16,size:32},"mat2x3<f16>":{align:8,size:16},"mat3x3<f32>":{align:16,size:48},"mat3x3<f16>":{align:8,size:24},"mat4x3<f32>":{align:16,size:64},"mat4x3<f16>":{align:8,size:32},"mat2x4<f32>":{align:16,size:32},"mat2x4<f16>":{align:8,size:16},"mat3x4<f32>":{align:16,size:48},"mat3x4<f16>":{align:8,size:24},"mat4x4<f32>":{align:16,size:64},"mat4x4<f16>":{align:8,size:32}};function Eb(i){const e=i.map(s=>({data:s,offset:0,size:0}));let t=0;for(let s=0;s<e.length;s++){const r=e[s];let n=dr[r.data.type].size;const o=dr[r.data.type].align;if(!dr[r.data.type])throw new Error(`[Pixi.js] WebGPU UniformBuffer: Unknown type ${r.data.type}`);r.data.size>1&&(n=Math.max(n,o)*r.data.size),t=Math.ceil(t/o)*o,r.size=n,r.offset=t,t+=n}return t=Math.ceil(t/16)*16,{uboElements:e,size:t}}function Sb(i,e){const{size:t,align:s}=dr[i.data.type],r=(s-t)/4,n=i.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
|
|
843
|
+
`))}class Xh{constructor(e){this._cache={},this._uniformGroupSyncHash={},this._renderer=e,this.gl=null,this._cache={}}contextChange(e){this.gl=e}updateUniformGroup(e,t,s){const r=this._renderer.shader._getProgramData(t);(!e.isStatic||e._dirtyId!==r.uniformDirtyGroups[e.uid])&&(r.uniformDirtyGroups[e.uid]=e._dirtyId,this._getUniformSyncFunction(e,t)(r.uniformData,e.uniforms,this._renderer,s))}_getUniformSyncFunction(e,t){var s;return((s=this._uniformGroupSyncHash[e._signature])==null?void 0:s[t._key])||this._createUniformSyncFunction(e,t)}_createUniformSyncFunction(e,t){const s=this._uniformGroupSyncHash[e._signature]||(this._uniformGroupSyncHash[e._signature]={}),r=this._getSignature(e,t._uniformData,"u");return this._cache[r]||(this._cache[r]=this._generateUniformsSync(e,t._uniformData)),s[t._key]=this._cache[r],s[t._key]}_generateUniformsSync(e,t){return jy(e,t)}_getSignature(e,t,s){const r=e.uniforms,n=[`${s}-`];for(const o in r)n.push(o),t[o]&&n.push(t[o].type);return n.join("-")}destroy(){this._renderer=null,this._cache=null}}Xh.extension={type:[A.WebGLSystem],name:"uniformGroup"};function Xy(i){const e={};if(e.normal=[i.ONE,i.ONE_MINUS_SRC_ALPHA],e.add=[i.ONE,i.ONE],e.multiply=[i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA],e.screen=[i.ONE,i.ONE_MINUS_SRC_COLOR,i.ONE,i.ONE_MINUS_SRC_ALPHA],e.none=[0,0],e["normal-npm"]=[i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA],e["add-npm"]=[i.SRC_ALPHA,i.ONE,i.ONE,i.ONE],e["screen-npm"]=[i.SRC_ALPHA,i.ONE_MINUS_SRC_COLOR,i.ONE,i.ONE_MINUS_SRC_ALPHA],e.erase=[i.ZERO,i.ONE_MINUS_SRC_ALPHA],!(i instanceof pe.get().getWebGLRenderingContext()))e.min=[i.ONE,i.ONE,i.ONE,i.ONE,i.MIN,i.MIN],e.max=[i.ONE,i.ONE,i.ONE,i.ONE,i.MAX,i.MAX];else{const s=i.getExtension("EXT_blend_minmax");s&&(e.min=[i.ONE,i.ONE,i.ONE,i.ONE,s.MIN_EXT,s.MIN_EXT],e.max=[i.ONE,i.ONE,i.ONE,i.ONE,s.MAX_EXT,s.MAX_EXT])}return e}const Yy=0,qy=1,Ky=2,Zy=3,Jy=4,Qy=5,Yh=class na{constructor(e){this._invertFrontFace=!1,this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode="none",this._blendEq=!1,this.map=[],this.map[Yy]=this.setBlend,this.map[qy]=this.setOffset,this.map[Ky]=this.setCullFace,this.map[Zy]=this.setDepthTest,this.map[Jy]=this.setFrontFace,this.map[Qy]=this.setDepthMask,this.checks=[],this.defaultState=It.for2d(),e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){this._invertFrontFace=!e.isRoot,this._cullFace?this.setFrontFace(this._frontFace):this._frontFaceDirty=!0}contextChange(e){this.gl=e,this.blendModesMap=Xy(e),this.resetState()}set(e){if(e||(e=this.defaultState),this.stateId!==e.data){let t=this.stateId^e.data,s=0;for(;t;)t&1&&this.map[s].call(this,!!(e.data&1<<s)),t>>=1,s++;this.stateId=e.data}for(let t=0;t<this.checks.length;t++)this.checks[t](this,e)}forceState(e){e||(e=this.defaultState);for(let t=0;t<this.map.length;t++)this.map[t].call(this,!!(e.data&1<<t));for(let t=0;t<this.checks.length;t++)this.checks[t](this,e);this.stateId=e.data}setBlend(e){this._updateCheck(na._checkBlendMode,e),this.gl[e?"enable":"disable"](this.gl.BLEND)}setOffset(e){this._updateCheck(na._checkPolygonOffset,e),this.gl[e?"enable":"disable"](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(e){this.gl[e?"enable":"disable"](this.gl.DEPTH_TEST)}setDepthMask(e){this.gl.depthMask(e)}setCullFace(e){this._cullFace=e,this.gl[e?"enable":"disable"](this.gl.CULL_FACE),this._cullFace&&this._frontFaceDirty&&this.setFrontFace(this._frontFace)}setFrontFace(e){this._frontFace=e,this._frontFaceDirty=!1;const t=this._invertFrontFace?!e:e;this._glFrontFace!==t&&(this._glFrontFace=t,this.gl.frontFace(this.gl[t?"CW":"CCW"]))}setBlendMode(e){if(this.blendModesMap[e]||(e="normal"),e===this.blendMode)return;this.blendMode=e;const t=this.blendModesMap[e],s=this.gl;t.length===2?s.blendFunc(t[0],t[1]):s.blendFuncSeparate(t[0],t[1],t[2],t[3]),t.length===6?(this._blendEq=!0,s.blendEquationSeparate(t[4],t[5])):this._blendEq&&(this._blendEq=!1,s.blendEquationSeparate(s.FUNC_ADD,s.FUNC_ADD))}setPolygonOffset(e,t){this.gl.polygonOffset(e,t)}resetState(){this._glFrontFace=!1,this._frontFace=!1,this._cullFace=!1,this._frontFaceDirty=!1,this._invertFrontFace=!1,this.gl.frontFace(this.gl.CCW),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode="",this.setBlendMode("normal")}_updateCheck(e,t){const s=this.checks.indexOf(e);t&&s===-1?this.checks.push(e):!t&&s!==-1&&this.checks.splice(s,1)}static _checkBlendMode(e,t){e.setBlendMode(t.blendMode)}static _checkPolygonOffset(e,t){e.setPolygonOffset(1,t.polygonOffset)}destroy(){this.gl=null,this.checks.length=0}};Yh.extension={type:[A.WebGLSystem],name:"state"};let eb=Yh;class tb{constructor(e){this.target=xo.TEXTURE_2D,this._layerInitMask=0,this.texture=e,this.width=-1,this.height=-1,this.type=he.UNSIGNED_BYTE,this.internalFormat=vo.RGBA,this.format=vo.RGBA,this.samplerType=0}destroy(){}}const sb={id:"buffer",upload(i,e,t,s,r,n=!1){const o=r||e.target;!n&&e.width===i.width&&e.height===i.height?t.texSubImage2D(o,0,0,0,i.width,i.height,e.format,e.type,i.resource):t.texImage2D(o,0,e.internalFormat,i.width,i.height,0,e.format,e.type,i.resource),e.width=i.width,e.height=i.height}},ib={"bc1-rgba-unorm":!0,"bc1-rgba-unorm-srgb":!0,"bc2-rgba-unorm":!0,"bc2-rgba-unorm-srgb":!0,"bc3-rgba-unorm":!0,"bc3-rgba-unorm-srgb":!0,"bc4-r-unorm":!0,"bc4-r-snorm":!0,"bc5-rg-unorm":!0,"bc5-rg-snorm":!0,"bc6h-rgb-ufloat":!0,"bc6h-rgb-float":!0,"bc7-rgba-unorm":!0,"bc7-rgba-unorm-srgb":!0,"etc2-rgb8unorm":!0,"etc2-rgb8unorm-srgb":!0,"etc2-rgb8a1unorm":!0,"etc2-rgb8a1unorm-srgb":!0,"etc2-rgba8unorm":!0,"etc2-rgba8unorm-srgb":!0,"eac-r11unorm":!0,"eac-r11snorm":!0,"eac-rg11unorm":!0,"eac-rg11snorm":!0,"astc-4x4-unorm":!0,"astc-4x4-unorm-srgb":!0,"astc-5x4-unorm":!0,"astc-5x4-unorm-srgb":!0,"astc-5x5-unorm":!0,"astc-5x5-unorm-srgb":!0,"astc-6x5-unorm":!0,"astc-6x5-unorm-srgb":!0,"astc-6x6-unorm":!0,"astc-6x6-unorm-srgb":!0,"astc-8x5-unorm":!0,"astc-8x5-unorm-srgb":!0,"astc-8x6-unorm":!0,"astc-8x6-unorm-srgb":!0,"astc-8x8-unorm":!0,"astc-8x8-unorm-srgb":!0,"astc-10x5-unorm":!0,"astc-10x5-unorm-srgb":!0,"astc-10x6-unorm":!0,"astc-10x6-unorm-srgb":!0,"astc-10x8-unorm":!0,"astc-10x8-unorm-srgb":!0,"astc-10x10-unorm":!0,"astc-10x10-unorm-srgb":!0,"astc-12x10-unorm":!0,"astc-12x10-unorm-srgb":!0,"astc-12x12-unorm":!0,"astc-12x12-unorm-srgb":!0},rb={id:"compressed",upload(i,e,t,s,r,n){const o=r??e.target;t.pixelStorei(t.UNPACK_ALIGNMENT,4);let a=i.pixelWidth,l=i.pixelHeight;const c=!!ib[i.format];for(let h=0;h<i.resource.length;h++){const u=i.resource[h];c?t.compressedTexImage2D(o,h,e.internalFormat,a,l,0,u):t.texImage2D(o,h,e.internalFormat,a,l,0,e.format,e.type,u),a=Math.max(a>>1,1),l=Math.max(l>>1,1)}}},qh=["right","left","top","bottom","front","back"];function nb(i){return{id:"cube",upload(e,t,s,r){const n=e.faces;for(let o=0;o<qh.length;o++){const a=qh[o],l=n[a];(i[l.uploadMethodId]||i.image).upload(l,t,s,r,xo.TEXTURE_CUBE_MAP_POSITIVE_X+o,(t._layerInitMask&1<<o)===0),t._layerInitMask|=1<<o}t.width=e.pixelWidth,t.height=e.pixelHeight}}}const Kh={id:"image",upload(i,e,t,s,r,n=!1){const o=r||e.target,a=i.pixelWidth,l=i.pixelHeight,c=i.resourceWidth,h=i.resourceHeight,u=s===2,p=n||e.width!==a||e.height!==l,d=c>=a&&h>=l,g=i.resource;(u?ob:ab)(t,o,e,a,l,c,h,g,p,d),e.width=a,e.height=l}};function ob(i,e,t,s,r,n,o,a,l,c){if(!c){l&&i.texImage2D(e,0,t.internalFormat,s,r,0,t.format,t.type,null),i.texSubImage2D(e,0,0,0,n,o,t.format,t.type,a);return}if(!l){i.texSubImage2D(e,0,0,0,t.format,t.type,a);return}i.texImage2D(e,0,t.internalFormat,s,r,0,t.format,t.type,a)}function ab(i,e,t,s,r,n,o,a,l,c){if(!c){l&&i.texImage2D(e,0,t.internalFormat,s,r,0,t.format,t.type,null),i.texSubImage2D(e,0,0,0,t.format,t.type,a);return}if(!l){i.texSubImage2D(e,0,0,0,t.format,t.type,a);return}i.texImage2D(e,0,t.internalFormat,t.format,t.type,a)}const lb=O_(),cb={id:"video",upload(i,e,t,s,r,n=lb){if(!i.isValid){const o=r??e.target;t.texImage2D(o,0,e.internalFormat,1,1,0,e.format,e.type,null);return}Kh.upload(i,e,t,s,r,n)}},Zh={linear:9729,nearest:9728},hb={linear:{linear:9987,nearest:9985},nearest:{linear:9986,nearest:9984}},To={"clamp-to-edge":33071,repeat:10497,"mirror-repeat":33648},ub={never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519};function Jh(i,e,t,s,r,n,o,a){const l=n;if(!a||i.addressModeU!=="repeat"||i.addressModeV!=="repeat"||i.addressModeW!=="repeat"){const c=To[o?"clamp-to-edge":i.addressModeU],h=To[o?"clamp-to-edge":i.addressModeV],u=To[o?"clamp-to-edge":i.addressModeW];e[r](l,e.TEXTURE_WRAP_S,c),e[r](l,e.TEXTURE_WRAP_T,h),e.TEXTURE_WRAP_R&&e[r](l,e.TEXTURE_WRAP_R,u)}if((!a||i.magFilter!=="linear")&&e[r](l,e.TEXTURE_MAG_FILTER,Zh[i.magFilter]),t){if(!a||i.mipmapFilter!=="linear"){const c=hb[i.minFilter][i.mipmapFilter];e[r](l,e.TEXTURE_MIN_FILTER,c)}}else e[r](l,e.TEXTURE_MIN_FILTER,Zh[i.minFilter]);if(s&&i.maxAnisotropy>1){const c=Math.min(i.maxAnisotropy,e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT));e[r](l,s.TEXTURE_MAX_ANISOTROPY_EXT,c)}i.compare&&e[r](l,e.TEXTURE_COMPARE_FUNC,ub[i.compare])}function db(i){return{r8unorm:i.RED,r8snorm:i.RED,r8uint:i.RED,r8sint:i.RED,r16uint:i.RED,r16sint:i.RED,r16float:i.RED,rg8unorm:i.RG,rg8snorm:i.RG,rg8uint:i.RG,rg8sint:i.RG,r32uint:i.RED,r32sint:i.RED,r32float:i.RED,rg16uint:i.RG,rg16sint:i.RG,rg16float:i.RG,rgba8unorm:i.RGBA,"rgba8unorm-srgb":i.RGBA,rgba8snorm:i.RGBA,rgba8uint:i.RGBA,rgba8sint:i.RGBA,bgra8unorm:i.RGBA,"bgra8unorm-srgb":i.RGBA,rgb9e5ufloat:i.RGB,rgb10a2unorm:i.RGBA,rg11b10ufloat:i.RGB,rg32uint:i.RG,rg32sint:i.RG,rg32float:i.RG,rgba16uint:i.RGBA,rgba16sint:i.RGBA,rgba16float:i.RGBA,rgba32uint:i.RGBA,rgba32sint:i.RGBA,rgba32float:i.RGBA,stencil8:i.STENCIL_INDEX8,depth16unorm:i.DEPTH_COMPONENT,depth24plus:i.DEPTH_COMPONENT,"depth24plus-stencil8":i.DEPTH_STENCIL,depth32float:i.DEPTH_COMPONENT,"depth32float-stencil8":i.DEPTH_STENCIL}}function fb(i,e){let t={},s=i.RGBA;return i instanceof pe.get().getWebGLRenderingContext()?e.srgb&&(t={"rgba8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT}):(t={"rgba8unorm-srgb":i.SRGB8_ALPHA8,"bgra8unorm-srgb":i.SRGB8_ALPHA8},s=i.RGBA8),{r8unorm:i.R8,r8snorm:i.R8_SNORM,r8uint:i.R8UI,r8sint:i.R8I,r16uint:i.R16UI,r16sint:i.R16I,r16float:i.R16F,rg8unorm:i.RG8,rg8snorm:i.RG8_SNORM,rg8uint:i.RG8UI,rg8sint:i.RG8I,r32uint:i.R32UI,r32sint:i.R32I,r32float:i.R32F,rg16uint:i.RG16UI,rg16sint:i.RG16I,rg16float:i.RG16F,rgba8unorm:i.RGBA,...t,rgba8snorm:i.RGBA8_SNORM,rgba8uint:i.RGBA8UI,rgba8sint:i.RGBA8I,bgra8unorm:s,rgb9e5ufloat:i.RGB9_E5,rgb10a2unorm:i.RGB10_A2,rg11b10ufloat:i.R11F_G11F_B10F,rg32uint:i.RG32UI,rg32sint:i.RG32I,rg32float:i.RG32F,rgba16uint:i.RGBA16UI,rgba16sint:i.RGBA16I,rgba16float:i.RGBA16F,rgba32uint:i.RGBA32UI,rgba32sint:i.RGBA32I,rgba32float:i.RGBA32F,stencil8:i.STENCIL_INDEX8,depth16unorm:i.DEPTH_COMPONENT16,depth24plus:i.DEPTH_COMPONENT24,"depth24plus-stencil8":i.DEPTH24_STENCIL8,depth32float:i.DEPTH_COMPONENT32F,"depth32float-stencil8":i.DEPTH32F_STENCIL8,...e.s3tc?{"bc1-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT1_EXT,"bc2-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT3_EXT,"bc3-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT5_EXT}:{},...e.s3tc_sRGB?{"bc1-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,"bc2-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,"bc3-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}:{},...e.rgtc?{"bc4-r-unorm":e.rgtc.COMPRESSED_RED_RGTC1_EXT,"bc4-r-snorm":e.rgtc.COMPRESSED_SIGNED_RED_RGTC1_EXT,"bc5-rg-unorm":e.rgtc.COMPRESSED_RED_GREEN_RGTC2_EXT,"bc5-rg-snorm":e.rgtc.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}:{},...e.bptc?{"bc6h-rgb-float":e.bptc.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT,"bc6h-rgb-ufloat":e.bptc.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT,"bc7-rgba-unorm":e.bptc.COMPRESSED_RGBA_BPTC_UNORM_EXT,"bc7-rgba-unorm-srgb":e.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT}:{},...e.etc?{"etc2-rgb8unorm":e.etc.COMPRESSED_RGB8_ETC2,"etc2-rgb8unorm-srgb":e.etc.COMPRESSED_SRGB8_ETC2,"etc2-rgb8a1unorm":e.etc.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgb8a1unorm-srgb":e.etc.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgba8unorm":e.etc.COMPRESSED_RGBA8_ETC2_EAC,"etc2-rgba8unorm-srgb":e.etc.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,"eac-r11unorm":e.etc.COMPRESSED_R11_EAC,"eac-rg11unorm":e.etc.COMPRESSED_SIGNED_RG11_EAC}:{},...e.astc?{"astc-4x4-unorm":e.astc.COMPRESSED_RGBA_ASTC_4x4_KHR,"astc-4x4-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,"astc-5x4-unorm":e.astc.COMPRESSED_RGBA_ASTC_5x4_KHR,"astc-5x4-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,"astc-5x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_5x5_KHR,"astc-5x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,"astc-6x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_6x5_KHR,"astc-6x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,"astc-6x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_6x6_KHR,"astc-6x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,"astc-8x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x5_KHR,"astc-8x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,"astc-8x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x6_KHR,"astc-8x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,"astc-8x8-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x8_KHR,"astc-8x8-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,"astc-10x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x5_KHR,"astc-10x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,"astc-10x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x6_KHR,"astc-10x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,"astc-10x8-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x8_KHR,"astc-10x8-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,"astc-10x10-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x10_KHR,"astc-10x10-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,"astc-12x10-unorm":e.astc.COMPRESSED_RGBA_ASTC_12x10_KHR,"astc-12x10-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,"astc-12x12-unorm":e.astc.COMPRESSED_RGBA_ASTC_12x12_KHR,"astc-12x12-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR}:{}}}function pb(i){return{r8unorm:i.UNSIGNED_BYTE,r8snorm:i.BYTE,r8uint:i.UNSIGNED_BYTE,r8sint:i.BYTE,r16uint:i.UNSIGNED_SHORT,r16sint:i.SHORT,r16float:i.HALF_FLOAT,rg8unorm:i.UNSIGNED_BYTE,rg8snorm:i.BYTE,rg8uint:i.UNSIGNED_BYTE,rg8sint:i.BYTE,r32uint:i.UNSIGNED_INT,r32sint:i.INT,r32float:i.FLOAT,rg16uint:i.UNSIGNED_SHORT,rg16sint:i.SHORT,rg16float:i.HALF_FLOAT,rgba8unorm:i.UNSIGNED_BYTE,"rgba8unorm-srgb":i.UNSIGNED_BYTE,rgba8snorm:i.BYTE,rgba8uint:i.UNSIGNED_BYTE,rgba8sint:i.BYTE,bgra8unorm:i.UNSIGNED_BYTE,"bgra8unorm-srgb":i.UNSIGNED_BYTE,rgb9e5ufloat:i.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:i.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:i.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:i.UNSIGNED_INT,rg32sint:i.INT,rg32float:i.FLOAT,rgba16uint:i.UNSIGNED_SHORT,rgba16sint:i.SHORT,rgba16float:i.HALF_FLOAT,rgba32uint:i.UNSIGNED_INT,rgba32sint:i.INT,rgba32float:i.FLOAT,stencil8:i.UNSIGNED_BYTE,depth16unorm:i.UNSIGNED_SHORT,depth24plus:i.UNSIGNED_INT,"depth24plus-stencil8":i.UNSIGNED_INT_24_8,depth32float:i.FLOAT,"depth32float-stencil8":i.FLOAT_32_UNSIGNED_INT_24_8_REV}}function mb(i){return{"2d":i.TEXTURE_2D,cube:i.TEXTURE_CUBE_MAP,"1d":null,"3d":(i==null?void 0:i.TEXTURE_3D)||null,"2d-array":(i==null?void 0:i.TEXTURE_2D_ARRAY)||null,"cube-array":(i==null?void 0:i.TEXTURE_CUBE_MAP_ARRAY)||null}}const gb=4;class Qh{constructor(e){this._glSamplers=Object.create(null),this._boundTextures=[],this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1,this._useSeparateSamplers=!1,this._renderer=e,this._managedTextures=new Rt({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"glTexture"});const t={image:Kh,buffer:sb,video:cb,compressed:rb};this._uploads={...t,cube:nb(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gl=e,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=fb(e,this._renderer.context.extensions),this._mapFormatToType=pb(e),this._mapFormatToFormat=db(e),this._mapViewDimensionToGlTarget=mb(e)),this._managedTextures.removeAll(!0),this._glSamplers=Object.create(null),this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1;for(let t=0;t<16;t++)this.bind(j.EMPTY,t)}initSource(e){this.bind(e)}bind(e,t=0){const s=e.source;e?(this.bindSource(s,t),this._useSeparateSamplers&&this._bindSampler(s.style,t)):(this.bindSource(null,t),this._useSeparateSamplers&&this._bindSampler(null,t))}bindSource(e,t=0){const s=this._gl;if(e._gcLastUsed=this._renderer.gc.now,this._boundTextures[t]!==e){this._boundTextures[t]=e,this._activateLocation(t),e||(e=j.EMPTY.source);const r=this.getGlSource(e);s.bindTexture(r.target,r.texture)}}_bindSampler(e,t=0){const s=this._gl;if(!e){this._boundSamplers[t]=null,s.bindSampler(t,null);return}const r=this._getGlSampler(e);this._boundSamplers[t]!==r&&(this._boundSamplers[t]=r,s.bindSampler(t,r))}unbind(e){const t=e.source,s=this._boundTextures,r=this._gl;for(let n=0;n<s.length;n++)if(s[n]===t){this._activateLocation(n);const o=this.getGlSource(t);r.bindTexture(o.target,null),s[n]=null}}_activateLocation(e){this._activeTextureLocation!==e&&(this._activeTextureLocation=e,this._gl.activeTexture(this._gl.TEXTURE0+e))}_initSource(e){const t=this._gl,s=new tb(t.createTexture());if(s.type=this._mapFormatToType[e.format],s.internalFormat=this._mapFormatToInternalFormat[e.format],s.format=this._mapFormatToFormat[e.format],s.target=this._mapViewDimensionToGlTarget[e.viewDimension],s.target===null)throw new Error(`Unsupported view dimension: ${e.viewDimension} with this webgl version: ${this._renderer.context.webGLVersion}`);if(e.uploadMethodId==="cube"&&(s.target=t.TEXTURE_CUBE_MAP),e.autoGenerateMipmaps&&(this._renderer.context.supports.nonPowOf2mipmaps||e.isPowerOfTwo)){const n=Math.max(e.width,e.height);e.mipLevelCount=Math.floor(Math.log2(n))+1}return e._gpuData[this._renderer.uid]=s,this._managedTextures.add(e)&&(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceUpdate,this),e.on("styleChange",this.onStyleChange,this),e.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(e),this.updateStyle(e,!1),s}onStyleChange(e){this.updateStyle(e,!1)}updateStyle(e,t){const s=this._gl,r=this.getGlSource(e);s.bindTexture(r.target,r.texture),this._boundTextures[this._activeTextureLocation]=e,Jh(e.style,s,e.mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"texParameteri",r.target,!this._renderer.context.supports.nonPowOf2wrapping&&!e.isPowerOfTwo,t)}onSourceUnload(e,t=!1){const s=e._gpuData[this._renderer.uid];s&&(t||(this.unbind(e),this._gl.deleteTexture(s.texture)),e.off("update",this.onSourceUpdate,this),e.off("resize",this.onSourceUpdate,this),e.off("styleChange",this.onStyleChange,this),e.off("updateMipmaps",this.onUpdateMipmaps,this))}onSourceUpdate(e){const t=this._gl,s=this.getGlSource(e);t.bindTexture(s.target,s.texture),this._boundTextures[this._activeTextureLocation]=e;const r=e.alphaMode==="premultiply-alpha-on-upload";if(this._premultiplyAlpha!==r&&(this._premultiplyAlpha=r,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,r)),this._uploads[e.uploadMethodId])this._uploads[e.uploadMethodId].upload(e,s,t,this._renderer.context.webGLVersion);else if(s.target===t.TEXTURE_2D)this._initEmptyTexture2D(s,e);else if(s.target===t.TEXTURE_2D_ARRAY)this._initEmptyTexture2DArray(s,e);else if(s.target===t.TEXTURE_CUBE_MAP)this._initEmptyTextureCube(s,e);else throw new Error("[GlTextureSystem] Unsupported texture target for empty allocation.");this._applyMipRange(s,e),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e,!1)}onUpdateMipmaps(e,t=!0){t&&this.bindSource(e,0);const s=this.getGlSource(e);this._gl.generateMipmap(s.target)}_initEmptyTexture2D(e,t){const s=this._gl;s.texImage2D(s.TEXTURE_2D,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let r=Math.max(t.pixelWidth>>1,1),n=Math.max(t.pixelHeight>>1,1);for(let o=1;o<t.mipLevelCount;o++)s.texImage2D(s.TEXTURE_2D,o,e.internalFormat,r,n,0,e.format,e.type,null),r=Math.max(r>>1,1),n=Math.max(n>>1,1)}_initEmptyTexture2DArray(e,t){if(this._renderer.context.webGLVersion!==2)throw new Error("[GlTextureSystem] TEXTURE_2D_ARRAY requires WebGL2.");const s=this._gl,r=Math.max(t.arrayLayerCount|0,1);s.texImage3D(s.TEXTURE_2D_ARRAY,0,e.internalFormat,t.pixelWidth,t.pixelHeight,r,0,e.format,e.type,null);let n=Math.max(t.pixelWidth>>1,1),o=Math.max(t.pixelHeight>>1,1);for(let a=1;a<t.mipLevelCount;a++)s.texImage3D(s.TEXTURE_2D_ARRAY,a,e.internalFormat,n,o,r,0,e.format,e.type,null),n=Math.max(n>>1,1),o=Math.max(o>>1,1)}_initEmptyTextureCube(e,t){const s=this._gl,r=6;for(let a=0;a<r;a++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+a,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let n=Math.max(t.pixelWidth>>1,1),o=Math.max(t.pixelHeight>>1,1);for(let a=1;a<t.mipLevelCount;a++){for(let l=0;l<r;l++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,a,e.internalFormat,n,o,0,e.format,e.type,null);n=Math.max(n>>1,1),o=Math.max(o>>1,1)}}_applyMipRange(e,t){if(this._renderer.context.webGLVersion!==2)return;const s=this._gl,r=Math.max((t.mipLevelCount|0)-1,0);s.texParameteri(e.target,s.TEXTURE_BASE_LEVEL,0),s.texParameteri(e.target,s.TEXTURE_MAX_LEVEL,r)}_initSampler(e){const t=this._gl,s=this._gl.createSampler();return this._glSamplers[e._resourceId]=s,Jh(e,t,this._boundTextures[this._activeTextureLocation].mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"samplerParameteri",s,!1,!0),this._glSamplers[e._resourceId]}_getGlSampler(e){return this._glSamplers[e._resourceId]||this._initSampler(e)}getGlSource(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]||this._initSource(e)}generateCanvas(e){const{pixels:t,width:s,height:r}=this.getPixels(e),n=pe.get().createCanvas();n.width=s,n.height=r;const o=n.getContext("2d");if(o){const a=o.createImageData(s,r);a.data.set(t),o.putImageData(a,0,0)}return n}getPixels(e){const t=e.source.resolution,s=e.frame,r=Math.max(Math.round(s.width*t),1),n=Math.max(Math.round(s.height*t),1),o=new Uint8Array(gb*r*n),a=this._renderer,l=a.renderTarget.getRenderTarget(e),c=a.renderTarget.getGpuRenderTarget(l),h=a.gl;return h.bindFramebuffer(h.FRAMEBUFFER,c.resolveTargetFramebuffer),h.readPixels(Math.round(s.x*t),Math.round(s.y*t),r,n,h.RGBA,h.UNSIGNED_BYTE,o),{pixels:new Uint8ClampedArray(o.buffer),width:r,height:n}}destroy(){this._managedTextures.destroy(),this._glSamplers=null,this._boundTextures=null,this._boundSamplers=null,this._mapFormatToInternalFormat=null,this._mapFormatToType=null,this._mapFormatToFormat=null,this._uploads=null,this._renderer=null}resetState(){this._activeTextureLocation=-1,this._boundTextures.fill(j.EMPTY.source),this._boundSamplers=Object.create(null);const e=this._gl;this._premultiplyAlpha=!1,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this._premultiplyAlpha)}}Qh.extension={type:[A.WebGLSystem],name:"texture"};class eu{contextChange(e){const t=new gt({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new H,type:"mat3x3<f32>"},uRound:{value:0,type:"f32"}}),s=e.limits.maxBatchableTextures,r=Pn({name:"graphics",bits:[nc,ac(s),Jc,Dn]});this.shader=new wt({glProgram:r,resources:{localUniforms:t,batchSamplers:cc(s)}})}execute(e,t){const s=t.context,r=s.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(s);r.groups[0]=n.globalUniforms.bindGroup,n.state.set(e.state),n.shader.bind(r),n.geometry.bind(a.geometry,r.glProgram);const c=l.instructions;for(let h=0;h<l.instructionSize;h++){const u=c[h];if(u.size){for(let p=0;p<u.textures.count;p++)n.texture.bind(u.textures.textures[p],p);n.geometry.draw(u.topology,u.size,u.start)}}}destroy(){this.shader.destroy(!0),this.shader=null}}eu.extension={type:[A.WebGLPipesAdaptor],name:"graphics"};class tu{init(){const e=Pn({name:"mesh",bits:[Jc,N_,Dn]});this._shader=new wt({glProgram:e,resources:{uTexture:j.EMPTY.source,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new H}}}})}execute(e,t){const s=e.renderer;let r=t._shader;if(r){if(!r.glProgram){ie("Mesh shader has no glProgram",t.shader);return}}else{r=this._shader;const n=t.texture,o=n.source;r.resources.uTexture=o,r.resources.uSampler=o.style,r.resources.textureUniforms.uniforms.uTextureMatrix=n.textureMatrix.mapCoord}r.groups[100]=s.globalUniforms.bindGroup,r.groups[101]=e.localUniformsBindGroup,s.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}tu.extension={type:[A.WebGLPipesAdaptor],name:"mesh"};const _b=[..._o,Fh,Iy,Cy,Oh,wh,Qh,Lh,Mh,Xh,jh,kh,eb,Bh,Ph],yb=[...xh],bb=[eh,tu,eu],su=[],iu=[],ru=[];Q.handleByNamedList(A.WebGLSystem,su),Q.handleByNamedList(A.WebGLPipes,iu),Q.handleByNamedList(A.WebGLPipesAdaptor,ru),Q.add(..._b,...yb,...bb);class vb extends ni{constructor(){const e={name:"webgl",type:_t.WEBGL,systems:su,renderPipes:iu,renderPipeAdaptors:ru};super(e)}}const xb=Object.freeze(Object.defineProperty({__proto__:null,WebGLRenderer:vb},Symbol.toStringTag,{value:"Module"}));class nu{constructor(e){this._hash=Object.create(null),this._renderer=e}contextChange(e){this._gpu=e}getBindGroup(e,t,s){return e._updateKey(),this._hash[e._key]||this._createBindGroup(e,t,s)}_createBindGroup(e,t,s){const r=this._gpu.device,n=t.layout[s],o=[],a=this._renderer;for(const h in n){const u=e.resources[h]??e.resources[n[h]];let p;if(u._resourceType==="uniformGroup"){const d=u;a.ubo.updateUniformGroup(d);const g=d.buffer;p={buffer:a.buffer.getGPUBuffer(g),offset:0,size:g.descriptor.size}}else if(u._resourceType==="buffer"){const d=u;p={buffer:a.buffer.getGPUBuffer(d),offset:0,size:d.descriptor.size}}else if(u._resourceType==="bufferResource"){const d=u;p={buffer:a.buffer.getGPUBuffer(d.buffer),offset:d.offset,size:d.size}}else if(u._resourceType==="textureSampler"){const d=u;p=a.texture.getGpuSampler(d)}else if(u._resourceType==="textureSource"){const d=u;p=a.texture.getTextureView(d)}o.push({binding:n[h],resource:p})}const l=a.shader.getProgramData(t).bindGroups[s],c=r.createBindGroup({layout:l,entries:o});return this._hash[e._key]=c,c}destroy(){this._hash=null,this._renderer=null}}nu.extension={type:[A.WebGPUSystem],name:"bindGroup"};class Cb{constructor(e){this.gpuBuffer=e}destroy(){this.gpuBuffer.destroy(),this.gpuBuffer=null}}class ou{constructor(e){this._renderer=e,this._managedBuffers=new Rt({renderer:e,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"gpuBuffer"})}contextChange(e){this._gpu=e}getGPUBuffer(e){var t;return e._gcLastUsed=this._renderer.gc.now,((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuBuffer)||this.createGPUBuffer(e)}updateBuffer(e){const t=this.getGPUBuffer(e),s=e.data;return e._updateID&&s&&(e._updateID=0,this._gpu.device.queue.writeBuffer(t,0,s.buffer,0,(e._updateSize||s.byteLength)+3&-4)),t}destroyAll(){this._managedBuffers.removeAll()}onBufferUnload(e){e.off("update",this.updateBuffer,this),e.off("change",this.onBufferChange,this)}createGPUBuffer(e){const t=this._gpu.device.createBuffer(e.descriptor);return e._updateID=0,e._resourceId=be("resource"),e.data&&(wn(e.data.buffer,t.getMappedRange(),e.data.byteOffset,e.data.byteLength),t.unmap()),e._gpuData[this._renderer.uid]=new Cb(t),this._managedBuffers.add(e)&&(e.on("update",this.updateBuffer,this),e.on("change",this.onBufferChange,this)),t}onBufferChange(e){this._managedBuffers.remove(e),e._updateID=0,this.createGPUBuffer(e)}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gpu=null}}ou.extension={type:[A.WebGPUSystem],name:"buffer"};class Eb{constructor({minUniformOffsetAlignment:e}){this._minUniformOffsetAlignment=256,this.byteIndex=0,this._minUniformOffsetAlignment=e,this.data=new Float32Array(65535)}clear(){this.byteIndex=0}addEmptyGroup(e){if(e>this._minUniformOffsetAlignment/4)throw new Error(`UniformBufferBatch: array is too large: ${e*4}`);const t=this.byteIndex;let s=t+e*4;if(s=Math.ceil(s/this._minUniformOffsetAlignment)*this._minUniformOffsetAlignment,s>this.data.length*4)throw new Error("UniformBufferBatch: ubo batch got too big");return this.byteIndex=s,t}addGroup(e){const t=this.addEmptyGroup(e.length);for(let s=0;s<e.length;s++)this.data[t/4+s]=e[s];return t}destroy(){this.data=null}}class au{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.pipeline.setColorMask(e))}destroy(){this._renderer=null,this._colorMaskCache=null}}au.extension={type:[A.WebGPUSystem],name:"colorMask"};class Ao{constructor(e){this._renderer=e}async init(e){return this._initPromise?this._initPromise:(this._initPromise=(e.gpu?Promise.resolve(e.gpu):this._createDeviceAndAdaptor(e)).then(t=>{this.gpu=t,this._renderer.runners.contextChange.emit(this.gpu)}),this._initPromise)}contextChange(e){this._renderer.gpu=e}async _createDeviceAndAdaptor(e){const t=await pe.get().getNavigator().gpu.requestAdapter({powerPreference:e.powerPreference,forceFallbackAdapter:e.forceFallbackAdapter}),s=["texture-compression-bc","texture-compression-astc","texture-compression-etc2"].filter(n=>t.features.has(n)),r=await t.requestDevice({requiredFeatures:s});return{adapter:t,device:r}}destroy(){this.gpu=null,this._renderer=null}}Ao.extension={type:[A.WebGPUSystem],name:"device"},Ao.defaultOptions={powerPreference:void 0,forceFallbackAdapter:!1};class lu{constructor(e){this._boundBindGroup=Object.create(null),this._boundVertexBuffer=Object.create(null),this._renderer=e}renderStart(){this.commandFinished=new Promise(e=>{this._resolveCommandFinished=e}),this.commandEncoder=this._renderer.gpu.device.createCommandEncoder()}beginRenderPass(e){this.endRenderPass(),this._clearCache(),this.renderPassEncoder=this.commandEncoder.beginRenderPass(e.descriptor)}endRenderPass(){this.renderPassEncoder&&this.renderPassEncoder.end(),this.renderPassEncoder=null}setViewport(e){this.renderPassEncoder.setViewport(e.x,e.y,e.width,e.height,0,1)}setPipelineFromGeometryProgramAndState(e,t,s,r){const n=this._renderer.pipeline.getPipeline(e,t,s,r);this.setPipeline(n)}setPipeline(e){this._boundPipeline!==e&&(this._boundPipeline=e,this.renderPassEncoder.setPipeline(e))}_setVertexBuffer(e,t){this._boundVertexBuffer[e]!==t&&(this._boundVertexBuffer[e]=t,this.renderPassEncoder.setVertexBuffer(e,this._renderer.buffer.updateBuffer(t)))}_setIndexBuffer(e){if(this._boundIndexBuffer===e)return;this._boundIndexBuffer=e;const t=e.data.BYTES_PER_ELEMENT===2?"uint16":"uint32";this.renderPassEncoder.setIndexBuffer(this._renderer.buffer.updateBuffer(e),t)}resetBindGroup(e){this._boundBindGroup[e]=null}setBindGroup(e,t,s){if(this._boundBindGroup[e]===t)return;this._boundBindGroup[e]=t,t._touch(this._renderer.gc.now,this._renderer.tick);const r=this._renderer.bindGroup.getBindGroup(t,s,e);this.renderPassEncoder.setBindGroup(e,r)}setGeometry(e,t){const s=this._renderer.pipeline.getBufferNamesToBind(e,t);for(const r in s)this._setVertexBuffer(parseInt(r,10),e.attributes[s[r]].buffer);e.indexBuffer&&this._setIndexBuffer(e.indexBuffer)}_setShaderBindGroups(e,t){for(const s in e.groups){const r=e.groups[s];t||this._syncBindGroup(r),this.setBindGroup(s,r,e.gpuProgram)}}_syncBindGroup(e){for(const t in e.resources){const s=e.resources[t];s.isUniformGroup&&this._renderer.ubo.updateUniformGroup(s)}}draw(e){const{geometry:t,shader:s,state:r,topology:n,size:o,start:a,instanceCount:l,skipSync:c}=e;this.setPipelineFromGeometryProgramAndState(t,s.gpuProgram,r,n),this.setGeometry(t,s.gpuProgram),this._setShaderBindGroups(s,c),t.indexBuffer?this.renderPassEncoder.drawIndexed(o||t.indexBuffer.data.length,l??t.instanceCount,a||0):this.renderPassEncoder.draw(o||t.getSize(),l??t.instanceCount,a||0)}finishRenderPass(){this.renderPassEncoder&&(this.renderPassEncoder.end(),this.renderPassEncoder=null)}postrender(){this.finishRenderPass(),this._gpu.device.queue.submit([this.commandEncoder.finish()]),this._resolveCommandFinished(),this.commandEncoder=null}restoreRenderPass(){const e=this._renderer.renderTarget.adaptor.getDescriptor(this._renderer.renderTarget.renderTarget,!1,[0,0,0,1],this._renderer.renderTarget.mipLevel,this._renderer.renderTarget.layer);this.renderPassEncoder=this.commandEncoder.beginRenderPass(e);const t=this._boundPipeline,s={...this._boundVertexBuffer},r=this._boundIndexBuffer,n={...this._boundBindGroup};this._clearCache();const o=this._renderer.renderTarget.viewport;this.renderPassEncoder.setViewport(o.x,o.y,o.width,o.height,0,1),this.setPipeline(t);for(const a in s)this._setVertexBuffer(a,s[a]);for(const a in n)this.setBindGroup(a,n[a],null);this._setIndexBuffer(r)}_clearCache(){for(let e=0;e<16;e++)this._boundBindGroup[e]=null,this._boundVertexBuffer[e]=null;this._boundIndexBuffer=null,this._boundPipeline=null}destroy(){this._renderer=null,this._gpu=null,this._boundBindGroup=null,this._boundVertexBuffer=null,this._boundIndexBuffer=null,this._boundPipeline=null}contextChange(e){this._gpu=e}}lu.extension={type:[A.WebGPUSystem],name:"encoder",priority:1};class cu{constructor(e){this._renderer=e}contextChange(){this.maxTextures=this._renderer.device.gpu.device.limits.maxSampledTexturesPerShaderStage,this.maxBatchableTextures=this.maxTextures}destroy(){}}cu.extension={type:[A.WebGPUSystem],name:"limits"};class hu{constructor(e){this._renderTargetStencilState=Object.create(null),this._renderer=e,e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){let t=this._renderTargetStencilState[e.uid];t||(t=this._renderTargetStencilState[e.uid]={stencilMode:ke.DISABLED,stencilReference:0}),this._activeRenderTarget=e,this.setStencilMode(t.stencilMode,t.stencilReference)}setStencilMode(e,t){const s=this._renderTargetStencilState[this._activeRenderTarget.uid];s.stencilMode=e,s.stencilReference=t;const r=this._renderer;r.pipeline.setStencilMode(e),r.encoder.renderPassEncoder.setStencilReference(t)}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._activeRenderTarget=null,this._renderTargetStencilState=null}}hu.extension={type:[A.WebGPUSystem],name:"stencil"};const dr={i32:{align:4,size:4},u32:{align:4,size:4},f32:{align:4,size:4},f16:{align:2,size:2},"vec2<i32>":{align:8,size:8},"vec2<u32>":{align:8,size:8},"vec2<f32>":{align:8,size:8},"vec2<f16>":{align:4,size:4},"vec3<i32>":{align:16,size:12},"vec3<u32>":{align:16,size:12},"vec3<f32>":{align:16,size:12},"vec3<f16>":{align:8,size:6},"vec4<i32>":{align:16,size:16},"vec4<u32>":{align:16,size:16},"vec4<f32>":{align:16,size:16},"vec4<f16>":{align:8,size:8},"mat2x2<f32>":{align:8,size:16},"mat2x2<f16>":{align:4,size:8},"mat3x2<f32>":{align:8,size:24},"mat3x2<f16>":{align:4,size:12},"mat4x2<f32>":{align:8,size:32},"mat4x2<f16>":{align:4,size:16},"mat2x3<f32>":{align:16,size:32},"mat2x3<f16>":{align:8,size:16},"mat3x3<f32>":{align:16,size:48},"mat3x3<f16>":{align:8,size:24},"mat4x3<f32>":{align:16,size:64},"mat4x3<f16>":{align:8,size:32},"mat2x4<f32>":{align:16,size:32},"mat2x4<f16>":{align:8,size:16},"mat3x4<f32>":{align:16,size:48},"mat3x4<f16>":{align:8,size:24},"mat4x4<f32>":{align:16,size:64},"mat4x4<f16>":{align:8,size:32}};function Sb(i){const e=i.map(s=>({data:s,offset:0,size:0}));let t=0;for(let s=0;s<e.length;s++){const r=e[s];let n=dr[r.data.type].size;const o=dr[r.data.type].align;if(!dr[r.data.type])throw new Error(`[Pixi.js] WebGPU UniformBuffer: Unknown type ${r.data.type}`);r.data.size>1&&(n=Math.max(n,o)*r.data.size),t=Math.ceil(t/o)*o,r.size=n,r.offset=t,t+=n}return t=Math.ceil(t/16)*16,{uboElements:e,size:t}}function Tb(i,e){const{size:t,align:s}=dr[i.data.type],r=(s-t)/4,n=i.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
|
|
844
844
|
v = uv.${i.data.name};
|
|
845
845
|
${e!==0?`offset += ${e};`:""}
|
|
846
846
|
|
|
@@ -856,7 +856,7 @@ fn mainFragment(
|
|
|
856
856
|
}
|
|
857
857
|
${r!==0?`arrayOffset += ${r};`:""}
|
|
858
858
|
}
|
|
859
|
-
`}function Tb(i){return Uh(i,"uboWgsl",Sb,My)}class uu extends Dh{constructor(){super({createUboElements:Eb,generateUboSync:Tb})}}uu.extension={type:[A.WebGPUSystem],name:"ubo"};const Lt=128;class du{constructor(e){this._bindGroupHash=Object.create(null),this._buffers=[],this._bindGroups=[],this._bufferResources=[],this._renderer=e,this._batchBuffer=new Cb({minUniformOffsetAlignment:Lt});const t=256/Lt;for(let s=0;s<t;s++){let r=Ee.UNIFORM|Ee.COPY_DST;s===0&&(r|=Ee.COPY_SRC),this._buffers.push(new Ut({data:this._batchBuffer.data,usage:r}))}}renderEnd(){this._uploadBindGroups(),this._resetBindGroups()}_resetBindGroups(){this._bindGroupHash=Object.create(null),this._batchBuffer.clear()}getUniformBindGroup(e,t){if(!t&&this._bindGroupHash[e.uid])return this._bindGroupHash[e.uid];this._renderer.ubo.ensureUniformGroup(e);const s=e.buffer.data,r=this._batchBuffer.addEmptyGroup(s.length);return this._renderer.ubo.syncUniformGroup(e,this._batchBuffer.data,r/4),this._bindGroupHash[e.uid]=this._getBindGroup(r/Lt),this._bindGroupHash[e.uid]}getUboResource(e){this._renderer.ubo.updateUniformGroup(e);const t=e.buffer.data,s=this._batchBuffer.addGroup(t);return this._getBufferResource(s/Lt)}getArrayBindGroup(e){const t=this._batchBuffer.addGroup(e);return this._getBindGroup(t/Lt)}getArrayBufferResource(e){const s=this._batchBuffer.addGroup(e)/Lt;return this._getBufferResource(s)}_getBufferResource(e){if(!this._bufferResources[e]){const t=this._buffers[e%2];this._bufferResources[e]=new Eo({buffer:t,offset:(e/2|0)*256,size:Lt})}return this._bufferResources[e]}_getBindGroup(e){if(!this._bindGroups[e]){const t=new Nt({0:this._getBufferResource(e)});this._bindGroups[e]=t}return this._bindGroups[e]}_uploadBindGroups(){const e=this._renderer.buffer,t=this._buffers[0];t.update(this._batchBuffer.byteIndex),e.updateBuffer(t);const s=this._renderer.gpu.device.createCommandEncoder();for(let r=1;r<this._buffers.length;r++){const n=this._buffers[r];s.copyBufferToBuffer(e.getGPUBuffer(t),Lt,e.getGPUBuffer(n),0,this._batchBuffer.byteIndex)}this._renderer.gpu.device.queue.submit([s.finish()])}destroy(){var e;for(let t=0;t<this._bindGroups.length;t++)(e=this._bindGroups[t])==null||e.destroy();this._bindGroups=null,this._bindGroupHash=null;for(let t=0;t<this._buffers.length;t++)this._buffers[t].destroy();this._buffers=null;for(let t=0;t<this._bufferResources.length;t++)this._bufferResources[t].destroy();this._bufferResources=null,this._batchBuffer.destroy(),this._renderer=null}}du.extension={type:[A.WebGPUPipes],name:"uniformBatch"};const Ab={"point-list":0,"line-list":1,"line-strip":2,"triangle-list":3,"triangle-strip":4};function wb(i,e,t,s,r){return i<<24|e<<16|t<<10|s<<5|r}function Ib(i,e,t,s,r){return t<<8|i<<5|s<<3|r<<1|e}class fu{constructor(e){this._moduleCache=Object.create(null),this._bufferLayoutsCache=Object.create(null),this._bindingNamesCache=Object.create(null),this._pipeCache=Object.create(null),this._pipeStateCaches=Object.create(null),this._colorMask=15,this._multisampleCount=1,this._colorTargetCount=1,this._renderer=e}contextChange(e){this._gpu=e,this.setStencilMode(ke.DISABLED),this._updatePipeHash()}setMultisampleCount(e){this._multisampleCount!==e&&(this._multisampleCount=e,this._updatePipeHash())}setRenderTarget(e){this._multisampleCount=e.msaaSamples,this._depthStencilAttachment=e.descriptor.depthStencilAttachment?1:0,this._colorTargetCount=e.colorTargetCount,this._updatePipeHash()}setColorMask(e){this._colorMask!==e&&(this._colorMask=e,this._updatePipeHash())}setStencilMode(e){this._stencilMode!==e&&(this._stencilMode=e,this._stencilState=Ft[e],this._updatePipeHash())}setPipeline(e,t,s,r){const n=this.getPipeline(e,t,s);r.setPipeline(n)}getPipeline(e,t,s,r){e._layoutKey||(Ih(e,t.attributeData),this._generateBufferKey(e)),r||(r=e.topology);const n=wb(e._layoutKey,t._layoutKey,s.data,s._blendModeId,Ab[r]);return this._pipeCache[n]?this._pipeCache[n]:(this._pipeCache[n]=this._createPipeline(e,t,s,r),this._pipeCache[n])}_createPipeline(e,t,s,r){const n=this._gpu.device,o=this._createVertexBufferLayouts(e,t),a=this._renderer.state.getColorTargets(s,this._colorTargetCount),l=this._stencilMode===ke.RENDERING_MASK_ADD?0:this._colorMask;for(let p=0;p<a.length;p++)a[p].writeMask=l;const c=this._renderer.shader.getProgramData(t).pipeline,h={vertex:{module:this._getModule(t.vertex.source),entryPoint:t.vertex.entryPoint,buffers:o},fragment:{module:this._getModule(t.fragment.source),entryPoint:t.fragment.entryPoint,targets:a},primitive:{topology:r,cullMode:s.cullMode},layout:c,multisample:{count:this._multisampleCount},label:"PIXI Pipeline"};return this._depthStencilAttachment&&(h.depthStencil={...this._stencilState,format:"depth24plus-stencil8",depthWriteEnabled:s.depthTest,depthCompare:s.depthTest?"less":"always"}),n.createRenderPipeline(h)}_getModule(e){return this._moduleCache[e]||this._createModule(e)}_createModule(e){const t=this._gpu.device;return this._moduleCache[e]=t.createShaderModule({code:e}),this._moduleCache[e]}_generateBufferKey(e){const t=[];let s=0;const r=Object.keys(e.attributes).sort();for(let o=0;o<r.length;o++){const a=e.attributes[r[o]];t[s++]=a.offset,t[s++]=a.format,t[s++]=a.stride,t[s++]=a.instance}const n=t.join("|");return e._layoutKey=Ks(n,"geometry"),e._layoutKey}_generateAttributeLocationsKey(e){const t=[];let s=0;const r=Object.keys(e.attributeData).sort();for(let o=0;o<r.length;o++){const a=e.attributeData[r[o]];t[s++]=a.location}const n=t.join("|");return e._attributeLocationsKey=Ks(n,"programAttributes"),e._attributeLocationsKey}getBufferNamesToBind(e,t){const s=e._layoutKey<<16|t._attributeLocationsKey;if(this._bindingNamesCache[s])return this._bindingNamesCache[s];const r=this._createVertexBufferLayouts(e,t),n=Object.create(null),o=t.attributeData;for(let a=0;a<r.length;a++){const c=Object.values(r[a].attributes)[0].shaderLocation;for(const h in o)if(o[h].location===c){n[a]=h;break}}return this._bindingNamesCache[s]=n,n}_createVertexBufferLayouts(e,t){t._attributeLocationsKey||this._generateAttributeLocationsKey(t);const s=e._layoutKey<<16|t._attributeLocationsKey;if(this._bufferLayoutsCache[s])return this._bufferLayoutsCache[s];const r=[];return e.buffers.forEach(n=>{const o={arrayStride:0,stepMode:"vertex",attributes:[]},a=o.attributes;for(const l in t.attributeData){const c=e.attributes[l];(c.divisor??1)!==1&&ie(`Attribute ${l} has an invalid divisor value of '${c.divisor}'. WebGPU only supports a divisor value of 1`),c.buffer===n&&(o.arrayStride=c.stride,o.stepMode=c.instance?"instance":"vertex",a.push({shaderLocation:t.attributeData[l].location,offset:c.offset,format:c.format}))}a.length&&r.push(o)}),this._bufferLayoutsCache[s]=r,r}_updatePipeHash(){const e=Ib(this._stencilMode,this._multisampleCount,this._colorMask,this._depthStencilAttachment,this._colorTargetCount);this._pipeStateCaches[e]||(this._pipeStateCaches[e]=Object.create(null)),this._pipeCache=this._pipeStateCaches[e]}destroy(){this._renderer=null,this._bufferLayoutsCache=null}}fu.extension={type:[A.WebGPUSystem],name:"pipeline"};class Rb{constructor(){this.contexts=[],this.msaaTextures=[],this.msaaSamples=1}}class Mb{init(e,t){this._renderer=e,this._renderTargetSystem=t}copyToTexture(e,t,s,r,n){const o=this._renderer,a=this._getGpuColorTexture(e),l=o.texture.getGpuSource(t.source);return o.encoder.commandEncoder.copyTextureToTexture({texture:a,origin:s},{texture:l,origin:n},r),t}startRenderPass(e,t=!0,s,r,n=0,o=0){var h,u;const l=this._renderTargetSystem.getGpuRenderTarget(e);if(o!==0&&((h=l.msaaTextures)!=null&&h.length))throw new Error("[RenderTargetSystem] Rendering to array layers is not supported with MSAA render targets.");if(n>0&&((u=l.msaaTextures)!=null&&u.length))throw new Error("[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.");const c=this.getDescriptor(e,t,s,n,o);l.descriptor=c,this._renderer.pipeline.setRenderTarget(l),this._renderer.encoder.beginRenderPass(l),this._renderer.encoder.setViewport(r)}finishRenderPass(){this._renderer.encoder.endRenderPass()}_getGpuColorTexture(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);return t.contexts[0]?t.contexts[0].getCurrentTexture():this._renderer.texture.getGpuSource(e.colorTextures[0].source)}getDescriptor(e,t,s,r=0,n=0){typeof t=="boolean"&&(t=t?st.ALL:st.NONE);const o=this._renderTargetSystem,a=o.getGpuRenderTarget(e),l=e.colorTextures.map((u,p)=>{const d=a.contexts[p];let g,_;if(d){if(n!==0)throw new Error("[RenderTargetSystem] Rendering to array layers is not supported for canvas targets.");g=d.getCurrentTexture().createView()}else g=this._renderer.texture.getGpuSource(u).createView({dimension:"2d",baseMipLevel:r,mipLevelCount:1,baseArrayLayer:n,arrayLayerCount:1});a.msaaTextures[p]&&(_=g,g=this._renderer.texture.getTextureView(a.msaaTextures[p]));const b=t&st.COLOR?"clear":"load";return s??(s=o.defaultClearColor),{view:g,resolveTarget:_,clearValue:s,storeOp:"store",loadOp:b}});let c;if((e.stencil||e.depth)&&!e.depthStencilTexture&&(e.ensureDepthStencilTexture(),e.depthStencilTexture.source.sampleCount=a.msaa?4:1),e.depthStencilTexture){const u=t&st.STENCIL?"clear":"load",p=t&st.DEPTH?"clear":"load";c={view:this._renderer.texture.getGpuSource(e.depthStencilTexture.source).createView({dimension:"2d",baseMipLevel:r,mipLevelCount:1,baseArrayLayer:n,arrayLayerCount:1}),stencilStoreOp:"store",stencilLoadOp:u,depthClearValue:1,depthLoadOp:p,depthStoreOp:"store"}}return{colorAttachments:l,depthStencilAttachment:c}}clear(e,t=!0,s,r,n=0,o=0){if(!t)return;const{gpu:a,encoder:l}=this._renderer,c=a.device;if(l.commandEncoder===null){const u=c.createCommandEncoder(),p=this.getDescriptor(e,t,s,n,o),d=u.beginRenderPass(p);d.setViewport(r.x,r.y,r.width,r.height,0,1),d.end();const g=u.finish();c.queue.submit([g])}else this.startRenderPass(e,t,s,r,n,o)}initGpuRenderTarget(e){e.isRoot=!0;const t=new Rb;return t.colorTargetCount=e.colorTextures.length,e.colorTextures.forEach((s,r)=>{if(s instanceof mt){const n=s.resource.getContext("webgpu"),o=s.transparent?"premultiplied":"opaque";try{n.configure({device:this._renderer.gpu.device,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,format:"bgra8unorm",alphaMode:o})}catch(a){console.error(a)}t.contexts[r]=n}if(t.msaa=s.source.antialias,s.source.antialias){const n=new De({width:0,height:0,sampleCount:4,arrayLayerCount:s.source.arrayLayerCount});t.msaaTextures[r]=n}}),t.msaa&&(t.msaaSamples=4,e.depthStencilTexture&&(e.depthStencilTexture.source.sampleCount=4)),t}destroyGpuRenderTarget(e){e.contexts.forEach(t=>{t.unconfigure()}),e.msaaTextures.forEach(t=>{t.destroy()}),e.msaaTextures.length=0,e.contexts.length=0}ensureDepthStencilTexture(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);e.depthStencilTexture&&t.msaa&&(e.depthStencilTexture.source.sampleCount=4)}resizeGpuRenderTarget(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);t.width=e.width,t.height=e.height,t.msaa&&e.colorTextures.forEach((s,r)=>{const n=t.msaaTextures[r];n==null||n.resize(s.source.width,s.source.height,s.source._resolution)})}}class pu extends yo{constructor(e){super(e),this.adaptor=new Mb,this.adaptor.init(e,this)}}pu.extension={type:[A.WebGPUSystem],name:"renderTarget"};class mu{constructor(){this._gpuProgramData=Object.create(null)}contextChange(e){this._gpu=e}getProgramData(e){return this._gpuProgramData[e._layoutKey]||this._createGPUProgramData(e)}_createGPUProgramData(e){const t=this._gpu.device,s=e.gpuLayout.map(n=>t.createBindGroupLayout({entries:n})),r={bindGroupLayouts:s};return this._gpuProgramData[e._layoutKey]={bindGroups:s,pipeline:t.createPipelineLayout(r)},this._gpuProgramData[e._layoutKey]}destroy(){this._gpu=null,this._gpuProgramData=null}}mu.extension={type:[A.WebGPUSystem],name:"shader"};const et={};et.normal={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}},et.add={alpha:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one",operation:"add"}},et.multiply={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"}},et.screen={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},et.overlay={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},et.none={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"zero",operation:"add"}},et["normal-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"}},et["add-npm"]={alpha:{srcFactor:"one",dstFactor:"one",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"}},et["screen-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src",operation:"add"}},et.erase={alpha:{srcFactor:"zero",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"add"}},et.min={alpha:{srcFactor:"one",dstFactor:"one",operation:"min"},color:{srcFactor:"one",dstFactor:"one",operation:"min"}},et.max={alpha:{srcFactor:"one",dstFactor:"one",operation:"max"},color:{srcFactor:"one",dstFactor:"one",operation:"max"}};class gu{constructor(){this.defaultState=new It,this.defaultState.blend=!0}contextChange(e){this.gpu=e}getColorTargets(e,t){const s=et[e.blendMode]||et.normal,r=[],n={format:"bgra8unorm",writeMask:0,blend:s};for(let o=0;o<t;o++)r[o]=n;return r}destroy(){this.gpu=null}}gu.extension={type:[A.WebGPUSystem],name:"state"};const Pb={type:"image",upload(i,e,t,s=0){const r=i.resource,n=(i.pixelWidth|0)*(i.pixelHeight|0),o=r.byteLength/n;t.device.queue.writeTexture({texture:e,origin:{x:0,y:0,z:s}},r,{offset:0,rowsPerImage:i.pixelHeight,bytesPerRow:i.pixelWidth*o},{width:i.pixelWidth,height:i.pixelHeight,depthOrArrayLayers:1})}},_u={"bc1-rgba-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"bc2-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc3-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc7-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"etc1-rgb-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"etc2-rgba8unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"astc-4x4-unorm":{blockBytes:16,blockWidth:4,blockHeight:4}},kb={blockBytes:4,blockWidth:1,blockHeight:1},Ob={type:"compressed",upload(i,e,t,s=0){let r=i.pixelWidth,n=i.pixelHeight;const o=_u[i.format]||kb;for(let a=0;a<i.resource.length;a++){const l=i.resource[a],c=Math.ceil(r/o.blockWidth)*o.blockBytes;t.device.queue.writeTexture({texture:e,mipLevel:a,origin:{x:0,y:0,z:s}},l,{offset:0,bytesPerRow:c},{width:Math.ceil(r/o.blockWidth)*o.blockWidth,height:Math.ceil(n/o.blockHeight)*o.blockHeight,depthOrArrayLayers:1}),r=Math.max(r>>1,1),n=Math.max(n>>1,1)}}},yu=["right","left","top","bottom","front","back"];function Bb(i){return{type:"cube",upload(e,t,s){const r=e.faces;for(let n=0;n<yu.length;n++){const o=yu[n],a=r[o];(i[a.uploadMethodId]||i.image).upload(a,t,s,n)}}}}const bu={type:"image",upload(i,e,t,s=0){const r=i.resource;if(!r)return;if(globalThis.HTMLImageElement&&r instanceof HTMLImageElement){const l=pe.get().createCanvas(r.width,r.height);l.getContext("2d").drawImage(r,0,0,r.width,r.height),i.resource=l,ie("ImageSource: Image element passed, converting to canvas and replacing resource.")}const n=Math.min(e.width,i.resourceWidth||i.pixelWidth),o=Math.min(e.height,i.resourceHeight||i.pixelHeight),a=i.alphaMode==="premultiply-alpha-on-upload";t.device.queue.copyExternalImageToTexture({source:r},{texture:e,origin:{x:0,y:0,z:s},premultipliedAlpha:a},{width:n,height:o})}},Db={type:"video",upload(i,e,t,s){bu.upload(i,e,t,s)}};class Nb{constructor(e){this.device=e,this.sampler=e.createSampler({minFilter:"linear"}),this.pipelines={}}_getMipmapPipeline(e){let t=this.pipelines[e];return t||(this.mipmapShaderModule||(this.mipmapShaderModule=this.device.createShaderModule({code:`
|
|
859
|
+
`}function Ab(i){return Uh(i,"uboWgsl",Tb,Py)}class uu extends Dh{constructor(){super({createUboElements:Sb,generateUboSync:Ab})}}uu.extension={type:[A.WebGPUSystem],name:"ubo"};const Lt=128;class du{constructor(e){this._bindGroupHash=Object.create(null),this._buffers=[],this._bindGroups=[],this._bufferResources=[],this._renderer=e,this._batchBuffer=new Eb({minUniformOffsetAlignment:Lt});const t=256/Lt;for(let s=0;s<t;s++){let r=Ee.UNIFORM|Ee.COPY_DST;s===0&&(r|=Ee.COPY_SRC),this._buffers.push(new Ut({data:this._batchBuffer.data,usage:r}))}}renderEnd(){this._uploadBindGroups(),this._resetBindGroups()}_resetBindGroups(){this._bindGroupHash=Object.create(null),this._batchBuffer.clear()}getUniformBindGroup(e,t){if(!t&&this._bindGroupHash[e.uid])return this._bindGroupHash[e.uid];this._renderer.ubo.ensureUniformGroup(e);const s=e.buffer.data,r=this._batchBuffer.addEmptyGroup(s.length);return this._renderer.ubo.syncUniformGroup(e,this._batchBuffer.data,r/4),this._bindGroupHash[e.uid]=this._getBindGroup(r/Lt),this._bindGroupHash[e.uid]}getUboResource(e){this._renderer.ubo.updateUniformGroup(e);const t=e.buffer.data,s=this._batchBuffer.addGroup(t);return this._getBufferResource(s/Lt)}getArrayBindGroup(e){const t=this._batchBuffer.addGroup(e);return this._getBindGroup(t/Lt)}getArrayBufferResource(e){const s=this._batchBuffer.addGroup(e)/Lt;return this._getBufferResource(s)}_getBufferResource(e){if(!this._bufferResources[e]){const t=this._buffers[e%2];this._bufferResources[e]=new Eo({buffer:t,offset:(e/2|0)*256,size:Lt})}return this._bufferResources[e]}_getBindGroup(e){if(!this._bindGroups[e]){const t=new Nt({0:this._getBufferResource(e)});this._bindGroups[e]=t}return this._bindGroups[e]}_uploadBindGroups(){const e=this._renderer.buffer,t=this._buffers[0];t.update(this._batchBuffer.byteIndex),e.updateBuffer(t);const s=this._renderer.gpu.device.createCommandEncoder();for(let r=1;r<this._buffers.length;r++){const n=this._buffers[r];s.copyBufferToBuffer(e.getGPUBuffer(t),Lt,e.getGPUBuffer(n),0,this._batchBuffer.byteIndex)}this._renderer.gpu.device.queue.submit([s.finish()])}destroy(){var e;for(let t=0;t<this._bindGroups.length;t++)(e=this._bindGroups[t])==null||e.destroy();this._bindGroups=null,this._bindGroupHash=null;for(let t=0;t<this._buffers.length;t++)this._buffers[t].destroy();this._buffers=null;for(let t=0;t<this._bufferResources.length;t++)this._bufferResources[t].destroy();this._bufferResources=null,this._batchBuffer.destroy(),this._renderer=null}}du.extension={type:[A.WebGPUPipes],name:"uniformBatch"};const wb={"point-list":0,"line-list":1,"line-strip":2,"triangle-list":3,"triangle-strip":4};function Ib(i,e,t,s,r){return i<<24|e<<16|t<<10|s<<5|r}function Rb(i,e,t,s,r){return t<<8|i<<5|s<<3|r<<1|e}class fu{constructor(e){this._moduleCache=Object.create(null),this._bufferLayoutsCache=Object.create(null),this._bindingNamesCache=Object.create(null),this._pipeCache=Object.create(null),this._pipeStateCaches=Object.create(null),this._colorMask=15,this._multisampleCount=1,this._colorTargetCount=1,this._renderer=e}contextChange(e){this._gpu=e,this.setStencilMode(ke.DISABLED),this._updatePipeHash()}setMultisampleCount(e){this._multisampleCount!==e&&(this._multisampleCount=e,this._updatePipeHash())}setRenderTarget(e){this._multisampleCount=e.msaaSamples,this._depthStencilAttachment=e.descriptor.depthStencilAttachment?1:0,this._colorTargetCount=e.colorTargetCount,this._updatePipeHash()}setColorMask(e){this._colorMask!==e&&(this._colorMask=e,this._updatePipeHash())}setStencilMode(e){this._stencilMode!==e&&(this._stencilMode=e,this._stencilState=Ft[e],this._updatePipeHash())}setPipeline(e,t,s,r){const n=this.getPipeline(e,t,s);r.setPipeline(n)}getPipeline(e,t,s,r){e._layoutKey||(Ih(e,t.attributeData),this._generateBufferKey(e)),r||(r=e.topology);const n=Ib(e._layoutKey,t._layoutKey,s.data,s._blendModeId,wb[r]);return this._pipeCache[n]?this._pipeCache[n]:(this._pipeCache[n]=this._createPipeline(e,t,s,r),this._pipeCache[n])}_createPipeline(e,t,s,r){const n=this._gpu.device,o=this._createVertexBufferLayouts(e,t),a=this._renderer.state.getColorTargets(s,this._colorTargetCount),l=this._stencilMode===ke.RENDERING_MASK_ADD?0:this._colorMask;for(let p=0;p<a.length;p++)a[p].writeMask=l;const c=this._renderer.shader.getProgramData(t).pipeline,h={vertex:{module:this._getModule(t.vertex.source),entryPoint:t.vertex.entryPoint,buffers:o},fragment:{module:this._getModule(t.fragment.source),entryPoint:t.fragment.entryPoint,targets:a},primitive:{topology:r,cullMode:s.cullMode},layout:c,multisample:{count:this._multisampleCount},label:"PIXI Pipeline"};return this._depthStencilAttachment&&(h.depthStencil={...this._stencilState,format:"depth24plus-stencil8",depthWriteEnabled:s.depthTest,depthCompare:s.depthTest?"less":"always"}),n.createRenderPipeline(h)}_getModule(e){return this._moduleCache[e]||this._createModule(e)}_createModule(e){const t=this._gpu.device;return this._moduleCache[e]=t.createShaderModule({code:e}),this._moduleCache[e]}_generateBufferKey(e){const t=[];let s=0;const r=Object.keys(e.attributes).sort();for(let o=0;o<r.length;o++){const a=e.attributes[r[o]];t[s++]=a.offset,t[s++]=a.format,t[s++]=a.stride,t[s++]=a.instance}const n=t.join("|");return e._layoutKey=Ks(n,"geometry"),e._layoutKey}_generateAttributeLocationsKey(e){const t=[];let s=0;const r=Object.keys(e.attributeData).sort();for(let o=0;o<r.length;o++){const a=e.attributeData[r[o]];t[s++]=a.location}const n=t.join("|");return e._attributeLocationsKey=Ks(n,"programAttributes"),e._attributeLocationsKey}getBufferNamesToBind(e,t){const s=e._layoutKey<<16|t._attributeLocationsKey;if(this._bindingNamesCache[s])return this._bindingNamesCache[s];const r=this._createVertexBufferLayouts(e,t),n=Object.create(null),o=t.attributeData;for(let a=0;a<r.length;a++){const c=Object.values(r[a].attributes)[0].shaderLocation;for(const h in o)if(o[h].location===c){n[a]=h;break}}return this._bindingNamesCache[s]=n,n}_createVertexBufferLayouts(e,t){t._attributeLocationsKey||this._generateAttributeLocationsKey(t);const s=e._layoutKey<<16|t._attributeLocationsKey;if(this._bufferLayoutsCache[s])return this._bufferLayoutsCache[s];const r=[];return e.buffers.forEach(n=>{const o={arrayStride:0,stepMode:"vertex",attributes:[]},a=o.attributes;for(const l in t.attributeData){const c=e.attributes[l];(c.divisor??1)!==1&&ie(`Attribute ${l} has an invalid divisor value of '${c.divisor}'. WebGPU only supports a divisor value of 1`),c.buffer===n&&(o.arrayStride=c.stride,o.stepMode=c.instance?"instance":"vertex",a.push({shaderLocation:t.attributeData[l].location,offset:c.offset,format:c.format}))}a.length&&r.push(o)}),this._bufferLayoutsCache[s]=r,r}_updatePipeHash(){const e=Rb(this._stencilMode,this._multisampleCount,this._colorMask,this._depthStencilAttachment,this._colorTargetCount);this._pipeStateCaches[e]||(this._pipeStateCaches[e]=Object.create(null)),this._pipeCache=this._pipeStateCaches[e]}destroy(){this._renderer=null,this._bufferLayoutsCache=null}}fu.extension={type:[A.WebGPUSystem],name:"pipeline"};class Mb{constructor(){this.contexts=[],this.msaaTextures=[],this.msaaSamples=1}}class Pb{init(e,t){this._renderer=e,this._renderTargetSystem=t}copyToTexture(e,t,s,r,n){const o=this._renderer,a=this._getGpuColorTexture(e),l=o.texture.getGpuSource(t.source);return o.encoder.commandEncoder.copyTextureToTexture({texture:a,origin:s},{texture:l,origin:n},r),t}startRenderPass(e,t=!0,s,r,n=0,o=0){var h,u;const l=this._renderTargetSystem.getGpuRenderTarget(e);if(o!==0&&((h=l.msaaTextures)!=null&&h.length))throw new Error("[RenderTargetSystem] Rendering to array layers is not supported with MSAA render targets.");if(n>0&&((u=l.msaaTextures)!=null&&u.length))throw new Error("[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.");const c=this.getDescriptor(e,t,s,n,o);l.descriptor=c,this._renderer.pipeline.setRenderTarget(l),this._renderer.encoder.beginRenderPass(l),this._renderer.encoder.setViewport(r)}finishRenderPass(){this._renderer.encoder.endRenderPass()}_getGpuColorTexture(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);return t.contexts[0]?t.contexts[0].getCurrentTexture():this._renderer.texture.getGpuSource(e.colorTextures[0].source)}getDescriptor(e,t,s,r=0,n=0){typeof t=="boolean"&&(t=t?st.ALL:st.NONE);const o=this._renderTargetSystem,a=o.getGpuRenderTarget(e),l=e.colorTextures.map((u,p)=>{const d=a.contexts[p];let g,_;if(d){if(n!==0)throw new Error("[RenderTargetSystem] Rendering to array layers is not supported for canvas targets.");g=d.getCurrentTexture().createView()}else g=this._renderer.texture.getGpuSource(u).createView({dimension:"2d",baseMipLevel:r,mipLevelCount:1,baseArrayLayer:n,arrayLayerCount:1});a.msaaTextures[p]&&(_=g,g=this._renderer.texture.getTextureView(a.msaaTextures[p]));const b=t&st.COLOR?"clear":"load";return s??(s=o.defaultClearColor),{view:g,resolveTarget:_,clearValue:s,storeOp:"store",loadOp:b}});let c;if((e.stencil||e.depth)&&!e.depthStencilTexture&&(e.ensureDepthStencilTexture(),e.depthStencilTexture.source.sampleCount=a.msaa?4:1),e.depthStencilTexture){const u=t&st.STENCIL?"clear":"load",p=t&st.DEPTH?"clear":"load";c={view:this._renderer.texture.getGpuSource(e.depthStencilTexture.source).createView({dimension:"2d",baseMipLevel:r,mipLevelCount:1,baseArrayLayer:n,arrayLayerCount:1}),stencilStoreOp:"store",stencilLoadOp:u,depthClearValue:1,depthLoadOp:p,depthStoreOp:"store"}}return{colorAttachments:l,depthStencilAttachment:c}}clear(e,t=!0,s,r,n=0,o=0){if(!t)return;const{gpu:a,encoder:l}=this._renderer,c=a.device;if(l.commandEncoder===null){const u=c.createCommandEncoder(),p=this.getDescriptor(e,t,s,n,o),d=u.beginRenderPass(p);d.setViewport(r.x,r.y,r.width,r.height,0,1),d.end();const g=u.finish();c.queue.submit([g])}else this.startRenderPass(e,t,s,r,n,o)}initGpuRenderTarget(e){e.isRoot=!0;const t=new Mb;return t.colorTargetCount=e.colorTextures.length,e.colorTextures.forEach((s,r)=>{if(s instanceof mt){const n=s.resource.getContext("webgpu"),o=s.transparent?"premultiplied":"opaque";try{n.configure({device:this._renderer.gpu.device,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,format:"bgra8unorm",alphaMode:o})}catch(a){console.error(a)}t.contexts[r]=n}if(t.msaa=s.source.antialias,s.source.antialias){const n=new De({width:0,height:0,sampleCount:4,arrayLayerCount:s.source.arrayLayerCount});t.msaaTextures[r]=n}}),t.msaa&&(t.msaaSamples=4,e.depthStencilTexture&&(e.depthStencilTexture.source.sampleCount=4)),t}destroyGpuRenderTarget(e){e.contexts.forEach(t=>{t.unconfigure()}),e.msaaTextures.forEach(t=>{t.destroy()}),e.msaaTextures.length=0,e.contexts.length=0}ensureDepthStencilTexture(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);e.depthStencilTexture&&t.msaa&&(e.depthStencilTexture.source.sampleCount=4)}resizeGpuRenderTarget(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);t.width=e.width,t.height=e.height,t.msaa&&e.colorTextures.forEach((s,r)=>{const n=t.msaaTextures[r];n==null||n.resize(s.source.width,s.source.height,s.source._resolution)})}}class pu extends yo{constructor(e){super(e),this.adaptor=new Pb,this.adaptor.init(e,this)}}pu.extension={type:[A.WebGPUSystem],name:"renderTarget"};class mu{constructor(){this._gpuProgramData=Object.create(null)}contextChange(e){this._gpu=e}getProgramData(e){return this._gpuProgramData[e._layoutKey]||this._createGPUProgramData(e)}_createGPUProgramData(e){const t=this._gpu.device,s=e.gpuLayout.map(n=>t.createBindGroupLayout({entries:n})),r={bindGroupLayouts:s};return this._gpuProgramData[e._layoutKey]={bindGroups:s,pipeline:t.createPipelineLayout(r)},this._gpuProgramData[e._layoutKey]}destroy(){this._gpu=null,this._gpuProgramData=null}}mu.extension={type:[A.WebGPUSystem],name:"shader"};const et={};et.normal={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}},et.add={alpha:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one",operation:"add"}},et.multiply={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"}},et.screen={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},et.overlay={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},et.none={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"zero",operation:"add"}},et["normal-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"}},et["add-npm"]={alpha:{srcFactor:"one",dstFactor:"one",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"}},et["screen-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src",operation:"add"}},et.erase={alpha:{srcFactor:"zero",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"add"}},et.min={alpha:{srcFactor:"one",dstFactor:"one",operation:"min"},color:{srcFactor:"one",dstFactor:"one",operation:"min"}},et.max={alpha:{srcFactor:"one",dstFactor:"one",operation:"max"},color:{srcFactor:"one",dstFactor:"one",operation:"max"}};class gu{constructor(){this.defaultState=new It,this.defaultState.blend=!0}contextChange(e){this.gpu=e}getColorTargets(e,t){const s=et[e.blendMode]||et.normal,r=[],n={format:"bgra8unorm",writeMask:0,blend:s};for(let o=0;o<t;o++)r[o]=n;return r}destroy(){this.gpu=null}}gu.extension={type:[A.WebGPUSystem],name:"state"};const kb={type:"image",upload(i,e,t,s=0){const r=i.resource,n=(i.pixelWidth|0)*(i.pixelHeight|0),o=r.byteLength/n;t.device.queue.writeTexture({texture:e,origin:{x:0,y:0,z:s}},r,{offset:0,rowsPerImage:i.pixelHeight,bytesPerRow:i.pixelWidth*o},{width:i.pixelWidth,height:i.pixelHeight,depthOrArrayLayers:1})}},_u={"bc1-rgba-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"bc2-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc3-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc7-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"etc1-rgb-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"etc2-rgba8unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"astc-4x4-unorm":{blockBytes:16,blockWidth:4,blockHeight:4}},Ob={blockBytes:4,blockWidth:1,blockHeight:1},Bb={type:"compressed",upload(i,e,t,s=0){let r=i.pixelWidth,n=i.pixelHeight;const o=_u[i.format]||Ob;for(let a=0;a<i.resource.length;a++){const l=i.resource[a],c=Math.ceil(r/o.blockWidth)*o.blockBytes;t.device.queue.writeTexture({texture:e,mipLevel:a,origin:{x:0,y:0,z:s}},l,{offset:0,bytesPerRow:c},{width:Math.ceil(r/o.blockWidth)*o.blockWidth,height:Math.ceil(n/o.blockHeight)*o.blockHeight,depthOrArrayLayers:1}),r=Math.max(r>>1,1),n=Math.max(n>>1,1)}}},yu=["right","left","top","bottom","front","back"];function Db(i){return{type:"cube",upload(e,t,s){const r=e.faces;for(let n=0;n<yu.length;n++){const o=yu[n],a=r[o];(i[a.uploadMethodId]||i.image).upload(a,t,s,n)}}}}const bu={type:"image",upload(i,e,t,s=0){const r=i.resource;if(!r)return;if(globalThis.HTMLImageElement&&r instanceof HTMLImageElement){const l=pe.get().createCanvas(r.width,r.height);l.getContext("2d").drawImage(r,0,0,r.width,r.height),i.resource=l,ie("ImageSource: Image element passed, converting to canvas and replacing resource.")}const n=Math.min(e.width,i.resourceWidth||i.pixelWidth),o=Math.min(e.height,i.resourceHeight||i.pixelHeight),a=i.alphaMode==="premultiply-alpha-on-upload";t.device.queue.copyExternalImageToTexture({source:r},{texture:e,origin:{x:0,y:0,z:s},premultipliedAlpha:a},{width:n,height:o})}},Nb={type:"video",upload(i,e,t,s){bu.upload(i,e,t,s)}};class Ub{constructor(e){this.device=e,this.sampler=e.createSampler({minFilter:"linear"}),this.pipelines={}}_getMipmapPipeline(e){let t=this.pipelines[e];return t||(this.mipmapShaderModule||(this.mipmapShaderModule=this.device.createShaderModule({code:`
|
|
860
860
|
var<private> pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>(
|
|
861
861
|
vec2<f32>(-1.0, -1.0), vec2<f32>(-1.0, 3.0), vec2<f32>(3.0, -1.0));
|
|
862
862
|
|
|
@@ -880,7 +880,7 @@ fn mainFragment(
|
|
|
880
880
|
fn fragmentMain(@location(0) texCoord : vec2<f32>) -> @location(0) vec4<f32> {
|
|
881
881
|
return textureSample(img, imgSampler, texCoord);
|
|
882
882
|
}
|
|
883
|
-
`})),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 s=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};s=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 p=s.createView({baseMipLevel:h++,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),d=o.beginRenderPass({colorAttachments:[{view:p,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=p}}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:s,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||s.destroy(),e}}class Ub{constructor(e){this.textureView=null,this.gpuTexture=e}destroy(){this.gpuTexture.destroy(),this.textureView=null,this.gpuTexture=null}}class vu{constructor(e){this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._renderer=e,e.gc.addCollection(this,"_bindGroupHash","hash"),this._managedTextures=new Rt({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"gpuTextureSource"});const t={image:bu,buffer:Pb,video:Db,compressed:Ob};this._uploads={...t,cube:Bb(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 s=_u[e.format]||{blockWidth:1,blockHeight:1},r=Math.ceil(e.pixelWidth/s.blockWidth)*s.blockWidth,n=Math.ceil(e.pixelHeight/s.blockHeight)*s.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 Ub(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 Nb(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],s=t==null?void 0:t.gpuTexture;s?(s.width!==e.pixelWidth||s.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 Nt({0:t,1:t.style,2:new gt({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 s=t._gpuData[this._renderer.uid];return s||(this.initSource(t),s=t._gpuData[this._renderer.uid]),s.textureView||(s.textureView=s.gpuTexture.createView({dimension:t.viewDimension})),s.textureView}generateCanvas(e){const t=this._renderer,s=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"}),s.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([s.finish()]),r}getPixels(e){const t=this.generateCanvas(e),s=Yn.getOptimalCanvasAndContext(t.width,t.height),r=s.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 Yn.returnCanvasAndContext(s),{pixels:l,width:n,height:o}}destroy(){this._managedTextures.destroy();for(const e of Object.keys(this._bindGroupHash)){const t=Number(e),s=this._bindGroupHash[t];s==null||s.destroy()}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._gpuSamplers=null,this._bindGroupHash=null}}vu.extension={type:[A.WebGPUSystem],name:"texture"};class xu{constructor(){this._maxTextures=0}contextChange(e){const t=new gt({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 s=Mn({name:"graphics",bits:[rc,oc(this._maxTextures),M_,Bn]});this.shader=new wt({gpuProgram:s,resources:{localUniforms:t}})}execute(e,t){const s=t.context,r=s.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(s),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 p=l.instructions;let d=null;for(let g=0;g<l.instructionSize;g++){const _=p[g];if(_.topology!==d&&(d=_.topology,c.setPipelineFromGeometryProgramAndState(a.geometry,r.gpuProgram,e.state,_.topology)),r.groups[1]=_.bindGroup,!_.gpuBindGroup){const b=_.textures;_.bindGroup=An(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}}xu.extension={type:[A.WebGPUPipesAdaptor],name:"graphics"};class Cu{init(){const e=Mn({name:"mesh",bits:[nr,B_,Bn]});this._shader=new wt({gpuProgram:e,resources:{uTexture:j.EMPTY._source,uSampler:j.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new H}}}})}execute(e,t){const s=e.renderer;let r=t._shader;if(!r)r=this._shader,r.groups[2]=s.texture.getTextureBindGroup(t.texture);else if(!r.gpuProgram){ie("Mesh shader has no gpuProgram",t.shader);return}const n=r.gpuProgram;if(n.autoAssignGlobalUniforms&&(r.groups[0]=s.globalUniforms.bindGroup),n.autoAssignLocalUniforms){const o=e.localUniforms;r.groups[1]=s.renderPipes.uniformBatch.getUniformBindGroup(o,!0)}s.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}Cu.extension={type:[A.WebGPUPipesAdaptor],name:"mesh"};const Gb=[..._o,uu,lu,Ao,cu,ou,vu,pu,mu,gu,fu,au,hu,nu],Fb=[...xh,du],Lb=[th,Cu,xu],Eu=[],Su=[],Tu=[];Q.handleByNamedList(A.WebGPUSystem,Eu),Q.handleByNamedList(A.WebGPUPipes,Su),Q.handleByNamedList(A.WebGPUPipesAdaptor,Tu),Q.add(...Gb,...Fb,...Lb);class Wb extends ni{constructor(){const e={name:"webgpu",type:_t.WEBGPU,systems:Eu,renderPipes:Su,renderPipeAdaptors:Tu};super(e)}}const Hb=Object.freeze(Object.defineProperty({__proto__:null,WebGPURenderer:Wb},Symbol.toStringTag,{value:"Module"}));Q.add(Of,Bf);const Ps=480,yi=480;class Vb{constructor(){this.container=null,this.resizeObserver=null,this.mode="floating",this.targetEl=null,this.app=new Ll}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:Ps,height:yi,backgroundAlpha:0,antialias:!0,resolution:window.devicePixelRatio||1,autoDensity:!0}),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:`${Ps}px`,height:`${yi}px`,zIndex:"2147483646",pointerEvents:"none",overflow:"visible"}),document.body.appendChild(this.container));const s=this.app.canvas;return Object.assign(s.style,{width:"100%",height:"100%",display:"block",pointerEvents:"auto"}),this.container.appendChild(s),this.setupResize(),s}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,s=Math.min(Ps,t),r=s/Ps,n=yi*r;this.container&&(this.container.style.width=`${s}px`,this.container.style.height=`${n}px`)}this.app.renderer.resize(Ps,yi)};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 Ps}get stageHeight(){return yi}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 zb(){var i,e;return((e=(i=globalThis.matchMedia)==null?void 0:i.call(globalThis,"(prefers-reduced-motion: reduce)"))==null?void 0:e.matches)??!1}const bi={easeOutCubic:i=>1-Math.pow(1-i,3),easeInCubic:i=>i*i*i,easeOutBack:i=>1+2.70158*Math.pow(i-1,3)+1.70158*Math.pow(i-1,2),easeInOutSine:i=>-(Math.cos(Math.PI*i)-1)/2};function fr(i){const{target:e,props:t,duration:s,easing:r=bi.easeOutCubic,delay:n=0,onComplete:o,ticker:a}=i;if(zb()){for(const p of Object.keys(t))e[p]=t[p];return o==null||o(),()=>{}}const l={};for(const p of Object.keys(t))l[p]=e[p];let c=-n,h=!1;const u=p=>{if(h||(c+=p.deltaMS,c<0))return;const d=Math.min(c/s,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 vi=200,Wt=vi*(480/854),Au=280;class $b{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+Wt}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:`${vi}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+Wt}async loadIdleImage(e){const t=j.from(e),s=new Dt(t);s.width=vi,s.height=Wt,s.anchor.set(.5,1),this.idleGroup=new Ve,this.idleGroup.addChild(s),this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+Wt}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+Wt,this.cancelEntrance=fr({target:this.container,props:{y:t},duration:700,easing:bi.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,fr({target:this.container,props:{y:this.stageHeight+Wt},duration:450,easing:bi.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 Ce(-vi/2,-Wt,vi,Wt),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 s=()=>{var l;const r=j.from(e);this.liveSprite=new Dt(r);const n=e.videoWidth||1,o=e.videoHeight||1,a=Au/n;this.liveSprite.width=Au,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,fr({target:this.liveSprite,props:{alpha:1},duration:500,easing:bi.easeInOutSine,ticker:t})};if(e.videoWidth>0&&e.videoHeight>0)s();else{const r=()=>{e.removeEventListener("loadeddata",r),e.removeEventListener("resize",r),s()};e.addEventListener("loadeddata",r),e.addEventListener("resize",r)}}clearLiveVideo(e){this.liveSprite&&fr({target:this.liveSprite,props:{alpha:0},duration:400,easing:bi.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 jb=[{urls:"stun:stun.l.google.com:19302"}],Xb=3e3,Yb="oai-events";class qb{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:jb}),this.setupPeerConnectionHandlers();for(const o of this.micStream.getAudioTracks())this.pc.addTrack(o,this.micStream);this.dc=this.pc.createDataChannel(Yb),this.setupDataChannelHandlers();const s=await this.pc.createOffer();await this.pc.setLocalDescription(s),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(s){const r=s instanceof Error?s:new Error(String(s));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,s,r,n;const e=(t=this.pc)==null?void 0:t.connectionState;console.log("[RealtimeSession] Connection state:",e),e==="connected"?(this._connected=!0,(s=this.onConnected)==null||s.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 s;const r=()=>{clearTimeout(s);try{t.removeEventListener("icegatheringstatechange",n)}catch{}e()},n=()=>{t.iceGatheringState==="complete"&&r()};t.addEventListener("icegatheringstatechange",n),s=setTimeout(r,Xb)})}async exchangeSDP(e){const{webrtcUrl:t,ephemeralKey:s,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 ${s}`,"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 s=JSON.parse(e.data);(t=this.onDataMessage)==null||t.call(this,s)}catch(s){console.warn("[RealtimeSession] Failed to parse data channel message:",s)}},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 Kb=24e3,Zb=`
|
|
883
|
+
`})),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 s=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};s=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 p=s.createView({baseMipLevel:h++,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),d=o.beginRenderPass({colorAttachments:[{view:p,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=p}}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:s,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||s.destroy(),e}}class Gb{constructor(e){this.textureView=null,this.gpuTexture=e}destroy(){this.gpuTexture.destroy(),this.textureView=null,this.gpuTexture=null}}class vu{constructor(e){this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._renderer=e,e.gc.addCollection(this,"_bindGroupHash","hash"),this._managedTextures=new Rt({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"gpuTextureSource"});const t={image:bu,buffer:kb,video:Nb,compressed:Bb};this._uploads={...t,cube:Db(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 s=_u[e.format]||{blockWidth:1,blockHeight:1},r=Math.ceil(e.pixelWidth/s.blockWidth)*s.blockWidth,n=Math.ceil(e.pixelHeight/s.blockHeight)*s.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 Gb(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 Ub(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],s=t==null?void 0:t.gpuTexture;s?(s.width!==e.pixelWidth||s.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 Nt({0:t,1:t.style,2:new gt({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 s=t._gpuData[this._renderer.uid];return s||(this.initSource(t),s=t._gpuData[this._renderer.uid]),s.textureView||(s.textureView=s.gpuTexture.createView({dimension:t.viewDimension})),s.textureView}generateCanvas(e){const t=this._renderer,s=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"}),s.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([s.finish()]),r}getPixels(e){const t=this.generateCanvas(e),s=Yn.getOptimalCanvasAndContext(t.width,t.height),r=s.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 Yn.returnCanvasAndContext(s),{pixels:l,width:n,height:o}}destroy(){this._managedTextures.destroy();for(const e of Object.keys(this._bindGroupHash)){const t=Number(e),s=this._bindGroupHash[t];s==null||s.destroy()}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._gpuSamplers=null,this._bindGroupHash=null}}vu.extension={type:[A.WebGPUSystem],name:"texture"};class xu{constructor(){this._maxTextures=0}contextChange(e){const t=new gt({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 s=Mn({name:"graphics",bits:[rc,oc(this._maxTextures),P_,Bn]});this.shader=new wt({gpuProgram:s,resources:{localUniforms:t}})}execute(e,t){const s=t.context,r=s.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(s),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 p=l.instructions;let d=null;for(let g=0;g<l.instructionSize;g++){const _=p[g];if(_.topology!==d&&(d=_.topology,c.setPipelineFromGeometryProgramAndState(a.geometry,r.gpuProgram,e.state,_.topology)),r.groups[1]=_.bindGroup,!_.gpuBindGroup){const b=_.textures;_.bindGroup=An(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}}xu.extension={type:[A.WebGPUPipesAdaptor],name:"graphics"};class Cu{init(){const e=Mn({name:"mesh",bits:[nr,D_,Bn]});this._shader=new wt({gpuProgram:e,resources:{uTexture:j.EMPTY._source,uSampler:j.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new H}}}})}execute(e,t){const s=e.renderer;let r=t._shader;if(!r)r=this._shader,r.groups[2]=s.texture.getTextureBindGroup(t.texture);else if(!r.gpuProgram){ie("Mesh shader has no gpuProgram",t.shader);return}const n=r.gpuProgram;if(n.autoAssignGlobalUniforms&&(r.groups[0]=s.globalUniforms.bindGroup),n.autoAssignLocalUniforms){const o=e.localUniforms;r.groups[1]=s.renderPipes.uniformBatch.getUniformBindGroup(o,!0)}s.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}Cu.extension={type:[A.WebGPUPipesAdaptor],name:"mesh"};const Fb=[..._o,uu,lu,Ao,cu,ou,vu,pu,mu,gu,fu,au,hu,nu],Lb=[...xh,du],Wb=[th,Cu,xu],Eu=[],Su=[],Tu=[];Q.handleByNamedList(A.WebGPUSystem,Eu),Q.handleByNamedList(A.WebGPUPipes,Su),Q.handleByNamedList(A.WebGPUPipesAdaptor,Tu),Q.add(...Fb,...Lb,...Wb);class Hb extends ni{constructor(){const e={name:"webgpu",type:_t.WEBGPU,systems:Eu,renderPipes:Su,renderPipeAdaptors:Tu};super(e)}}const Vb=Object.freeze(Object.defineProperty({__proto__:null,WebGPURenderer:Hb},Symbol.toStringTag,{value:"Module"}));Q.add(Bf,Df);const Ps=480,yi=480;class zb{constructor(){this.container=null,this.resizeObserver=null,this.mode="floating",this.targetEl=null,this.app=new Ll}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:Ps,height:yi,backgroundAlpha:0,antialias:!0,resolution:window.devicePixelRatio||1,autoDensity:!0}),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:`${Ps}px`,height:`${yi}px`,zIndex:"2147483646",pointerEvents:"none",overflow:"visible"}),document.body.appendChild(this.container));const s=this.app.canvas;return Object.assign(s.style,{width:"100%",height:"100%",display:"block",pointerEvents:"auto"}),this.container.appendChild(s),this.setupResize(),s}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,s=Math.min(Ps,t),r=s/Ps,n=yi*r;this.container&&(this.container.style.width=`${s}px`,this.container.style.height=`${n}px`)}this.app.renderer.resize(Ps,yi)};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 Ps}get stageHeight(){return yi}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 $b(){var i,e;return((e=(i=globalThis.matchMedia)==null?void 0:i.call(globalThis,"(prefers-reduced-motion: reduce)"))==null?void 0:e.matches)??!1}const bi={easeOutCubic:i=>1-Math.pow(1-i,3),easeInCubic:i=>i*i*i,easeOutBack:i=>1+2.70158*Math.pow(i-1,3)+1.70158*Math.pow(i-1,2),easeInOutSine:i=>-(Math.cos(Math.PI*i)-1)/2};function fr(i){const{target:e,props:t,duration:s,easing:r=bi.easeOutCubic,delay:n=0,onComplete:o,ticker:a}=i;if($b()){for(const p of Object.keys(t))e[p]=t[p];return o==null||o(),()=>{}}const l={};for(const p of Object.keys(t))l[p]=e[p];let c=-n,h=!1;const u=p=>{if(h||(c+=p.deltaMS,c<0))return;const d=Math.min(c/s,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 vi=200,Wt=vi*(480/854),Au=280;class jb{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+Wt}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:`${vi}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+Wt}async loadIdleImage(e){const t=j.from(e),s=new Dt(t);s.width=vi,s.height=Wt,s.anchor.set(.5,1),this.idleGroup=new Ve,this.idleGroup.addChild(s),this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+Wt}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+Wt,this.cancelEntrance=fr({target:this.container,props:{y:t},duration:700,easing:bi.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,fr({target:this.container,props:{y:this.stageHeight+Wt},duration:450,easing:bi.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 Ce(-vi/2,-Wt,vi,Wt),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 s=()=>{var l;const r=j.from(e);this.liveSprite=new Dt(r);const n=e.videoWidth||1,o=e.videoHeight||1,a=Au/n;this.liveSprite.width=Au,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,fr({target:this.liveSprite,props:{alpha:1},duration:500,easing:bi.easeInOutSine,ticker:t})};if(e.videoWidth>0&&e.videoHeight>0)s();else{const r=()=>{e.removeEventListener("loadeddata",r),e.removeEventListener("resize",r),s()};e.addEventListener("loadeddata",r),e.addEventListener("resize",r)}}clearLiveVideo(e){this.liveSprite&&fr({target:this.liveSprite,props:{alpha:0},duration:400,easing:bi.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 Xb=[{urls:"stun:stun.l.google.com:19302"}],Yb=3e3,qb="oai-events";class Kb{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:Xb}),this.setupPeerConnectionHandlers();for(const o of this.micStream.getAudioTracks())this.pc.addTrack(o,this.micStream);this.dc=this.pc.createDataChannel(qb),this.setupDataChannelHandlers();const s=await this.pc.createOffer();await this.pc.setLocalDescription(s),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(s){const r=s instanceof Error?s:new Error(String(s));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,s,r,n;const e=(t=this.pc)==null?void 0:t.connectionState;console.log("[RealtimeSession] Connection state:",e),e==="connected"?(this._connected=!0,(s=this.onConnected)==null||s.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 s;const r=()=>{clearTimeout(s);try{t.removeEventListener("icegatheringstatechange",n)}catch{}e()},n=()=>{t.iceGatheringState==="complete"&&r()};t.addEventListener("icegatheringstatechange",n),s=setTimeout(r,Yb)})}async exchangeSDP(e){const{webrtcUrl:t,ephemeralKey:s,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 ${s}`,"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 s=JSON.parse(e.data);(t=this.onDataMessage)==null||t.call(this,s)}catch(s){console.warn("[RealtimeSession] Failed to parse data channel message:",s)}},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 Zb=24e3,Jb=`
|
|
884
884
|
class PcmBufferProcessor extends AudioWorkletProcessor {
|
|
885
885
|
constructor() {
|
|
886
886
|
super()
|
|
@@ -918,12 +918,12 @@ class PcmBufferProcessor extends AudioWorkletProcessor {
|
|
|
918
918
|
}
|
|
919
919
|
|
|
920
920
|
registerProcessor('pcm-buffer-processor', PcmBufferProcessor)
|
|
921
|
-
`;function
|
|
921
|
+
`;function Qb(i){const e=new Int16Array(i.length);for(let t=0;t<i.length;t++){const s=Math.max(-1,Math.min(1,i[t]));e[t]=s<0?s*32768:s*32767}return e}class ev{constructor(){this.onAudioChunk=null,this.audioCtx=null,this.sourceNode=null,this.workletNode=null,this._started=!1,this._paused=!1}get isStarted(){return this._started}get isPaused(){return this._paused}async start(e){if(this._started)return;this.audioCtx=new AudioContext({sampleRate:Zb});const t=new Blob([Jb],{type:"application/javascript"}),s=URL.createObjectURL(t);await this.audioCtx.audioWorklet.addModule(s),URL.revokeObjectURL(s),this.sourceNode=this.audioCtx.createMediaStreamSource(e),this.workletNode=new AudioWorkletNode(this.audioCtx,"pcm-buffer-processor"),this.workletNode.port.onmessage=n=>{var o;if(n.data.type==="chunk"){const a=n.data.samples,l=Qb(a);(o=this.onAudioChunk)==null||o.call(this,new Uint8Array(l.buffer))}},this.sourceNode.connect(this.workletNode);const r=this.audioCtx.createGain();r.gain.value=0,r.connect(this.audioCtx.destination),this.workletNode.connect(r),this._started=!0,this._paused=!1,console.log("[AudioForwarder] Started capturing remote audio at 24kHz")}pause(){var e;!this._started||this._paused||(this._paused=!0,(e=this.workletNode)==null||e.port.postMessage({type:"pause"}),console.log("[AudioForwarder] Paused"))}resume(){var e;!this._started||!this._paused||(this._paused=!1,(e=this.workletNode)==null||e.port.postMessage({type:"resume"}),console.log("[AudioForwarder] Resumed"))}stop(){var e,t,s;if(this._started){try{(e=this.workletNode)==null||e.disconnect()}catch{}try{(t=this.sourceNode)==null||t.disconnect()}catch{}try{(s=this.audioCtx)==null||s.close()}catch{}this.workletNode=null,this.sourceNode=null,this.audioCtx=null,this._started=!1,this._paused=!1,console.log("[AudioForwarder] Stopped")}}}var wo={},xi={},wu;function tv(){if(wu)return xi;wu=1,xi.byteLength=a,xi.toByteArray=c,xi.fromByteArray=p;for(var i=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=0,n=s.length;r<n;++r)i[r]=s[r],e[s.charCodeAt(r)]=r;e[45]=62,e[95]=63;function o(d){var g=d.length;if(g%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var _=d.indexOf("=");_===-1&&(_=g);var b=_===g?0:4-_%4;return[_,b]}function a(d){var g=o(d),_=g[0],b=g[1];return(_+b)*3/4-b}function l(d,g,_){return(g+_)*3/4-_}function c(d){var g,_=o(d),b=_[0],v=_[1],C=new t(l(d,b,v)),E=0,S=v>0?b-4:b,w;for(w=0;w<S;w+=4)g=e[d.charCodeAt(w)]<<18|e[d.charCodeAt(w+1)]<<12|e[d.charCodeAt(w+2)]<<6|e[d.charCodeAt(w+3)],C[E++]=g>>16&255,C[E++]=g>>8&255,C[E++]=g&255;return v===2&&(g=e[d.charCodeAt(w)]<<2|e[d.charCodeAt(w+1)]>>4,C[E++]=g&255),v===1&&(g=e[d.charCodeAt(w)]<<10|e[d.charCodeAt(w+1)]<<4|e[d.charCodeAt(w+2)]>>2,C[E++]=g>>8&255,C[E++]=g&255),C}function h(d){return i[d>>18&63]+i[d>>12&63]+i[d>>6&63]+i[d&63]}function u(d,g,_){for(var b,v=[],C=g;C<_;C+=3)b=(d[C]<<16&16711680)+(d[C+1]<<8&65280)+(d[C+2]&255),v.push(h(b));return v.join("")}function p(d){for(var g,_=d.length,b=_%3,v=[],C=16383,E=0,S=_-b;E<S;E+=C)v.push(u(d,E,E+C>S?S:E+C));return b===1?(g=d[_-1],v.push(i[g>>2]+i[g<<4&63]+"==")):b===2&&(g=(d[_-2]<<8)+d[_-1],v.push(i[g>>10]+i[g>>4&63]+i[g<<2&63]+"=")),v.join("")}return xi}var pr={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */var Iu;function sv(){return Iu||(Iu=1,pr.read=function(i,e,t,s,r){var n,o,a=r*8-s-1,l=(1<<a)-1,c=l>>1,h=-7,u=t?r-1:0,p=t?-1:1,d=i[e+u];for(u+=p,n=d&(1<<-h)-1,d>>=-h,h+=a;h>0;n=n*256+i[e+u],u+=p,h-=8);for(o=n&(1<<-h)-1,n>>=-h,h+=s;h>0;o=o*256+i[e+u],u+=p,h-=8);if(n===0)n=1-c;else{if(n===l)return o?NaN:(d?-1:1)*(1/0);o=o+Math.pow(2,s),n=n-c}return(d?-1:1)*o*Math.pow(2,n-s)},pr.write=function(i,e,t,s,r,n){var o,a,l,c=n*8-r-1,h=(1<<c)-1,u=h>>1,p=r===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=s?0:n-1,g=s?1:-1,_=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=h):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+u>=1?e+=p/l:e+=p*Math.pow(2,1-u),e*l>=2&&(o++,l/=2),o+u>=h?(a=0,o=h):o+u>=1?(a=(e*l-1)*Math.pow(2,r),o=o+u):(a=e*Math.pow(2,u-1)*Math.pow(2,r),o=0));r>=8;i[t+d]=a&255,d+=g,a/=256,r-=8);for(o=o<<r|a,c+=r;c>0;i[t+d]=o&255,d+=g,o/=256,c-=8);i[t+d-g]|=_*128}),pr}/*!
|
|
922
922
|
* The buffer module from node.js, for the browser.
|
|
923
923
|
*
|
|
924
924
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
925
925
|
* @license MIT
|
|
926
|
-
*/var Ru;function sv(){return Ru||(Ru=1,(function(i){const e=ev(),t=tv(),s=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;i.Buffer=a,i.SlowBuffer=C,i.INSPECT_MAX_BYTES=50;const r=2147483647;i.kMaxLength=r,a.TYPED_ARRAY_SUPPORT=n(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function n(){try{const y=new Uint8Array(1),f={foo:function(){return 42}};return Object.setPrototypeOf(f,Uint8Array.prototype),Object.setPrototypeOf(y,f),y.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(y){if(y>r)throw new RangeError('The value "'+y+'" is invalid for option "size"');const f=new Uint8Array(y);return Object.setPrototypeOf(f,a.prototype),f}function a(y,f,m){if(typeof y=="number"){if(typeof f=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(y)}return l(y,f,m)}a.poolSize=8192;function l(y,f,m){if(typeof y=="string")return p(y,f);if(ArrayBuffer.isView(y))return g(y);if(y==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof y);if(tt(y,ArrayBuffer)||y&&tt(y.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(tt(y,SharedArrayBuffer)||y&&tt(y.buffer,SharedArrayBuffer)))return _(y,f,m);if(typeof y=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const x=y.valueOf&&y.valueOf();if(x!=null&&x!==y)return a.from(x,f,m);const T=b(y);if(T)return T;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof y[Symbol.toPrimitive]=="function")return a.from(y[Symbol.toPrimitive]("string"),f,m);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof y)}a.from=function(y,f,m){return l(y,f,m)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function c(y){if(typeof y!="number")throw new TypeError('"size" argument must be of type number');if(y<0)throw new RangeError('The value "'+y+'" is invalid for option "size"')}function h(y,f,m){return c(y),y<=0?o(y):f!==void 0?typeof m=="string"?o(y).fill(f,m):o(y).fill(f):o(y)}a.alloc=function(y,f,m){return h(y,f,m)};function u(y){return c(y),o(y<0?0:v(y)|0)}a.allocUnsafe=function(y){return u(y)},a.allocUnsafeSlow=function(y){return u(y)};function p(y,f){if((typeof f!="string"||f==="")&&(f="utf8"),!a.isEncoding(f))throw new TypeError("Unknown encoding: "+f);const m=E(y,f)|0;let x=o(m);const T=x.write(y,f);return T!==m&&(x=x.slice(0,T)),x}function d(y){const f=y.length<0?0:v(y.length)|0,m=o(f);for(let x=0;x<f;x+=1)m[x]=y[x]&255;return m}function g(y){if(tt(y,Uint8Array)){const f=new Uint8Array(y);return _(f.buffer,f.byteOffset,f.byteLength)}return d(y)}function _(y,f,m){if(f<0||y.byteLength<f)throw new RangeError('"offset" is outside of buffer bounds');if(y.byteLength<f+(m||0))throw new RangeError('"length" is outside of buffer bounds');let x;return f===void 0&&m===void 0?x=new Uint8Array(y):m===void 0?x=new Uint8Array(y,f):x=new Uint8Array(y,f,m),Object.setPrototypeOf(x,a.prototype),x}function b(y){if(a.isBuffer(y)){const f=v(y.length)|0,m=o(f);return m.length===0||y.copy(m,0,0,f),m}if(y.length!==void 0)return typeof y.length!="number"||zs(y.length)?o(0):d(y);if(y.type==="Buffer"&&Array.isArray(y.data))return d(y.data)}function v(y){if(y>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return y|0}function C(y){return+y!=y&&(y=0),a.alloc(+y)}a.isBuffer=function(f){return f!=null&&f._isBuffer===!0&&f!==a.prototype},a.compare=function(f,m){if(tt(f,Uint8Array)&&(f=a.from(f,f.offset,f.byteLength)),tt(m,Uint8Array)&&(m=a.from(m,m.offset,m.byteLength)),!a.isBuffer(f)||!a.isBuffer(m))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(f===m)return 0;let x=f.length,T=m.length;for(let I=0,P=Math.min(x,T);I<P;++I)if(f[I]!==m[I]){x=f[I],T=m[I];break}return x<T?-1:T<x?1:0},a.isEncoding=function(f){switch(String(f).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(f,m){if(!Array.isArray(f))throw new TypeError('"list" argument must be an Array of Buffers');if(f.length===0)return a.alloc(0);let x;if(m===void 0)for(m=0,x=0;x<f.length;++x)m+=f[x].length;const T=a.allocUnsafe(m);let I=0;for(x=0;x<f.length;++x){let P=f[x];if(tt(P,Uint8Array))I+P.length>T.length?(a.isBuffer(P)||(P=a.from(P)),P.copy(T,I)):Uint8Array.prototype.set.call(T,P,I);else if(a.isBuffer(P))P.copy(T,I);else throw new TypeError('"list" argument must be an Array of Buffers');I+=P.length}return T};function E(y,f){if(a.isBuffer(y))return y.length;if(ArrayBuffer.isView(y)||tt(y,ArrayBuffer))return y.byteLength;if(typeof y!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof y);const m=y.length,x=arguments.length>2&&arguments[2]===!0;if(!x&&m===0)return 0;let T=!1;for(;;)switch(f){case"ascii":case"latin1":case"binary":return m;case"utf8":case"utf-8":return Ct(y).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return m*2;case"hex":return m>>>1;case"base64":return Bt(y).length;default:if(T)return x?-1:Ct(y).length;f=(""+f).toLowerCase(),T=!0}}a.byteLength=E;function S(y,f,m){let x=!1;if((f===void 0||f<0)&&(f=0),f>this.length||((m===void 0||m>this.length)&&(m=this.length),m<=0)||(m>>>=0,f>>>=0,m<=f))return"";for(y||(y="utf8");;)switch(y){case"hex":return N(this,f,m);case"utf8":case"utf-8":return z(this,f,m);case"ascii":return U(this,f,m);case"latin1":case"binary":return q(this,f,m);case"base64":return X(this,f,m);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return K(this,f,m);default:if(x)throw new TypeError("Unknown encoding: "+y);y=(y+"").toLowerCase(),x=!0}}a.prototype._isBuffer=!0;function w(y,f,m){const x=y[f];y[f]=y[m],y[m]=x}a.prototype.swap16=function(){const f=this.length;if(f%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let m=0;m<f;m+=2)w(this,m,m+1);return this},a.prototype.swap32=function(){const f=this.length;if(f%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let m=0;m<f;m+=4)w(this,m,m+3),w(this,m+1,m+2);return this},a.prototype.swap64=function(){const f=this.length;if(f%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let m=0;m<f;m+=8)w(this,m,m+7),w(this,m+1,m+6),w(this,m+2,m+5),w(this,m+3,m+4);return this},a.prototype.toString=function(){const f=this.length;return f===0?"":arguments.length===0?z(this,0,f):S.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(f){if(!a.isBuffer(f))throw new TypeError("Argument must be a Buffer");return this===f?!0:a.compare(this,f)===0},a.prototype.inspect=function(){let f="";const m=i.INSPECT_MAX_BYTES;return f=this.toString("hex",0,m).replace(/(.{2})/g,"$1 ").trim(),this.length>m&&(f+=" ... "),"<Buffer "+f+">"},s&&(a.prototype[s]=a.prototype.inspect),a.prototype.compare=function(f,m,x,T,I){if(tt(f,Uint8Array)&&(f=a.from(f,f.offset,f.byteLength)),!a.isBuffer(f))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof f);if(m===void 0&&(m=0),x===void 0&&(x=f?f.length:0),T===void 0&&(T=0),I===void 0&&(I=this.length),m<0||x>f.length||T<0||I>this.length)throw new RangeError("out of range index");if(T>=I&&m>=x)return 0;if(T>=I)return-1;if(m>=x)return 1;if(m>>>=0,x>>>=0,T>>>=0,I>>>=0,this===f)return 0;let P=I-T,J=x-m;const Re=Math.min(P,J),Te=this.slice(T,I),Me=f.slice(m,x);for(let _e=0;_e<Re;++_e)if(Te[_e]!==Me[_e]){P=Te[_e],J=Me[_e];break}return P<J?-1:J<P?1:0};function R(y,f,m,x,T){if(y.length===0)return-1;if(typeof m=="string"?(x=m,m=0):m>2147483647?m=2147483647:m<-2147483648&&(m=-2147483648),m=+m,zs(m)&&(m=T?0:y.length-1),m<0&&(m=y.length+m),m>=y.length){if(T)return-1;m=y.length-1}else if(m<0)if(T)m=0;else return-1;if(typeof f=="string"&&(f=a.from(f,x)),a.isBuffer(f))return f.length===0?-1:M(y,f,m,x,T);if(typeof f=="number")return f=f&255,typeof Uint8Array.prototype.indexOf=="function"?T?Uint8Array.prototype.indexOf.call(y,f,m):Uint8Array.prototype.lastIndexOf.call(y,f,m):M(y,[f],m,x,T);throw new TypeError("val must be string, number or Buffer")}function M(y,f,m,x,T){let I=1,P=y.length,J=f.length;if(x!==void 0&&(x=String(x).toLowerCase(),x==="ucs2"||x==="ucs-2"||x==="utf16le"||x==="utf-16le")){if(y.length<2||f.length<2)return-1;I=2,P/=2,J/=2,m/=2}function Re(Me,_e){return I===1?Me[_e]:Me.readUInt16BE(_e*I)}let Te;if(T){let Me=-1;for(Te=m;Te<P;Te++)if(Re(y,Te)===Re(f,Me===-1?0:Te-Me)){if(Me===-1&&(Me=Te),Te-Me+1===J)return Me*I}else Me!==-1&&(Te-=Te-Me),Me=-1}else for(m+J>P&&(m=P-J),Te=m;Te>=0;Te--){let Me=!0;for(let _e=0;_e<J;_e++)if(Re(y,Te+_e)!==Re(f,_e)){Me=!1;break}if(Me)return Te}return-1}a.prototype.includes=function(f,m,x){return this.indexOf(f,m,x)!==-1},a.prototype.indexOf=function(f,m,x){return R(this,f,m,x,!0)},a.prototype.lastIndexOf=function(f,m,x){return R(this,f,m,x,!1)};function D(y,f,m,x){m=Number(m)||0;const T=y.length-m;x?(x=Number(x),x>T&&(x=T)):x=T;const I=f.length;x>I/2&&(x=I/2);let P;for(P=0;P<x;++P){const J=parseInt(f.substr(P*2,2),16);if(zs(J))return P;y[m+P]=J}return P}function G(y,f,m,x){return dt(Ct(f,y.length-m),y,m,x)}function k(y,f,m,x){return dt(hs(f),y,m,x)}function O(y,f,m,x){return dt(Bt(f),y,m,x)}function V(y,f,m,x){return dt(Vs(f,y.length-m),y,m,x)}a.prototype.write=function(f,m,x,T){if(m===void 0)T="utf8",x=this.length,m=0;else if(x===void 0&&typeof m=="string")T=m,x=this.length,m=0;else if(isFinite(m))m=m>>>0,isFinite(x)?(x=x>>>0,T===void 0&&(T="utf8")):(T=x,x=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const I=this.length-m;if((x===void 0||x>I)&&(x=I),f.length>0&&(x<0||m<0)||m>this.length)throw new RangeError("Attempt to write outside buffer bounds");T||(T="utf8");let P=!1;for(;;)switch(T){case"hex":return D(this,f,m,x);case"utf8":case"utf-8":return G(this,f,m,x);case"ascii":case"latin1":case"binary":return k(this,f,m,x);case"base64":return O(this,f,m,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,f,m,x);default:if(P)throw new TypeError("Unknown encoding: "+T);T=(""+T).toLowerCase(),P=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function X(y,f,m){return f===0&&m===y.length?e.fromByteArray(y):e.fromByteArray(y.slice(f,m))}function z(y,f,m){m=Math.min(y.length,m);const x=[];let T=f;for(;T<m;){const I=y[T];let P=null,J=I>239?4:I>223?3:I>191?2:1;if(T+J<=m){let Re,Te,Me,_e;switch(J){case 1:I<128&&(P=I);break;case 2:Re=y[T+1],(Re&192)===128&&(_e=(I&31)<<6|Re&63,_e>127&&(P=_e));break;case 3:Re=y[T+1],Te=y[T+2],(Re&192)===128&&(Te&192)===128&&(_e=(I&15)<<12|(Re&63)<<6|Te&63,_e>2047&&(_e<55296||_e>57343)&&(P=_e));break;case 4:Re=y[T+1],Te=y[T+2],Me=y[T+3],(Re&192)===128&&(Te&192)===128&&(Me&192)===128&&(_e=(I&15)<<18|(Re&63)<<12|(Te&63)<<6|Me&63,_e>65535&&_e<1114112&&(P=_e))}}P===null?(P=65533,J=1):P>65535&&(P-=65536,x.push(P>>>10&1023|55296),P=56320|P&1023),x.push(P),T+=J}return B(x)}const de=4096;function B(y){const f=y.length;if(f<=de)return String.fromCharCode.apply(String,y);let m="",x=0;for(;x<f;)m+=String.fromCharCode.apply(String,y.slice(x,x+=de));return m}function U(y,f,m){let x="";m=Math.min(y.length,m);for(let T=f;T<m;++T)x+=String.fromCharCode(y[T]&127);return x}function q(y,f,m){let x="";m=Math.min(y.length,m);for(let T=f;T<m;++T)x+=String.fromCharCode(y[T]);return x}function N(y,f,m){const x=y.length;(!f||f<0)&&(f=0),(!m||m<0||m>x)&&(m=x);let T="";for(let I=f;I<m;++I)T+=Mr[y[I]];return T}function K(y,f,m){const x=y.slice(f,m);let T="";for(let I=0;I<x.length-1;I+=2)T+=String.fromCharCode(x[I]+x[I+1]*256);return T}a.prototype.slice=function(f,m){const x=this.length;f=~~f,m=m===void 0?x:~~m,f<0?(f+=x,f<0&&(f=0)):f>x&&(f=x),m<0?(m+=x,m<0&&(m=0)):m>x&&(m=x),m<f&&(m=f);const T=this.subarray(f,m);return Object.setPrototypeOf(T,a.prototype),T};function Z(y,f,m){if(y%1!==0||y<0)throw new RangeError("offset is not uint");if(y+f>m)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(f,m,x){f=f>>>0,m=m>>>0,x||Z(f,m,this.length);let T=this[f],I=1,P=0;for(;++P<m&&(I*=256);)T+=this[f+P]*I;return T},a.prototype.readUintBE=a.prototype.readUIntBE=function(f,m,x){f=f>>>0,m=m>>>0,x||Z(f,m,this.length);let T=this[f+--m],I=1;for(;m>0&&(I*=256);)T+=this[f+--m]*I;return T},a.prototype.readUint8=a.prototype.readUInt8=function(f,m){return f=f>>>0,m||Z(f,1,this.length),this[f]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(f,m){return f=f>>>0,m||Z(f,2,this.length),this[f]|this[f+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(f,m){return f=f>>>0,m||Z(f,2,this.length),this[f]<<8|this[f+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(f,m){return f=f>>>0,m||Z(f,4,this.length),(this[f]|this[f+1]<<8|this[f+2]<<16)+this[f+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(f,m){return f=f>>>0,m||Z(f,4,this.length),this[f]*16777216+(this[f+1]<<16|this[f+2]<<8|this[f+3])},a.prototype.readBigUInt64LE=ft(function(f){f=f>>>0,we(f,"offset");const m=this[f],x=this[f+7];(m===void 0||x===void 0)&&ce(f,this.length-8);const T=m+this[++f]*2**8+this[++f]*2**16+this[++f]*2**24,I=this[++f]+this[++f]*2**8+this[++f]*2**16+x*2**24;return BigInt(T)+(BigInt(I)<<BigInt(32))}),a.prototype.readBigUInt64BE=ft(function(f){f=f>>>0,we(f,"offset");const m=this[f],x=this[f+7];(m===void 0||x===void 0)&&ce(f,this.length-8);const T=m*2**24+this[++f]*2**16+this[++f]*2**8+this[++f],I=this[++f]*2**24+this[++f]*2**16+this[++f]*2**8+x;return(BigInt(T)<<BigInt(32))+BigInt(I)}),a.prototype.readIntLE=function(f,m,x){f=f>>>0,m=m>>>0,x||Z(f,m,this.length);let T=this[f],I=1,P=0;for(;++P<m&&(I*=256);)T+=this[f+P]*I;return I*=128,T>=I&&(T-=Math.pow(2,8*m)),T},a.prototype.readIntBE=function(f,m,x){f=f>>>0,m=m>>>0,x||Z(f,m,this.length);let T=m,I=1,P=this[f+--T];for(;T>0&&(I*=256);)P+=this[f+--T]*I;return I*=128,P>=I&&(P-=Math.pow(2,8*m)),P},a.prototype.readInt8=function(f,m){return f=f>>>0,m||Z(f,1,this.length),this[f]&128?(255-this[f]+1)*-1:this[f]},a.prototype.readInt16LE=function(f,m){f=f>>>0,m||Z(f,2,this.length);const x=this[f]|this[f+1]<<8;return x&32768?x|4294901760:x},a.prototype.readInt16BE=function(f,m){f=f>>>0,m||Z(f,2,this.length);const x=this[f+1]|this[f]<<8;return x&32768?x|4294901760:x},a.prototype.readInt32LE=function(f,m){return f=f>>>0,m||Z(f,4,this.length),this[f]|this[f+1]<<8|this[f+2]<<16|this[f+3]<<24},a.prototype.readInt32BE=function(f,m){return f=f>>>0,m||Z(f,4,this.length),this[f]<<24|this[f+1]<<16|this[f+2]<<8|this[f+3]},a.prototype.readBigInt64LE=ft(function(f){f=f>>>0,we(f,"offset");const m=this[f],x=this[f+7];(m===void 0||x===void 0)&&ce(f,this.length-8);const T=this[f+4]+this[f+5]*2**8+this[f+6]*2**16+(x<<24);return(BigInt(T)<<BigInt(32))+BigInt(m+this[++f]*2**8+this[++f]*2**16+this[++f]*2**24)}),a.prototype.readBigInt64BE=ft(function(f){f=f>>>0,we(f,"offset");const m=this[f],x=this[f+7];(m===void 0||x===void 0)&&ce(f,this.length-8);const T=(m<<24)+this[++f]*2**16+this[++f]*2**8+this[++f];return(BigInt(T)<<BigInt(32))+BigInt(this[++f]*2**24+this[++f]*2**16+this[++f]*2**8+x)}),a.prototype.readFloatLE=function(f,m){return f=f>>>0,m||Z(f,4,this.length),t.read(this,f,!0,23,4)},a.prototype.readFloatBE=function(f,m){return f=f>>>0,m||Z(f,4,this.length),t.read(this,f,!1,23,4)},a.prototype.readDoubleLE=function(f,m){return f=f>>>0,m||Z(f,8,this.length),t.read(this,f,!0,52,8)},a.prototype.readDoubleBE=function(f,m){return f=f>>>0,m||Z(f,8,this.length),t.read(this,f,!1,52,8)};function $(y,f,m,x,T,I){if(!a.isBuffer(y))throw new TypeError('"buffer" argument must be a Buffer instance');if(f>T||f<I)throw new RangeError('"value" argument is out of bounds');if(m+x>y.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(f,m,x,T){if(f=+f,m=m>>>0,x=x>>>0,!T){const J=Math.pow(2,8*x)-1;$(this,f,m,x,J,0)}let I=1,P=0;for(this[m]=f&255;++P<x&&(I*=256);)this[m+P]=f/I&255;return m+x},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(f,m,x,T){if(f=+f,m=m>>>0,x=x>>>0,!T){const J=Math.pow(2,8*x)-1;$(this,f,m,x,J,0)}let I=x-1,P=1;for(this[m+I]=f&255;--I>=0&&(P*=256);)this[m+I]=f/P&255;return m+x},a.prototype.writeUint8=a.prototype.writeUInt8=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,1,255,0),this[m]=f&255,m+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,2,65535,0),this[m]=f&255,this[m+1]=f>>>8,m+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,2,65535,0),this[m]=f>>>8,this[m+1]=f&255,m+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,4,4294967295,0),this[m+3]=f>>>24,this[m+2]=f>>>16,this[m+1]=f>>>8,this[m]=f&255,m+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,4,4294967295,0),this[m]=f>>>24,this[m+1]=f>>>16,this[m+2]=f>>>8,this[m+3]=f&255,m+4};function ae(y,f,m,x,T){se(f,x,T,y,m,7);let I=Number(f&BigInt(4294967295));y[m++]=I,I=I>>8,y[m++]=I,I=I>>8,y[m++]=I,I=I>>8,y[m++]=I;let P=Number(f>>BigInt(32)&BigInt(4294967295));return y[m++]=P,P=P>>8,y[m++]=P,P=P>>8,y[m++]=P,P=P>>8,y[m++]=P,m}function xe(y,f,m,x,T){se(f,x,T,y,m,7);let I=Number(f&BigInt(4294967295));y[m+7]=I,I=I>>8,y[m+6]=I,I=I>>8,y[m+5]=I,I=I>>8,y[m+4]=I;let P=Number(f>>BigInt(32)&BigInt(4294967295));return y[m+3]=P,P=P>>8,y[m+2]=P,P=P>>8,y[m+1]=P,P=P>>8,y[m]=P,m+8}a.prototype.writeBigUInt64LE=ft(function(f,m=0){return ae(this,f,m,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=ft(function(f,m=0){return xe(this,f,m,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(f,m,x,T){if(f=+f,m=m>>>0,!T){const Re=Math.pow(2,8*x-1);$(this,f,m,x,Re-1,-Re)}let I=0,P=1,J=0;for(this[m]=f&255;++I<x&&(P*=256);)f<0&&J===0&&this[m+I-1]!==0&&(J=1),this[m+I]=(f/P>>0)-J&255;return m+x},a.prototype.writeIntBE=function(f,m,x,T){if(f=+f,m=m>>>0,!T){const Re=Math.pow(2,8*x-1);$(this,f,m,x,Re-1,-Re)}let I=x-1,P=1,J=0;for(this[m+I]=f&255;--I>=0&&(P*=256);)f<0&&J===0&&this[m+I+1]!==0&&(J=1),this[m+I]=(f/P>>0)-J&255;return m+x},a.prototype.writeInt8=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,1,127,-128),f<0&&(f=255+f+1),this[m]=f&255,m+1},a.prototype.writeInt16LE=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,2,32767,-32768),this[m]=f&255,this[m+1]=f>>>8,m+2},a.prototype.writeInt16BE=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,2,32767,-32768),this[m]=f>>>8,this[m+1]=f&255,m+2},a.prototype.writeInt32LE=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,4,2147483647,-2147483648),this[m]=f&255,this[m+1]=f>>>8,this[m+2]=f>>>16,this[m+3]=f>>>24,m+4},a.prototype.writeInt32BE=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,4,2147483647,-2147483648),f<0&&(f=4294967295+f+1),this[m]=f>>>24,this[m+1]=f>>>16,this[m+2]=f>>>8,this[m+3]=f&255,m+4},a.prototype.writeBigInt64LE=ft(function(f,m=0){return ae(this,f,m,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=ft(function(f,m=0){return xe(this,f,m,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Se(y,f,m,x,T,I){if(m+x>y.length)throw new RangeError("Index out of range");if(m<0)throw new RangeError("Index out of range")}function F(y,f,m,x,T){return f=+f,m=m>>>0,T||Se(y,f,m,4),t.write(y,f,m,x,23,4),m+4}a.prototype.writeFloatLE=function(f,m,x){return F(this,f,m,!0,x)},a.prototype.writeFloatBE=function(f,m,x){return F(this,f,m,!1,x)};function fe(y,f,m,x,T){return f=+f,m=m>>>0,T||Se(y,f,m,8),t.write(y,f,m,x,52,8),m+8}a.prototype.writeDoubleLE=function(f,m,x){return fe(this,f,m,!0,x)},a.prototype.writeDoubleBE=function(f,m,x){return fe(this,f,m,!1,x)},a.prototype.copy=function(f,m,x,T){if(!a.isBuffer(f))throw new TypeError("argument should be a Buffer");if(x||(x=0),!T&&T!==0&&(T=this.length),m>=f.length&&(m=f.length),m||(m=0),T>0&&T<x&&(T=x),T===x||f.length===0||this.length===0)return 0;if(m<0)throw new RangeError("targetStart out of bounds");if(x<0||x>=this.length)throw new RangeError("Index out of range");if(T<0)throw new RangeError("sourceEnd out of bounds");T>this.length&&(T=this.length),f.length-m<T-x&&(T=f.length-m+x);const I=T-x;return this===f&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(m,x,T):Uint8Array.prototype.set.call(f,this.subarray(x,T),m),I},a.prototype.fill=function(f,m,x,T){if(typeof f=="string"){if(typeof m=="string"?(T=m,m=0,x=this.length):typeof x=="string"&&(T=x,x=this.length),T!==void 0&&typeof T!="string")throw new TypeError("encoding must be a string");if(typeof T=="string"&&!a.isEncoding(T))throw new TypeError("Unknown encoding: "+T);if(f.length===1){const P=f.charCodeAt(0);(T==="utf8"&&P<128||T==="latin1")&&(f=P)}}else typeof f=="number"?f=f&255:typeof f=="boolean"&&(f=Number(f));if(m<0||this.length<m||this.length<x)throw new RangeError("Out of range index");if(x<=m)return this;m=m>>>0,x=x===void 0?this.length:x>>>0,f||(f=0);let I;if(typeof f=="number")for(I=m;I<x;++I)this[I]=f;else{const P=a.isBuffer(f)?f:a.from(f,T),J=P.length;if(J===0)throw new TypeError('The value "'+f+'" is invalid for argument "value"');for(I=0;I<x-m;++I)this[I+m]=P[I%J]}return this};const le={};function L(y,f,m){le[y]=class extends m{constructor(){super(),Object.defineProperty(this,"message",{value:f.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${y}]`,this.stack,delete this.name}get code(){return y}set code(T){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:T,writable:!0})}toString(){return`${this.name} [${y}]: ${this.message}`}}}L("ERR_BUFFER_OUT_OF_BOUNDS",function(y){return y?`${y} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),L("ERR_INVALID_ARG_TYPE",function(y,f){return`The "${y}" argument must be of type number. Received type ${typeof f}`},TypeError),L("ERR_OUT_OF_RANGE",function(y,f,m){let x=`The value of "${y}" is out of range.`,T=m;return Number.isInteger(m)&&Math.abs(m)>2**32?T=me(String(m)):typeof m=="bigint"&&(T=String(m),(m>BigInt(2)**BigInt(32)||m<-(BigInt(2)**BigInt(32)))&&(T=me(T)),T+="n"),x+=` It must be ${f}. Received ${T}`,x},RangeError);function me(y){let f="",m=y.length;const x=y[0]==="-"?1:0;for(;m>=x+4;m-=3)f=`_${y.slice(m-3,m)}${f}`;return`${y.slice(0,m)}${f}`}function Y(y,f,m){we(f,"offset"),(y[f]===void 0||y[f+m]===void 0)&&ce(f,y.length-(m+1))}function se(y,f,m,x,T,I){if(y>m||y<f){const P=typeof f=="bigint"?"n":"";let J;throw f===0||f===BigInt(0)?J=`>= 0${P} and < 2${P} ** ${(I+1)*8}${P}`:J=`>= -(2${P} ** ${(I+1)*8-1}${P}) and < 2 ** ${(I+1)*8-1}${P}`,new le.ERR_OUT_OF_RANGE("value",J,y)}Y(x,T,I)}function we(y,f){if(typeof y!="number")throw new le.ERR_INVALID_ARG_TYPE(f,"number",y)}function ce(y,f,m){throw Math.floor(y)!==y?(we(y,m),new le.ERR_OUT_OF_RANGE("offset","an integer",y)):f<0?new le.ERR_BUFFER_OUT_OF_BOUNDS:new le.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${f}`,y)}const He=/[^+/0-9A-Za-z-_]/g;function Zt(y){if(y=y.split("=")[0],y=y.trim().replace(He,""),y.length<2)return"";for(;y.length%4!==0;)y=y+"=";return y}function Ct(y,f){f=f||1/0;let m;const x=y.length;let T=null;const I=[];for(let P=0;P<x;++P){if(m=y.charCodeAt(P),m>55295&&m<57344){if(!T){if(m>56319){(f-=3)>-1&&I.push(239,191,189);continue}else if(P+1===x){(f-=3)>-1&&I.push(239,191,189);continue}T=m;continue}if(m<56320){(f-=3)>-1&&I.push(239,191,189),T=m;continue}m=(T-55296<<10|m-56320)+65536}else T&&(f-=3)>-1&&I.push(239,191,189);if(T=null,m<128){if((f-=1)<0)break;I.push(m)}else if(m<2048){if((f-=2)<0)break;I.push(m>>6|192,m&63|128)}else if(m<65536){if((f-=3)<0)break;I.push(m>>12|224,m>>6&63|128,m&63|128)}else if(m<1114112){if((f-=4)<0)break;I.push(m>>18|240,m>>12&63|128,m>>6&63|128,m&63|128)}else throw new Error("Invalid code point")}return I}function hs(y){const f=[];for(let m=0;m<y.length;++m)f.push(y.charCodeAt(m)&255);return f}function Vs(y,f){let m,x,T;const I=[];for(let P=0;P<y.length&&!((f-=2)<0);++P)m=y.charCodeAt(P),x=m>>8,T=m%256,I.push(T),I.push(x);return I}function Bt(y){return e.toByteArray(Zt(y))}function dt(y,f,m,x){let T;for(T=0;T<x&&!(T+m>=f.length||T>=y.length);++T)f[T+m]=y[T];return T}function tt(y,f){return y instanceof f||y!=null&&y.constructor!=null&&y.constructor.name!=null&&y.constructor.name===f.name}function zs(y){return y!==y}const Mr=(function(){const y="0123456789abcdef",f=new Array(256);for(let m=0;m<16;++m){const x=m*16;for(let T=0;T<16;++T)f[x+T]=y[m]+y[T]}return f})();function ft(y){return typeof BigInt>"u"?Pr:y}function Pr(){throw new Error("BigInt not supported")}})(wo)),wo}var iv=sv();const rv="https://api.anam.ai",nv="/v1",Mu={client:"js-sdk",version:"4.12.0"};var ov=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};const Pu="https://api.anam.ai",Io="/v1";var kt;(function(i){i.CLIENT_METRIC_MEASUREMENT_ERROR="client_error",i.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED="client_connection_closed",i.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED="client_connection_established",i.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",i.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success"})(kt||(kt={}));let Ro=Pu,ku=Io,Ht,Ou=!1;const av=(i,e=Io)=>{Ro=i,ku=e},lv=i=>{Ht=i},cv=i=>{Ou=i};let Vt={sessionId:null,organizationId:null,attemptCorrelationId:null};const ks=i=>{Vt=Object.assign(Object.assign({},Vt),i)},as=(i,e,t)=>ov(void 0,void 0,void 0,function*(){if(!Ou)try{const s=Object.assign(Object.assign({},Mu),t);Vt.sessionId&&(s.sessionId=Vt.sessionId),Vt.organizationId&&(s.organizationId=Vt.organizationId),Vt.attemptCorrelationId&&(s.attemptCorrelationId=Vt.attemptCorrelationId);const r=`${ku}/metrics/client`;let n,o={"Content-Type":"application/json"};Ht!=null&&Ht.enabled&&(Ht!=null&&Ht.baseUrl)?(n=`${Ht.baseUrl}${r}`,o["X-Anam-Target-Url"]=`${Ro}${r}`):n=`${Ro}${r}`,yield fetch(n,{method:"POST",headers:o,body:JSON.stringify({name:i,value:e,tags:s})})}catch(s){console.error("Failed to send error metric:",s)}}),hv=(i,e="console")=>{var t,s,r;const n={};i.forEach(u=>{n[u.type]||(n[u.type]=[]),n[u.type].push(u)});const o={issues:[]},a=((t=n["inbound-rtp"])===null||t===void 0?void 0:t.filter(u=>u.kind==="video"))||[];a.length>0&&(o.personaVideoStream=[],a.forEach(u=>{var p,d,g,_,b;const v={framesReceived:(p=u.framesReceived)!==null&&p!==void 0?p:"unknown",framesDropped:(d=u.framesDropped)!==null&&d!==void 0?d:"unknown",framesPerSecond:(g=u.framesPerSecond)!==null&&g!==void 0?g:"unknown",packetsReceived:(_=u.packetsReceived)!==null&&_!==void 0?_:"unknown",packetsLost:(b=u.packetsLost)!==null&&b!==void 0?b:"unknown",resolution:u.frameWidth&&u.frameHeight?`${u.frameWidth}x${u.frameHeight}`:void 0,jitter:u.jitter!==void 0?u.jitter:void 0};o.personaVideoStream.push(v)}));const l=((s=n["inbound-rtp"])===null||s===void 0?void 0:s.filter(u=>u.kind==="audio"))||[];l.length>0&&(o.personaAudioStream=[],l.forEach(u=>{var p,d,g;const _={packetsReceived:(p=u.packetsReceived)!==null&&p!==void 0?p:"unknown",packetsLost:(d=u.packetsLost)!==null&&d!==void 0?d:"unknown",audioLevel:(g=u.audioLevel)!==null&&g!==void 0?g:"unknown",jitter:u.jitter!==void 0?u.jitter:void 0,totalAudioEnergy:u.totalAudioEnergy!==void 0?u.totalAudioEnergy:void 0};o.personaAudioStream.push(_)}));const c=((r=n["outbound-rtp"])===null||r===void 0?void 0:r.filter(u=>u.kind==="audio"))||[];c.length>0&&(o.userAudioInput=[],c.forEach(u=>{var p,d;const g={packetsSent:(p=u.packetsSent)!==null&&p!==void 0?p:"unknown",retransmittedPackets:(d=u.retransmittedPacketsSent)!==null&&d!==void 0?d:void 0,avgPacketSendDelay:u.totalPacketSendDelay!==void 0?u.totalPacketSendDelay/(u.packetsSent||1)*1e3:void 0};o.userAudioInput.push(g)})),n.codec&&(o.codecs=[],n.codec.forEach(u=>{const p={status:u.payloadType?"Active":"Available",mimeType:u.mimeType||"Unknown",payloadType:u.payloadType||"N/A",clockRate:u.clockRate||void 0,channels:u.channels||void 0};o.codecs.push(p)})),n.transport&&(o.transportLayer=[],n.transport.forEach(u=>{const p={dtlsState:u.dtlsState||"unknown",iceState:u.iceState||"unknown",bytesSent:u.bytesSent||void 0,bytesReceived:u.bytesReceived||void 0};o.transportLayer.push(p)}));const h=[];if(a.forEach(u=>{typeof u.framesDropped=="number"&&u.framesDropped>0&&h.push(`Video: ${u.framesDropped} frames dropped`),typeof u.packetsLost=="number"&&u.packetsLost>0&&h.push(`Video: ${u.packetsLost} packets lost`),typeof u.framesPerSecond=="number"&&u.framesPerSecond<23&&h.push(`Video: Low frame rate (${u.framesPerSecond} fps)`)}),l.forEach(u=>{typeof u.packetsLost=="number"&&u.packetsLost>0&&h.push(`Audio: ${u.packetsLost} packets lost`),typeof u.jitter=="number"&&u.jitter>.1&&h.push(`Audio: High jitter (${(u.jitter*1e3).toFixed(1)}ms)`)}),o.issues=h,e==="json")return o;console.group("📊 WebRTC Session Statistics Report"),o.personaVideoStream&&o.personaVideoStream.length>0&&(console.group("📹 Persona Video Stream (Inbound)"),o.personaVideoStream.forEach(u=>{console.log(`Frames Received: ${u.framesReceived}`),console.log(`Frames Dropped: ${u.framesDropped}`),console.log(`Frames Per Second: ${u.framesPerSecond}`),console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),u.resolution&&console.log(`Resolution: ${u.resolution}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`)}),console.groupEnd()),o.personaAudioStream&&o.personaAudioStream.length>0&&(console.group("🔊 Persona Audio Stream (Inbound)"),o.personaAudioStream.forEach(u=>{console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),console.log(`Audio Level: ${u.audioLevel}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`),u.totalAudioEnergy!==void 0&&console.log(`Total Audio Energy: ${u.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),o.userAudioInput&&o.userAudioInput.length>0&&(console.group("🎤 User Audio Input (Outbound)"),o.userAudioInput.forEach(u=>{console.log(`Packets Sent: ${typeof u.packetsSent=="number"?u.packetsSent.toLocaleString():u.packetsSent}`),u.retransmittedPackets&&console.log(`Retransmitted Packets: ${u.retransmittedPackets}`),u.avgPacketSendDelay!==void 0&&console.log(`Avg Packet Send Delay: ${u.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),o.codecs&&o.codecs.length>0&&(console.group("🔧 Codecs Used"),o.codecs.forEach(u=>{console.log(`${u.status} ${u.mimeType} - Payload Type: ${u.payloadType}`),u.clockRate&&console.log(` Clock Rate: ${u.clockRate}Hz`),u.channels&&console.log(` Channels: ${u.channels}`)}),console.groupEnd()),o.transportLayer&&o.transportLayer.length>0&&(console.group("🚚 Transport Layer"),o.transportLayer.forEach(u=>{console.log(`DTLS State: ${u.dtlsState}`),console.log(`ICE State: ${u.iceState}`),(u.bytesReceived||u.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(u.bytesSent||0).toLocaleString()}, Received: ${(u.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),o.issues.length>0?(console.group("⚠️ Potential Issues Detected"),o.issues.forEach(u=>console.warn(u)),console.groupEnd()):console.log("✅ No significant issues detected"),console.groupEnd()};var ze;(function(i){i.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED="CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED",i.CLIENT_ERROR_CODE_SPEND_CAP_REACHED="CLIENT_ERROR_CODE_SPEND_CAP_REACHED",i.CLIENT_ERROR_CODE_VALIDATION_ERROR="CLIENT_ERROR_CODE_VALIDATION_ERROR",i.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR="CLIENT_ERROR_CODE_AUTHENTICATION_ERROR",i.CLIENT_ERROR_CODE_SERVER_ERROR="CLIENT_ERROR_CODE_SERVER_ERROR",i.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED="CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED",i.CLIENT_ERROR_CODE_SERVICE_BUSY="CLIENT_ERROR_CODE_SERVICE_BUSY",i.CLIENT_ERROR_CODE_NO_PLAN_FOUND="CLIENT_ERROR_CODE_NO_PLAN_FOUND",i.CLIENT_ERROR_CODE_UNKNOWN_ERROR="CLIENT_ERROR_CODE_UNKNOWN_ERROR",i.CLIENT_ERROR_CODE_CONFIGURATION_ERROR="CLIENT_ERROR_CODE_CONFIGURATION_ERROR"})(ze||(ze={}));class Ne extends Error{constructor(e,t,s=500,r){super(e),this.name="ClientError",this.code=t,this.statusCode=s,this.details=r,Object.setPrototypeOf(this,Ne.prototype),as(kt.CLIENT_METRIC_MEASUREMENT_ERROR,t,{details:r,statusCode:s})}}function Bu(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}function uv(i){if(!(!i||!i.enabled)){if(!i.baseUrl)return"API Gateway baseUrl is required when enabled";try{const e=new URL(i.baseUrl);if(!["http:","https:","ws:","wss:"].includes(e.protocol))return`Invalid API Gateway baseUrl protocol: ${e.protocol}. Must be http:, https:, ws:, or wss:`}catch{return`Invalid API Gateway baseUrl: ${i.baseUrl}`}if(i.wsPath&&!i.wsPath.startsWith("/"))return"API Gateway wsPath must start with /"}}var Xe;(function(i){i.OFFER="offer",i.ANSWER="answer",i.ICE_CANDIDATE="icecandidate",i.END_SESSION="endsession",i.HEARTBEAT="heartbeat",i.WARNING="warning",i.TALK_STREAM_INTERRUPTED="talkinputstreaminterrupted",i.TALK_STREAM_INPUT="talkstream",i.SESSION_READY="sessionready",i.AGENT_AUDIO_INPUT="agentaudioinput",i.AGENT_AUDIO_INPUT_END="agentaudioinputend"})(Xe||(Xe={}));var yt;(function(i){i.SPEECH_TEXT="speechText",i.CLIENT_TOOL_EVENT="clientToolEvent",i.TOOL_CALL_STARTED_EVENT="toolCallStarted",i.TOOL_CALL_COMPLETED_EVENT="toolCallCompleted",i.TOOL_CALL_FAILED_EVENT="toolCallFailed",i.REASONING_TEXT="reasoningText",i.USER_SPEECH_STARTED="userSpeechStarted",i.USER_SPEECH_ENDED="userSpeechEnded"})(yt||(yt={}));var zt;(function(i){i.PENDING="pending",i.GRANTED="granted",i.DENIED="denied",i.NOT_REQUESTED="not_requested"})(zt||(zt={}));var mr;(function(i){i.USER="user",i.PERSONA="persona"})(mr||(mr={}));var te;(function(i){i.MESSAGE_HISTORY_UPDATED="MESSAGE_HISTORY_UPDATED",i.MESSAGE_STREAM_EVENT_RECEIVED="MESSAGE_STREAM_EVENT_RECEIVED",i.CONNECTION_ESTABLISHED="CONNECTION_ESTABLISHED",i.CONNECTION_CLOSED="CONNECTION_CLOSED",i.INPUT_AUDIO_STREAM_STARTED="INPUT_AUDIO_STREAM_STARTED",i.VIDEO_STREAM_STARTED="VIDEO_STREAM_STARTED",i.VIDEO_PLAY_STARTED="VIDEO_PLAY_STARTED",i.AUDIO_STREAM_STARTED="AUDIO_STREAM_STARTED",i.TALK_STREAM_INTERRUPTED="TALK_STREAM_INTERRUPTED",i.SESSION_READY="SESSION_READY",i.SERVER_WARNING="SERVER_WARNING",i.MIC_PERMISSION_PENDING="MIC_PERMISSION_PENDING",i.MIC_PERMISSION_GRANTED="MIC_PERMISSION_GRANTED",i.MIC_PERMISSION_DENIED="MIC_PERMISSION_DENIED",i.INPUT_AUDIO_DEVICE_CHANGED="INPUT_AUDIO_DEVICE_CHANGED",i.CLIENT_TOOL_EVENT_RECEIVED="CLIENT_TOOL_EVENT_RECEIVED",i.TOOL_CALL_STARTED="TOOL_CALL_STARTED",i.TOOL_CALL_COMPLETED="TOOL_CALL_COMPLETED",i.TOOL_CALL_FAILED="TOOL_CALL_FAILED",i.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",i.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED",i.USER_SPEECH_STARTED="USER_SPEECH_STARTED",i.USER_SPEECH_ENDED="USER_SPEECH_ENDED"})(te||(te={}));var Ue;(function(i){i.WEB_SOCKET_OPEN="WEB_SOCKET_OPEN",i.SIGNAL_MESSAGE_RECEIVED="SIGNAL_MESSAGE_RECEIVED",i.WEBRTC_CHAT_MESSAGE_RECEIVED="WEBRTC_CHAT_MESSAGE_RECEIVED",i.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED="WEBRTC_CLIENT_TOOL_EVENT_RECEIVED",i.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED",i.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED",i.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED",i.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED"})(Ue||(Ue={}));var $t;(function(i){i.NORMAL="CONNECTION_CLOSED_CODE_NORMAL",i.MICROPHONE_PERMISSION_DENIED="CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED",i.SIGNALLING_CLIENT_CONNECTION_FAILURE="CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE",i.WEBRTC_FAILURE="CONNECTION_CLOSED_CODE_WEBRTC_FAILURE",i.SERVER_CLOSED_CONNECTION="CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION"})($t||($t={}));class dv{constructor(e,t){this.sequenceNumber=0,this.config=e,this.signallingClient=t}sendAudioChunk(e){const s={audioData:typeof e=="string"?e:this.arrayBufferToBase64(e),encoding:this.config.encoding,sampleRate:this.config.sampleRate,channels:this.config.channels,sequenceNumber:this.sequenceNumber++};this.signallingClient.sendAgentAudioInput(s)}endSequence(){this.signallingClient.sendAgentAudioInputEnd(),this.sequenceNumber=0}getSequenceNumber(){return this.sequenceNumber}getConfig(){return this.config}arrayBufferToBase64(e){const t=e instanceof Uint8Array?e:new Uint8Array(e),s=Array.from(t,r=>String.fromCharCode(r)).join("");return btoa(s)}}var Os=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};const fv=5,pv=5;class mv{constructor(e,t,s,r,n){var o,a,l,c,h;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.heartBeatIntervalRef=null,this.publicEventEmitter=s,this.internalEventEmitter=r,this.apiGatewayConfig=n,!e)throw new Error("Signalling Client: sessionId is required");this.sessionId=e;const{heartbeatIntervalSeconds:u,maxWsReconnectionAttempts:p,url:d}=t;if(this.heartbeatIntervalSeconds=u||fv,this.maxWsReconnectionAttempts=p||pv,!d.baseUrl)throw new Error("Signalling Client: baseUrl is required");if(!((o=this.apiGatewayConfig)===null||o===void 0)&&o.enabled&&(!((a=this.apiGatewayConfig)===null||a===void 0)&&a.baseUrl)){const g=new URL(this.apiGatewayConfig.baseUrl),_=(l=this.apiGatewayConfig.wsPath)!==null&&l!==void 0?l:"/ws";g.protocol=g.protocol.replace("http","ws"),g.pathname=_,this.url=g;const b=d.protocol||"https",v=b==="http"?"ws":"wss",C=`${b}://${d.baseUrl}`,E=(c=d.signallingPath)!==null&&c!==void 0?c:"/ws",S=new URL(C);S.protocol=v==="ws"?"ws:":"wss:",d.port&&(S.port=d.port),S.pathname=E,S.searchParams.append("session_id",e),this.url.searchParams.append("target_url",S.href)}else{const _=`${d.protocol||"https"}://${d.baseUrl}`;this.url=new URL(_),this.url.protocol=d.protocol==="http"?"ws:":"wss:",d.port&&(this.url.port=d.port),this.url.pathname=(h=d.signallingPath)!==null&&h!==void 0?h:"/ws",this.url.searchParams.append("session_id",e)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){return this.socket=new WebSocket(this.url.href),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.socket}sendOffer(e){return Os(this,void 0,void 0,function*(){const t={connectionDescription:e,userUid:this.sessionId},s={actionType:Xe.OFFER,sessionId:this.sessionId,payload:t};this.sendSignalMessage(s)})}sendIceCandidate(e){return Os(this,void 0,void 0,function*(){const t={actionType:Xe.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(t)})}sendSignalMessage(e){var t;if(((t=this.socket)===null||t===void 0?void 0:t.readyState)===WebSocket.OPEN)try{this.socket.send(JSON.stringify(e))}catch(s){console.error("SignallingClient - sendSignalMessage: error sending message",s)}else this.sendingBuffer.push(e)}sendTalkMessage(e){return Os(this,void 0,void 0,function*(){const t={actionType:Xe.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)})}sendAgentAudioInput(e){const t={actionType:Xe.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)}sendAgentAudioInputEnd(){const e={actionType:Xe.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(e)}closeSocket(){this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(){return Os(this,void 0,void 0,function*(){if(!this.socket)throw new Error("SignallingClient - onOpen: socket is null");try{this.wsConnectionAttempts=0,this.flushSendingBuffer(),this.socket.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(Ue.WEB_SOCKET_OPEN)}catch(e){console.error("SignallingClient - onOpen: error in onOpen",e),this.publicEventEmitter.emit(te.CONNECTION_CLOSED,$t.SIGNALLING_CLIENT_CONNECTION_FAILURE)}})}onClose(){return Os(this,void 0,void 0,function*(){this.wsConnectionAttempts+=1,!this.stopSignal&&(this.wsConnectionAttempts<=this.maxWsReconnectionAttempts?(this.socket=null,setTimeout(()=>{this.connect()},100*this.wsConnectionAttempts)):(this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.publicEventEmitter.emit(te.CONNECTION_CLOSED,$t.SIGNALLING_CLIENT_CONNECTION_FAILURE)))})}onError(e){this.stopSignal||console.error("SignallingClient - onError: ",e)}flushSendingBuffer(){const e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(t=>{var s;((s=this.socket)===null||s===void 0?void 0:s.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(t)):e.push(t)}),this.sendingBuffer=e}onMessage(e){return Os(this,void 0,void 0,function*(){const t=JSON.parse(e.data);this.internalEventEmitter.emit(Ue.SIGNAL_MESSAGE_RECEIVED,t)})}startSendingHeartBeats(){if(!this.socket)throw new Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");const e=this.heartbeatIntervalSeconds*1e3,t={actionType:Xe.HEARTBEAT,sessionId:this.sessionId,payload:""},s=JSON.stringify(t);this.heartBeatIntervalRef=setInterval(()=>{var r;this.stopSignal||((r=this.socket)===null||r===void 0?void 0:r.readyState)===WebSocket.OPEN&&this.socket.send(s)},e)}}function gv(i){return"brainType"in i||"llmId"in i}var Du=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};class _v{constructor(e,t,s){if(!e&&!t)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=t||null,this.baseUrl=(s==null?void 0:s.baseUrl)||rv,this.apiVersion=(s==null?void 0:s.apiVersion)||nv,this.apiGatewayConfig=(s==null?void 0:s.apiGateway)||void 0}buildGatewayUrlAndHeaders(e,t){var s,r;if(!((s=this.apiGatewayConfig)===null||s===void 0)&&s.enabled&&(!((r=this.apiGatewayConfig)===null||r===void 0)&&r.baseUrl)){const n=`${this.apiGatewayConfig.baseUrl}${e}`,o=new URL(`${this.baseUrl}${e}`),a=Object.assign(Object.assign({},t),{"X-Anam-Target-Url":o.href});return{url:n,headers:a}}else return{url:`${this.baseUrl}${e}`,headers:t}}startSession(e,t){return Du(this,void 0,void 0,function*(){if(!this.sessionToken){if(!e)throw new Ne("Persona configuration must be provided when using apiKey",ze.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(e)}e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");try{const s=`${this.apiVersion}/engine/session`,{url:r,headers:n}=this.buildGatewayUrlAndHeaders(s,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),o=yield fetch(r,{method:"POST",headers:n,body:JSON.stringify({personaConfig:e,sessionOptions:t,clientMetadata:Mu})}),a=yield o.json(),l=a.error;switch(o.status){case 200:case 201:return a;case 400:throw new Ne("Invalid request to start session",ze.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:a.message});case 401:throw new Ne("Authentication failed when starting session",ze.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:a.message});case 402:throw new Ne("Please sign up for a plan to start a session",ze.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:a.message});case 403:throw new Ne("Authentication failed when starting session",ze.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:a.message});case 429:throw l==="Concurrent session limit reached"?new Ne("Concurrency limit reached, please upgrade your plan",ze.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:a.message}):l==="Spend cap reached"?new Ne("Spend cap reached, please upgrade your plan",ze.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:a.message}):new Ne("Usage limit reached, please upgrade your plan",ze.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:a.message});case 503:throw new Ne("There are no available personas, please try again later",ze.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:a.message});default:throw new Ne("Unknown error when starting session",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:a.message})}}catch(s){throw s instanceof Ne?s:new Ne("Failed to start session",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:s instanceof Error?s.message:String(s)})}})}unsafe_getSessionToken(e){return Du(this,void 0,void 0,function*(){if(console.warn("Using unsecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let t={clientLabel:"js-sdk-api-key"};gv(e)&&(t=Object.assign(Object.assign({},t),{personaConfig:e}));try{const s=`${this.apiVersion}/auth/session-token`,{url:r,headers:n}=this.buildGatewayUrlAndHeaders(s,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`});return(yield(yield fetch(r,{method:"POST",headers:n,body:JSON.stringify(t)})).json()).sessionToken}catch{throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}var yv=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};class bv{constructor(e,t,s){this.baseUrl=e,this.sessionId=t,this.apiGatewayConfig=s}sendTalkCommand(e){return yv(this,void 0,void 0,function*(){var t,s;try{let r,n={"Content-Type":"application/json"};const o="/talk",a=`?session_id=${this.sessionId}`;if(!((t=this.apiGatewayConfig)===null||t===void 0)&&t.enabled&&(!((s=this.apiGatewayConfig)===null||s===void 0)&&s.baseUrl)){r=`${this.apiGatewayConfig.baseUrl}${o}${a}`;const c=new URL(`${this.baseUrl}${o}${a}`);n["X-Anam-Target-Url"]=c.href}else r=`${this.baseUrl}${o}${a}`;const l=yield fetch(r,{method:"POST",headers:n,body:JSON.stringify({content:e})});if(!l.ok)throw new Error(`Failed to send talk command: ${l.status} ${l.statusText}`)}catch(r){throw console.error(r),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}class vv{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach(s=>{s(...t)})}}class xv{constructor(e,t){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(Ue.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,role:e.role,endOfSpeech:e.end_of_speech,interrupted:e.interrupted}}processUserMessage(e){const t={id:e.id,content:e.content,role:e.role};this.messages.push(t)}processPersonaMessage(e){const t={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},s=this.messages.findIndex(r=>r.id===t.id);if(s!==-1){const r=this.messages[s];this.messages[s]=Object.assign(Object.assign({},r),{content:r.content+t.content,interrupted:r.interrupted||t.interrupted})}else this.messages.push(t)}processWebRtcTextMessageEvent(e){const t=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(te.MESSAGE_STREAM_EVENT_RECEIVED,t),t.role){case mr.USER:this.processUserMessage(t);break;case mr.PERSONA:this.processPersonaMessage(t);break}t.endOfSpeech&&this.publicEventEmitter.emit(te.MESSAGE_HISTORY_UPDATED,this.messages)}}class Cv{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){if(e===te.CONNECTION_ESTABLISHED&&as(kt.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===te.CONNECTION_CLOSED){const[s,r]=t;as(kt.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,s,r?{details:r}:void 0)}this.listeners[e]&&this.listeners[e].forEach(s=>{s(...t)})}}var Ke;(function(i){i[i.UNSTARTED=0]="UNSTARTED",i[i.STREAMING=1]="STREAMING",i[i.INTERRUPTED=2]="INTERRUPTED",i[i.ENDED=3]="ENDED"})(Ke||(Ke={}));var Mo=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};class Ev{constructor(e,t,s){this.state=Ke.UNSTARTED,this.correlationId=e,this.internalEventEmitter=t,this.signallingClient=s,this.internalEventEmitter.addListener(Ue.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(Ue.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return Mo(this,void 0,void 0,function*(){e.actionType===Xe.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=Ke.INTERRUPTED,this.onDeactivate())})}endMessage(){return Mo(this,void 0,void 0,function*(){if(this.state===Ke.ENDED){console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");return}if(this.state!==Ke.STREAMING){console.warn("Talk stream is not active state: "+this.state);return}const e={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(e),this.state=Ke.ENDED,this.onDeactivate()})}streamMessageChunk(e,t){return Mo(this,void 0,void 0,function*(){if(this.state!==Ke.STREAMING&&this.state!==Ke.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const s={content:e,startOfSpeech:this.state===Ke.UNSTARTED,endOfSpeech:t,correlationId:this.correlationId};this.state=t?Ke.ENDED:Ke.STREAMING,this.state===Ke.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(s)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===Ke.STREAMING||this.state===Ke.UNSTARTED}getState(){return this.state}}var Po=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};const Nu=(i,e)=>{if(isNaN(i)||isNaN(e))return 0;const t=e-i;return t>0?t:0};class Uu{constructor(e){this.handlers=Object.create(null),this.pendingCalls=Object.create(null),this.publicEventEmitter=e}clearPendingCalls(){this.pendingCalls=Object.create(null)}registerHandler(e,t){return this.handlers[e]=t,()=>{delete this.handlers[e]}}processToolCallStartedEvent(e){return Po(this,void 0,void 0,function*(){const{tool_name:t,timestamp:s}=e,r=this.WebRTCToolCallStartedEventToToolCallStartedPayload(e),n=new Date(s);if(this.pendingCalls[e.tool_call_id]={payload:r,timestamp:n.getTime()},!(t in this.handlers))return;const o=this.handlers[t];if(o.onStart)try{let a=yield o.onStart(r);if(e.tool_type==="client"){yield this.processToolCallCompletedEvent(Object.assign(Object.assign({},e),{result:a,timestamp:new Date().toISOString()}));return}}catch(a){a instanceof Error?yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${a.message}`,timestamp:new Date().toISOString()})):yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${String(a)}`,timestamp:new Date().toISOString()}));return}})}processToolCallCompletedEvent(e){return Po(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:s,timestamp:r}=e,n=this.webRTCToolCallCompletedEventToToolCallCompletedPayload(e);if(s in this.pendingCalls&&delete this.pendingCalls[s],!(t in this.handlers))return;const o=this.handlers[t];if(o.onComplete){e.tool_type==="client"&&this.publicEventEmitter.emit(te.TOOL_CALL_COMPLETED,n);try{yield o.onComplete(n)}catch(a){console.error(`Error in onComplete handler for tool ${t}:`,a);return}}})}processToolCallFailedEvent(e){return Po(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:s,timestamp:r}=e,n=this.webRTCToolCallFailedEventToToolCallFailedPayload(e);if(s in this.pendingCalls&&delete this.pendingCalls[s],!(t in this.handlers))return;const o=this.handlers[t];if(o.onFail){e.tool_type==="client"&&this.publicEventEmitter.emit(te.TOOL_CALL_FAILED,n);try{yield o.onFail(n)}catch(a){console.error(`Error in onFail handler for tool ${t}:`,a);return}}})}static WebRTCClientToolEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.event_name,eventData:e.event_data,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}static WebRTCToolCallStartedEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.tool_name,eventData:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}WebRTCToolCallStartedEventToToolCallStartedPayload(e){return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,arguments:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallCompletedEventToToolCallCompletedPayload(e){const t=new Date(e.timestamp),s=this.pendingCalls[e.tool_call_id],r=s?Nu(s.timestamp,t.getTime()):0;return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,result:e.result,executionTime:r>0?r:0,timestamp:e.timestamp,documentsAccessed:e.documents_accessed,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallFailedEventToToolCallFailedPayload(e){const t=new Date(e.timestamp),s=this.pendingCalls[e.tool_call_id],r=s?Nu(s.timestamp,t.getTime()):0;return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,errorMessage:e.error_message,executionTime:r>0?r:0,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}var it=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};const Sv=15e3,Tv=5e3,Av=2;class wv{constructor(e,t,s,r,n){var o,a,l,c;this.peerConnection=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:zt.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.publicEventEmitter=s,this.internalEventEmitter=r,this.toolCallManager=n,this.apiGatewayConfig=t.apiGateway;const{inputAudio:h}=t;this.inputAudioState=h.inputAudioState,t.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=t.inputAudio.userProvidedMediaStream),this.disableInputAudio=t.inputAudio.disableInputAudio===!0,this.internalEventEmitter.addListener(Ue.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(Ue.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.internalEventEmitter.addListener(Ue.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,this.toolCallManager.processToolCallStartedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(Ue.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,this.toolCallManager.processToolCallCompletedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(Ue.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,this.toolCallManager.processToolCallFailedEvent.bind(this.toolCallManager)),this.iceServers=t.iceServers,this.signallingClient=new mv(e,t.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig),this.engineApiRestClient=new bv(t.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=t.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=(a=(o=t.metrics)===null||o===void 0?void 0:o.showPeerConnectionStatsReport)!==null&&a!==void 0?a:!1,this.peerConnectionStatsReportOutputFormat=(c=(l=t.metrics)===null||l===void 0?void 0:l.peerConnectionStatsReportOutputFormat)!==null&&c!==void 0?c:"console"}onInputAudioStateChange(e,t){e.isMuted!==t.isMuted&&(t.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(t=>{t.enabled=!1})}unmuteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(t=>{t.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>it(this,void 0,void 0,function*(){if(!(!this.peerConnection||!this.dataChannel||this.dataChannel.readyState!=="open"))try{const e=yield this.peerConnection.getStats();this.sendClientSideMetrics(e)}catch(e){console.error("Failed to collect and send stats:",e)}}),Tv))}sendClientSideMetrics(e){e.forEach(t=>{if(t.type==="inbound-rtp"){const s={message_type:"remote_rtp_stats",data:t};this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(JSON.stringify(s))}})}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const e=setTimeout(()=>{this.successMetricPoller&&(console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},Sv);this.successMetricPoller=setInterval(()=>it(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired){this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e);return}try{const t=yield this.peerConnection.getStats();let s=!1,r=null;t.forEach(n=>{n.type==="inbound-rtp"&&n.kind==="video"&&(n.framesDecoded!==void 0&&n.framesDecoded>0?(s=!0,r="framesDecoded"):n.framesReceived!==void 0&&n.framesReceived>0?(s=!0,r="framesReceived"):n.bytesReceived>0&&n.packetsReceived>0&&n.bytesReceived>1e5&&(s=!0,r="bytesReceived"))}),s&&!this.successMetricFired&&(this.successMetricFired=!0,as(kt.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",r?{detectionMethod:r}:void 0),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e),this.successMetricPoller=null)}catch{}}),500)}muteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}unmuteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(e){return it(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");if(e==null)throw new Error("StreamingClient - changeAudioInputDevice: deviceId is required");const t=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(r=>{r.stop()});const s={echoCancellation:!0,deviceId:{exact:e}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:s}),this.audioDeviceId=e,yield this.setupAudioTrack(),t&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(te.INPUT_AUDIO_DEVICE_CHANGED,e)}catch(s){throw console.error("Failed to change audio input device:",s),new Error(`StreamingClient - changeAudioInputDevice: ${s instanceof Error?s.message:String(s)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}sendDataMessage(e){this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(e)}setMediaStreamTargetById(e){if(e){const t=document.getElementById(e);if(!t)throw new Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=t}}startConnection(){try{if(this.peerConnection){console.error("StreamingClient - startConnection: peer connection already exists");return}this.signallingClient.connect()}catch(e){console.error("StreamingClient - startConnection: error",e),this.handleWebrtcFailure(e)}}stopConnection(){return it(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return it(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - sendTalkCommand: peer connection is null");yield this.engineApiRestClient.sendTalkCommand(e)})}startTalkMessageStream(e){return e||(e=Math.random().toString(36).substring(2,15)),new Ev(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new dv(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return it(this,void 0,void 0,function*(){this.peerConnection=new RTCPeerConnection({iceServers:this.iceServers,iceCandidatePoolSize:Av}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?this.peerConnection.addTransceiver("audio",{direction:"recvonly"}):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?yield this.setupAudioTrack():this.requestMicrophonePermissionAsync().catch(e=>{console.error("Async microphone permission request failed:",e)}))})}onSignalMessage(e){return it(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");return}switch(e.actionType){case Xe.ANSWER:const t=e.payload;yield this.peerConnection.setRemoteDescription(t),this.connectionReceivedAnswer=!0,this.flushRemoteIceCandidateBuffer();break;case Xe.ICE_CANDIDATE:const s=e.payload,r=new RTCIceCandidate(s);this.connectionReceivedAnswer?yield this.peerConnection.addIceCandidate(r):this.remoteIceCandidateBuffer.push(r);break;case Xe.END_SESSION:const n=e.payload;this.publicEventEmitter.emit(te.CONNECTION_CLOSED,$t.SERVER_CLOSED_CONNECTION,n),this.shutdown();break;case Xe.WARNING:const o=e.payload;console.warn("Warning received from server: "+o),this.publicEventEmitter.emit(te.SERVER_WARNING,o);break;case Xe.TALK_STREAM_INTERRUPTED:const a=e.payload;this.publicEventEmitter.emit(te.TALK_STREAM_INTERRUPTED,a.correlationId);break;case Xe.SESSION_READY:const l=e.sessionId;this.publicEventEmitter.emit(te.SESSION_READY,l);break;case Xe.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your anam-sdk version up to date?",e)}})}onSignallingClientConnected(){return it(this,void 0,void 0,function*(){if(!this.peerConnection)try{yield this.initPeerConnectionAndSendOffer()}catch(e){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",e),this.handleWebrtcFailure(e)}})}flushRemoteIceCandidateBuffer(){this.remoteIceCandidateBuffer.forEach(e=>{var t;(t=this.peerConnection)===null||t===void 0||t.addIceCandidate(e)}),this.remoteIceCandidateBuffer=[]}onIceCandidate(e){e.candidate&&this.signallingClient.sendIceCandidate(e.candidate)}onIceConnectionStateChange(){var e,t;(((e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState)==="connected"||((t=this.peerConnection)===null||t===void 0?void 0:t.iceConnectionState)==="completed")&&(this.publicEventEmitter.emit(te.CONNECTION_ESTABLISHED),this.startStatsCollection())}onConnectionStateChange(){var e;((e=this.peerConnection)===null||e===void 0?void 0:e.connectionState)==="closed"&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(e){console.error({message:"StreamingClient - handleWebrtcFailure: ",err:e}),e.name==="NotAllowedError"&&e.message==="Permission denied"?this.publicEventEmitter.emit(te.CONNECTION_CLOSED,$t.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(te.CONNECTION_CLOSED,$t.WEBRTC_FAILURE);try{this.stopConnection()}catch(t){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",t)}}onTrackEventHandler(e){if(e.track.kind==="video"){if(this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(te.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const t=this.videoElement.requestVideoFrameCallback(()=>{var s;(s=this.videoElement)===null||s===void 0||s.cancelVideoFrameCallback(t),this.publicEventEmitter.emit(te.VIDEO_PLAY_STARTED),this.successMetricFired||(this.successMetricFired=!0,as(kt.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:"videoElement"}))})}}else e.track.kind==="audio"&&(this.audioStream=e.streams[0],this.publicEventEmitter.emit(te.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return it(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - setupDataChannels: peer connection is not initialized");return}if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");const e=this.peerConnection.createDataChannel("session",{ordered:!0});e.onopen=()=>{this.dataChannel=e??null},e.onclose=()=>{},e.onmessage=t=>{var s,r,n,o;try{const a=JSON.parse(t.data);switch(a.messageType){case yt.SPEECH_TEXT:this.internalEventEmitter.emit(Ue.WEBRTC_CHAT_MESSAGE_RECEIVED,a.data);break;case yt.CLIENT_TOOL_EVENT:const l=a.data;this.internalEventEmitter.emit(Ue.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,l);const c=Uu.WebRTCClientToolEventToClientToolEvent(l);this.publicEventEmitter.emit(te.CLIENT_TOOL_EVENT_RECEIVED,c);break;case yt.TOOL_CALL_STARTED_EVENT:const h=a.data;this.publicEventEmitter.emit(te.TOOL_CALL_STARTED,this.toolCallManager.WebRTCToolCallStartedEventToToolCallStartedPayload(h)),this.internalEventEmitter.emit(Ue.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,h);break;case yt.TOOL_CALL_COMPLETED_EVENT:const u=a.data;this.publicEventEmitter.emit(te.TOOL_CALL_COMPLETED,this.toolCallManager.webRTCToolCallCompletedEventToToolCallCompletedPayload(u)),this.internalEventEmitter.emit(Ue.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,u);break;case yt.TOOL_CALL_FAILED_EVENT:const p=a.data;this.publicEventEmitter.emit(te.TOOL_CALL_FAILED,this.toolCallManager.webRTCToolCallFailedEventToToolCallFailedPayload(p)),this.internalEventEmitter.emit(Ue.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,p);break;case yt.REASONING_TEXT:this.internalEventEmitter.emit(Ue.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,a.data);break;case yt.USER_SPEECH_STARTED:this.publicEventEmitter.emit(te.USER_SPEECH_STARTED,(r=(s=a.data)===null||s===void 0?void 0:s.user_action_correlation_id)!==null&&r!==void 0?r:"unknown");break;case yt.USER_SPEECH_ENDED:this.publicEventEmitter.emit(te.USER_SPEECH_ENDED,(o=(n=a.data)===null||n===void 0?void 0:n.user_action_correlation_id)!==null&&o!==void 0?o:"unknown");break;default:break}}catch(a){console.error("Failed to parse data channel message:",a)}}})}requestMicrophonePermissionAsync(){return it(this,void 0,void 0,function*(){if(this.inputAudioState.permissionState!==zt.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:zt.PENDING}),this.publicEventEmitter.emit(te.MIC_PERMISSION_PENDING);try{const e={echoCancellation:!0};this.audioDeviceId&&(e.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:e}),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:zt.GRANTED}),this.publicEventEmitter.emit(te.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(e){console.error("Failed to get microphone permission:",e),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:zt.DENIED});const t=e instanceof Error?e.message:String(e);this.publicEventEmitter.emit(te.MIC_PERMISSION_DENIED,t)}}})}setupAudioTrack(){return it(this,void 0,void 0,function*(){if(!this.peerConnection||!this.inputAudioStream)return;if(!this.inputAudioStream.getAudioTracks().length){console.error("StreamingClient - setupAudioTrack: stream does not have audio tracks");return}this.inputAudioState.isMuted&&this.muteAllAudioTracks();const e=this.inputAudioStream.getAudioTracks()[0],s=this.peerConnection.getSenders().find(r=>{var n;return((n=r.track)===null||n===void 0?void 0:n.kind)==="audio"||r.track===null&&r.dtmf!==null});if(s)try{yield s.replaceTrack(e)}catch(r){console.error("Failed to replace audio track:",r),this.peerConnection.addTrack(e,this.inputAudioStream)}else this.peerConnection.addTrack(e,this.inputAudioStream);this.publicEventEmitter.emit(te.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return it(this,void 0,void 0,function*(){if(yield this.initPeerConnection(),!this.peerConnection){console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized");return}try{const e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e)}catch(e){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",e)}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription)})}shutdown(){return it(this,void 0,void 0,function*(){var e;if(this.showPeerConnectionStatsReport){const t=yield(e=this.peerConnection)===null||e===void 0?void 0:e.getStats();if(t){const s=hv(t,this.peerConnectionStatsReportOutputFormat);s&&console.log(s,void 0,2)}}this.statsCollectionInterval&&(clearInterval(this.statsCollectionInterval),this.statsCollectionInterval=null),this.successMetricPoller&&(clearInterval(this.successMetricPoller),this.successMetricPoller=null),this.successMetricFired=!1;try{this.inputAudioStream&&this.inputAudioStream.getTracks().forEach(t=>{t.stop()}),this.inputAudioStream=null}catch(t){console.error("StreamingClient - shutdown: error stopping input audio stream",t)}try{this.signallingClient.stop()}catch(t){console.error("StreamingClient - shutdown: error stopping signallilng",t)}this.toolCallManager.clearPendingCalls();try{this.peerConnection&&this.peerConnection.connectionState!=="closed"&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(t){console.error("StreamingClient - shutdown: error closing peer connection",t)}})}}class Iv{constructor(e,t){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(Ue.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,endOfThought:e.end_of_thought,role:e.role}}processWebRtcReasoningTextMessageEvent(e){const t=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(te.REASONING_STREAM_EVENT_RECEIVED,t);const s={id:t.id,content:t.content,role:t.role},r=this.reasoning_messages.findIndex(n=>n.id===s.id);if(r!==-1){const n=this.reasoning_messages[r];n.content+=s.content,this.reasoning_messages[r]=n}else this.reasoning_messages.push(s);t.endOfThought&&this.publicEventEmitter.emit(te.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}var jt=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};class Rv{constructor(e,t,s){var r,n,o,a,l;this.inputAudioState={isMuted:!1,permissionState:zt.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const c=this.validateClientConfig(e,t,s);if(c)throw new Ne(c,ze.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=t,this.clientOptions=s,(!((r=s==null?void 0:s.api)===null||r===void 0)&&r.baseUrl||!((n=s==null?void 0:s.api)===null||n===void 0)&&n.apiVersion)&&av(s.api.baseUrl||Pu,s.api.apiVersion||Io),!((a=(o=s==null?void 0:s.api)===null||o===void 0?void 0:o.apiGateway)===null||a===void 0)&&a.enabled&&lv(s.api.apiGateway),!((l=s==null?void 0:s.metrics)===null||l===void 0)&&l.disableClientMetrics&&cv(!0),this.publicEventEmitter=new Cv,this.internalEventEmitter=new vv,this.toolCallManager=new Uu(this.publicEventEmitter),this.apiClient=new _v(e,s==null?void 0:s.apiKey,s==null?void 0:s.api),this.messageHistoryClient=new xv(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new Iv(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const t=e.split(".")[1],s=iv.Buffer.from(t,"base64").toString("utf8");return JSON.parse(s)}catch{throw new Error("Invalid session token format")}}validateClientConfig(e,t,s){var r,n;if(!e&&!(s!=null&&s.apiKey))return"Either sessionToken or apiKey must be provided";if(s!=null&&s.apiKey&&e)return"Only one of sessionToken or apiKey should be used";const o=uv((r=s==null?void 0:s.api)===null||r===void 0?void 0:r.apiGateway);if(o)return o;if(e){const a=this.decodeJwt(e);this.organizationId=a.accountId,ks({organizationId:this.organizationId});const l=(n=a.type)===null||n===void 0?void 0:n.toLowerCase();if(l==="legacy")return"Legacy session tokens are no longer supported. Please define your persona when creating your session token. See https://docs.anam.ai/resources/migrating-legacy for more information.";if((l==="ephemeral"||l==="stateful")&&t)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!t)return"Missing persona config. Persona configuration must be provided when using apiKey";if(s!=null&&s.voiceDetection){if(s.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(s.voiceDetection.endOfSpeechSensitivity!==void 0){if(typeof s.voiceDetection.endOfSpeechSensitivity!="number")return"End of speech sensitivity must be a number";if(s.voiceDetection.endOfSpeechSensitivity<0||s.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var e;const t={};if(!((e=this.clientOptions)===null||e===void 0)&&e.voiceDetection&&(t.voiceDetection=this.clientOptions.voiceDetection),Object.keys(t).length!==0)return t}startSession(e){return jt(this,void 0,void 0,function*(){var t,s,r,n,o,a,l,c,h,u,p,d;const g=this.personaConfig,_=this.buildStartSessionOptionsForClient(),b=yield this.apiClient.startSession(g,_),{sessionId:v,clientConfig:C,engineHost:E,engineProtocol:S,signallingEndpoint:w}=b,{heartbeatIntervalSeconds:R,maxWsReconnectionAttempts:M,iceServers:D}=C;this.sessionId=v,ks({sessionId:this.sessionId});const G=!((t=this.clientOptions)===null||t===void 0)&&t.iceServers?this.clientOptions.iceServers:D;try{this.streamingClient=new wv(v,{engine:{baseUrl:`${S}://${E}`},signalling:{heartbeatIntervalSeconds:R,maxWsReconnectionAttempts:M,url:{baseUrl:E,protocol:S,signallingPath:w}},iceServers:G,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:!((s=this.clientOptions)===null||s===void 0)&&s.disableInputAudio?void 0:e,audioDeviceId:(r=this.clientOptions)===null||r===void 0?void 0:r.audioDeviceId,disableInputAudio:(n=this.clientOptions)===null||n===void 0?void 0:n.disableInputAudio},apiGateway:(a=(o=this.clientOptions)===null||o===void 0?void 0:o.api)===null||a===void 0?void 0:a.apiGateway,metrics:{showPeerConnectionStatsReport:(h=(c=(l=this.clientOptions)===null||l===void 0?void 0:l.metrics)===null||c===void 0?void 0:c.showPeerConnectionStatsReport)!==null&&h!==void 0?h:!1,peerConnectionStatsReportOutputFormat:(d=(p=(u=this.clientOptions)===null||u===void 0?void 0:u.metrics)===null||p===void 0?void 0:p.peerConnectionStatsReportOutputFormat)!==null&&d!==void 0?d:"console"}},this.publicEventEmitter,this.internalEventEmitter,this.toolCallManager)}catch(k){throw ks({sessionId:null}),new Ne("Failed to initialize streaming client",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:k instanceof Error?k.message:String(k),sessionId:v})}return v})}startSessionIfNeeded(e){return jt(this,void 0,void 0,function*(){if((!this.sessionId||!this.streamingClient)&&(yield this.startSession(e),!this.sessionId||!this.streamingClient))throw new Ne("Session ID or streaming client is not available after starting session",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return jt(this,void 0,void 0,function*(){var t;if(this._isStreaming)throw new Error("Already streaming");const s=Bu();return ks({attemptCorrelationId:s,sessionId:null}),as(kt.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio&&e&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored."),yield this.startSessionIfNeeded(e),this._isStreaming=!0,new Promise(r=>{var n;const o=[];let a=!1,l=!1;this.publicEventEmitter.addListener(te.VIDEO_STREAM_STARTED,c=>{o.push(c),a=!0,l&&r(o)}),this.publicEventEmitter.addListener(te.AUDIO_STREAM_STARTED,c=>{o.push(c),l=!0,a&&r(o)}),(n=this.streamingClient)===null||n===void 0||n.startConnection()})})}streamToVideoAndAudioElements(e,t,s){return jt(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(e,s)})}streamToVideoElement(e,t){return jt(this,void 0,void 0,function*(){var s;const r=Bu();ks({attemptCorrelationId:r,sessionId:null}),as(kt.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((s=this.clientOptions)===null||s===void 0)&&s.disableInputAudio&&t&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(t)}catch(n){throw n instanceof Ne?n:new Ne("Failed to start session",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:n instanceof Error?n.message:String(n),sessionId:this.sessionId})}if(this._isStreaming)throw new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw new Error("Failed to stream: streaming client is not available");this.streamingClient.setMediaStreamTargetById(e),this.streamingClient.startConnection()})}talk(e){return jt(this,void 0,void 0,function*(){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(e)})}sendDataMessage(e){if(this.streamingClient)this.streamingClient.sendDataMessage(e);else throw new Error("Failed to send message: session is not started.")}sendUserMessage(e){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to send user message: no active session");const s=new Date().toISOString().replace("Z",""),r=JSON.stringify({content:e,timestamp:s,session_id:t,message_type:"speech"});this.sendDataMessage(r)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to send interrupt command: no active session");const t=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:new Date().toISOString()});this.sendDataMessage(t)}addContext(e){if(!this._isStreaming)throw new Error("Failed to add context: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to add context: no active session");const s=JSON.stringify({message_type:"context",session_id:t,content:e});this.sendDataMessage(s)}stopStreaming(){return jt(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(te.CONNECTION_CLOSED,$t.NORMAL),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,ks({attemptCorrelationId:null,sessionId:null,organizationId:this.organizationId}),this._isStreaming=!1)})}isStreaming(){return this._isStreaming}setPersonaConfig(e){this.personaConfig=e}getPersonaConfig(){return this.personaConfig}getInputAudioState(){var e;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Audio state will not be used because input audio is disabled."),this.streamingClient&&(this.inputAudioState=this.streamingClient.getInputAudioState()),this.inputAudioState}muteInputAudio(){var e,t;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."),this.streamingClient&&!(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var e,t;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(e){return jt(this,void 0,void 0,function*(){var t;if(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(e)})}createTalkMessageStream(e){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(e&&e.trim()==="")throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(e)}createAgentAudioInputStream(e){if(!this.streamingClient)throw new Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(e)}addListener(e,t){this.publicEventEmitter.addListener(e,t)}removeListener(e,t){this.publicEventEmitter.removeListener(e,t)}getActiveSessionId(){return this.sessionId}registerToolCallHandler(e,t){return this.toolCallManager.registerHandler(e,t)}}const Mv=(i,e)=>new Rv(i,void 0,e);let Pv=0;class kv{constructor(e){this.onVideoReady=null,this.onConnected=null,this.onDisconnected=null,this.onTalkStreamInterrupted=null,this.onError=null,this.audioInputStream=null,this.videoElement=null,this._connected=!1,this._closing=!1,this.inlineMode=e.inlineMode??!1,this.client=Mv(e.sessionToken,{disableInputAudio:!0,metrics:{disableClientMetrics:!0}})}get isConnected(){return this._connected}get videoEl(){return this.videoElement}async connect(){var e;try{const t=`anam-avatar-video-${++Pv}`;this.videoElement=document.createElement("video"),this.videoElement.id=t,this.videoElement.autoplay=!0,this.videoElement.playsInline=!0,this.inlineMode?this.videoElement.style.cssText=`
|
|
926
|
+
*/var Ru;function iv(){return Ru||(Ru=1,(function(i){const e=tv(),t=sv(),s=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;i.Buffer=a,i.SlowBuffer=C,i.INSPECT_MAX_BYTES=50;const r=2147483647;i.kMaxLength=r,a.TYPED_ARRAY_SUPPORT=n(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function n(){try{const y=new Uint8Array(1),f={foo:function(){return 42}};return Object.setPrototypeOf(f,Uint8Array.prototype),Object.setPrototypeOf(y,f),y.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(y){if(y>r)throw new RangeError('The value "'+y+'" is invalid for option "size"');const f=new Uint8Array(y);return Object.setPrototypeOf(f,a.prototype),f}function a(y,f,m){if(typeof y=="number"){if(typeof f=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(y)}return l(y,f,m)}a.poolSize=8192;function l(y,f,m){if(typeof y=="string")return p(y,f);if(ArrayBuffer.isView(y))return g(y);if(y==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof y);if(tt(y,ArrayBuffer)||y&&tt(y.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(tt(y,SharedArrayBuffer)||y&&tt(y.buffer,SharedArrayBuffer)))return _(y,f,m);if(typeof y=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const x=y.valueOf&&y.valueOf();if(x!=null&&x!==y)return a.from(x,f,m);const T=b(y);if(T)return T;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof y[Symbol.toPrimitive]=="function")return a.from(y[Symbol.toPrimitive]("string"),f,m);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof y)}a.from=function(y,f,m){return l(y,f,m)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function c(y){if(typeof y!="number")throw new TypeError('"size" argument must be of type number');if(y<0)throw new RangeError('The value "'+y+'" is invalid for option "size"')}function h(y,f,m){return c(y),y<=0?o(y):f!==void 0?typeof m=="string"?o(y).fill(f,m):o(y).fill(f):o(y)}a.alloc=function(y,f,m){return h(y,f,m)};function u(y){return c(y),o(y<0?0:v(y)|0)}a.allocUnsafe=function(y){return u(y)},a.allocUnsafeSlow=function(y){return u(y)};function p(y,f){if((typeof f!="string"||f==="")&&(f="utf8"),!a.isEncoding(f))throw new TypeError("Unknown encoding: "+f);const m=E(y,f)|0;let x=o(m);const T=x.write(y,f);return T!==m&&(x=x.slice(0,T)),x}function d(y){const f=y.length<0?0:v(y.length)|0,m=o(f);for(let x=0;x<f;x+=1)m[x]=y[x]&255;return m}function g(y){if(tt(y,Uint8Array)){const f=new Uint8Array(y);return _(f.buffer,f.byteOffset,f.byteLength)}return d(y)}function _(y,f,m){if(f<0||y.byteLength<f)throw new RangeError('"offset" is outside of buffer bounds');if(y.byteLength<f+(m||0))throw new RangeError('"length" is outside of buffer bounds');let x;return f===void 0&&m===void 0?x=new Uint8Array(y):m===void 0?x=new Uint8Array(y,f):x=new Uint8Array(y,f,m),Object.setPrototypeOf(x,a.prototype),x}function b(y){if(a.isBuffer(y)){const f=v(y.length)|0,m=o(f);return m.length===0||y.copy(m,0,0,f),m}if(y.length!==void 0)return typeof y.length!="number"||zs(y.length)?o(0):d(y);if(y.type==="Buffer"&&Array.isArray(y.data))return d(y.data)}function v(y){if(y>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return y|0}function C(y){return+y!=y&&(y=0),a.alloc(+y)}a.isBuffer=function(f){return f!=null&&f._isBuffer===!0&&f!==a.prototype},a.compare=function(f,m){if(tt(f,Uint8Array)&&(f=a.from(f,f.offset,f.byteLength)),tt(m,Uint8Array)&&(m=a.from(m,m.offset,m.byteLength)),!a.isBuffer(f)||!a.isBuffer(m))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(f===m)return 0;let x=f.length,T=m.length;for(let I=0,P=Math.min(x,T);I<P;++I)if(f[I]!==m[I]){x=f[I],T=m[I];break}return x<T?-1:T<x?1:0},a.isEncoding=function(f){switch(String(f).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(f,m){if(!Array.isArray(f))throw new TypeError('"list" argument must be an Array of Buffers');if(f.length===0)return a.alloc(0);let x;if(m===void 0)for(m=0,x=0;x<f.length;++x)m+=f[x].length;const T=a.allocUnsafe(m);let I=0;for(x=0;x<f.length;++x){let P=f[x];if(tt(P,Uint8Array))I+P.length>T.length?(a.isBuffer(P)||(P=a.from(P)),P.copy(T,I)):Uint8Array.prototype.set.call(T,P,I);else if(a.isBuffer(P))P.copy(T,I);else throw new TypeError('"list" argument must be an Array of Buffers');I+=P.length}return T};function E(y,f){if(a.isBuffer(y))return y.length;if(ArrayBuffer.isView(y)||tt(y,ArrayBuffer))return y.byteLength;if(typeof y!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof y);const m=y.length,x=arguments.length>2&&arguments[2]===!0;if(!x&&m===0)return 0;let T=!1;for(;;)switch(f){case"ascii":case"latin1":case"binary":return m;case"utf8":case"utf-8":return Ct(y).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return m*2;case"hex":return m>>>1;case"base64":return Bt(y).length;default:if(T)return x?-1:Ct(y).length;f=(""+f).toLowerCase(),T=!0}}a.byteLength=E;function S(y,f,m){let x=!1;if((f===void 0||f<0)&&(f=0),f>this.length||((m===void 0||m>this.length)&&(m=this.length),m<=0)||(m>>>=0,f>>>=0,m<=f))return"";for(y||(y="utf8");;)switch(y){case"hex":return N(this,f,m);case"utf8":case"utf-8":return z(this,f,m);case"ascii":return U(this,f,m);case"latin1":case"binary":return q(this,f,m);case"base64":return X(this,f,m);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return K(this,f,m);default:if(x)throw new TypeError("Unknown encoding: "+y);y=(y+"").toLowerCase(),x=!0}}a.prototype._isBuffer=!0;function w(y,f,m){const x=y[f];y[f]=y[m],y[m]=x}a.prototype.swap16=function(){const f=this.length;if(f%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let m=0;m<f;m+=2)w(this,m,m+1);return this},a.prototype.swap32=function(){const f=this.length;if(f%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let m=0;m<f;m+=4)w(this,m,m+3),w(this,m+1,m+2);return this},a.prototype.swap64=function(){const f=this.length;if(f%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let m=0;m<f;m+=8)w(this,m,m+7),w(this,m+1,m+6),w(this,m+2,m+5),w(this,m+3,m+4);return this},a.prototype.toString=function(){const f=this.length;return f===0?"":arguments.length===0?z(this,0,f):S.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(f){if(!a.isBuffer(f))throw new TypeError("Argument must be a Buffer");return this===f?!0:a.compare(this,f)===0},a.prototype.inspect=function(){let f="";const m=i.INSPECT_MAX_BYTES;return f=this.toString("hex",0,m).replace(/(.{2})/g,"$1 ").trim(),this.length>m&&(f+=" ... "),"<Buffer "+f+">"},s&&(a.prototype[s]=a.prototype.inspect),a.prototype.compare=function(f,m,x,T,I){if(tt(f,Uint8Array)&&(f=a.from(f,f.offset,f.byteLength)),!a.isBuffer(f))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof f);if(m===void 0&&(m=0),x===void 0&&(x=f?f.length:0),T===void 0&&(T=0),I===void 0&&(I=this.length),m<0||x>f.length||T<0||I>this.length)throw new RangeError("out of range index");if(T>=I&&m>=x)return 0;if(T>=I)return-1;if(m>=x)return 1;if(m>>>=0,x>>>=0,T>>>=0,I>>>=0,this===f)return 0;let P=I-T,J=x-m;const Re=Math.min(P,J),Te=this.slice(T,I),Me=f.slice(m,x);for(let _e=0;_e<Re;++_e)if(Te[_e]!==Me[_e]){P=Te[_e],J=Me[_e];break}return P<J?-1:J<P?1:0};function R(y,f,m,x,T){if(y.length===0)return-1;if(typeof m=="string"?(x=m,m=0):m>2147483647?m=2147483647:m<-2147483648&&(m=-2147483648),m=+m,zs(m)&&(m=T?0:y.length-1),m<0&&(m=y.length+m),m>=y.length){if(T)return-1;m=y.length-1}else if(m<0)if(T)m=0;else return-1;if(typeof f=="string"&&(f=a.from(f,x)),a.isBuffer(f))return f.length===0?-1:M(y,f,m,x,T);if(typeof f=="number")return f=f&255,typeof Uint8Array.prototype.indexOf=="function"?T?Uint8Array.prototype.indexOf.call(y,f,m):Uint8Array.prototype.lastIndexOf.call(y,f,m):M(y,[f],m,x,T);throw new TypeError("val must be string, number or Buffer")}function M(y,f,m,x,T){let I=1,P=y.length,J=f.length;if(x!==void 0&&(x=String(x).toLowerCase(),x==="ucs2"||x==="ucs-2"||x==="utf16le"||x==="utf-16le")){if(y.length<2||f.length<2)return-1;I=2,P/=2,J/=2,m/=2}function Re(Me,_e){return I===1?Me[_e]:Me.readUInt16BE(_e*I)}let Te;if(T){let Me=-1;for(Te=m;Te<P;Te++)if(Re(y,Te)===Re(f,Me===-1?0:Te-Me)){if(Me===-1&&(Me=Te),Te-Me+1===J)return Me*I}else Me!==-1&&(Te-=Te-Me),Me=-1}else for(m+J>P&&(m=P-J),Te=m;Te>=0;Te--){let Me=!0;for(let _e=0;_e<J;_e++)if(Re(y,Te+_e)!==Re(f,_e)){Me=!1;break}if(Me)return Te}return-1}a.prototype.includes=function(f,m,x){return this.indexOf(f,m,x)!==-1},a.prototype.indexOf=function(f,m,x){return R(this,f,m,x,!0)},a.prototype.lastIndexOf=function(f,m,x){return R(this,f,m,x,!1)};function D(y,f,m,x){m=Number(m)||0;const T=y.length-m;x?(x=Number(x),x>T&&(x=T)):x=T;const I=f.length;x>I/2&&(x=I/2);let P;for(P=0;P<x;++P){const J=parseInt(f.substr(P*2,2),16);if(zs(J))return P;y[m+P]=J}return P}function G(y,f,m,x){return dt(Ct(f,y.length-m),y,m,x)}function k(y,f,m,x){return dt(hs(f),y,m,x)}function O(y,f,m,x){return dt(Bt(f),y,m,x)}function V(y,f,m,x){return dt(Vs(f,y.length-m),y,m,x)}a.prototype.write=function(f,m,x,T){if(m===void 0)T="utf8",x=this.length,m=0;else if(x===void 0&&typeof m=="string")T=m,x=this.length,m=0;else if(isFinite(m))m=m>>>0,isFinite(x)?(x=x>>>0,T===void 0&&(T="utf8")):(T=x,x=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const I=this.length-m;if((x===void 0||x>I)&&(x=I),f.length>0&&(x<0||m<0)||m>this.length)throw new RangeError("Attempt to write outside buffer bounds");T||(T="utf8");let P=!1;for(;;)switch(T){case"hex":return D(this,f,m,x);case"utf8":case"utf-8":return G(this,f,m,x);case"ascii":case"latin1":case"binary":return k(this,f,m,x);case"base64":return O(this,f,m,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,f,m,x);default:if(P)throw new TypeError("Unknown encoding: "+T);T=(""+T).toLowerCase(),P=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function X(y,f,m){return f===0&&m===y.length?e.fromByteArray(y):e.fromByteArray(y.slice(f,m))}function z(y,f,m){m=Math.min(y.length,m);const x=[];let T=f;for(;T<m;){const I=y[T];let P=null,J=I>239?4:I>223?3:I>191?2:1;if(T+J<=m){let Re,Te,Me,_e;switch(J){case 1:I<128&&(P=I);break;case 2:Re=y[T+1],(Re&192)===128&&(_e=(I&31)<<6|Re&63,_e>127&&(P=_e));break;case 3:Re=y[T+1],Te=y[T+2],(Re&192)===128&&(Te&192)===128&&(_e=(I&15)<<12|(Re&63)<<6|Te&63,_e>2047&&(_e<55296||_e>57343)&&(P=_e));break;case 4:Re=y[T+1],Te=y[T+2],Me=y[T+3],(Re&192)===128&&(Te&192)===128&&(Me&192)===128&&(_e=(I&15)<<18|(Re&63)<<12|(Te&63)<<6|Me&63,_e>65535&&_e<1114112&&(P=_e))}}P===null?(P=65533,J=1):P>65535&&(P-=65536,x.push(P>>>10&1023|55296),P=56320|P&1023),x.push(P),T+=J}return B(x)}const de=4096;function B(y){const f=y.length;if(f<=de)return String.fromCharCode.apply(String,y);let m="",x=0;for(;x<f;)m+=String.fromCharCode.apply(String,y.slice(x,x+=de));return m}function U(y,f,m){let x="";m=Math.min(y.length,m);for(let T=f;T<m;++T)x+=String.fromCharCode(y[T]&127);return x}function q(y,f,m){let x="";m=Math.min(y.length,m);for(let T=f;T<m;++T)x+=String.fromCharCode(y[T]);return x}function N(y,f,m){const x=y.length;(!f||f<0)&&(f=0),(!m||m<0||m>x)&&(m=x);let T="";for(let I=f;I<m;++I)T+=Mr[y[I]];return T}function K(y,f,m){const x=y.slice(f,m);let T="";for(let I=0;I<x.length-1;I+=2)T+=String.fromCharCode(x[I]+x[I+1]*256);return T}a.prototype.slice=function(f,m){const x=this.length;f=~~f,m=m===void 0?x:~~m,f<0?(f+=x,f<0&&(f=0)):f>x&&(f=x),m<0?(m+=x,m<0&&(m=0)):m>x&&(m=x),m<f&&(m=f);const T=this.subarray(f,m);return Object.setPrototypeOf(T,a.prototype),T};function Z(y,f,m){if(y%1!==0||y<0)throw new RangeError("offset is not uint");if(y+f>m)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(f,m,x){f=f>>>0,m=m>>>0,x||Z(f,m,this.length);let T=this[f],I=1,P=0;for(;++P<m&&(I*=256);)T+=this[f+P]*I;return T},a.prototype.readUintBE=a.prototype.readUIntBE=function(f,m,x){f=f>>>0,m=m>>>0,x||Z(f,m,this.length);let T=this[f+--m],I=1;for(;m>0&&(I*=256);)T+=this[f+--m]*I;return T},a.prototype.readUint8=a.prototype.readUInt8=function(f,m){return f=f>>>0,m||Z(f,1,this.length),this[f]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(f,m){return f=f>>>0,m||Z(f,2,this.length),this[f]|this[f+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(f,m){return f=f>>>0,m||Z(f,2,this.length),this[f]<<8|this[f+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(f,m){return f=f>>>0,m||Z(f,4,this.length),(this[f]|this[f+1]<<8|this[f+2]<<16)+this[f+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(f,m){return f=f>>>0,m||Z(f,4,this.length),this[f]*16777216+(this[f+1]<<16|this[f+2]<<8|this[f+3])},a.prototype.readBigUInt64LE=ft(function(f){f=f>>>0,we(f,"offset");const m=this[f],x=this[f+7];(m===void 0||x===void 0)&&ce(f,this.length-8);const T=m+this[++f]*2**8+this[++f]*2**16+this[++f]*2**24,I=this[++f]+this[++f]*2**8+this[++f]*2**16+x*2**24;return BigInt(T)+(BigInt(I)<<BigInt(32))}),a.prototype.readBigUInt64BE=ft(function(f){f=f>>>0,we(f,"offset");const m=this[f],x=this[f+7];(m===void 0||x===void 0)&&ce(f,this.length-8);const T=m*2**24+this[++f]*2**16+this[++f]*2**8+this[++f],I=this[++f]*2**24+this[++f]*2**16+this[++f]*2**8+x;return(BigInt(T)<<BigInt(32))+BigInt(I)}),a.prototype.readIntLE=function(f,m,x){f=f>>>0,m=m>>>0,x||Z(f,m,this.length);let T=this[f],I=1,P=0;for(;++P<m&&(I*=256);)T+=this[f+P]*I;return I*=128,T>=I&&(T-=Math.pow(2,8*m)),T},a.prototype.readIntBE=function(f,m,x){f=f>>>0,m=m>>>0,x||Z(f,m,this.length);let T=m,I=1,P=this[f+--T];for(;T>0&&(I*=256);)P+=this[f+--T]*I;return I*=128,P>=I&&(P-=Math.pow(2,8*m)),P},a.prototype.readInt8=function(f,m){return f=f>>>0,m||Z(f,1,this.length),this[f]&128?(255-this[f]+1)*-1:this[f]},a.prototype.readInt16LE=function(f,m){f=f>>>0,m||Z(f,2,this.length);const x=this[f]|this[f+1]<<8;return x&32768?x|4294901760:x},a.prototype.readInt16BE=function(f,m){f=f>>>0,m||Z(f,2,this.length);const x=this[f+1]|this[f]<<8;return x&32768?x|4294901760:x},a.prototype.readInt32LE=function(f,m){return f=f>>>0,m||Z(f,4,this.length),this[f]|this[f+1]<<8|this[f+2]<<16|this[f+3]<<24},a.prototype.readInt32BE=function(f,m){return f=f>>>0,m||Z(f,4,this.length),this[f]<<24|this[f+1]<<16|this[f+2]<<8|this[f+3]},a.prototype.readBigInt64LE=ft(function(f){f=f>>>0,we(f,"offset");const m=this[f],x=this[f+7];(m===void 0||x===void 0)&&ce(f,this.length-8);const T=this[f+4]+this[f+5]*2**8+this[f+6]*2**16+(x<<24);return(BigInt(T)<<BigInt(32))+BigInt(m+this[++f]*2**8+this[++f]*2**16+this[++f]*2**24)}),a.prototype.readBigInt64BE=ft(function(f){f=f>>>0,we(f,"offset");const m=this[f],x=this[f+7];(m===void 0||x===void 0)&&ce(f,this.length-8);const T=(m<<24)+this[++f]*2**16+this[++f]*2**8+this[++f];return(BigInt(T)<<BigInt(32))+BigInt(this[++f]*2**24+this[++f]*2**16+this[++f]*2**8+x)}),a.prototype.readFloatLE=function(f,m){return f=f>>>0,m||Z(f,4,this.length),t.read(this,f,!0,23,4)},a.prototype.readFloatBE=function(f,m){return f=f>>>0,m||Z(f,4,this.length),t.read(this,f,!1,23,4)},a.prototype.readDoubleLE=function(f,m){return f=f>>>0,m||Z(f,8,this.length),t.read(this,f,!0,52,8)},a.prototype.readDoubleBE=function(f,m){return f=f>>>0,m||Z(f,8,this.length),t.read(this,f,!1,52,8)};function $(y,f,m,x,T,I){if(!a.isBuffer(y))throw new TypeError('"buffer" argument must be a Buffer instance');if(f>T||f<I)throw new RangeError('"value" argument is out of bounds');if(m+x>y.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(f,m,x,T){if(f=+f,m=m>>>0,x=x>>>0,!T){const J=Math.pow(2,8*x)-1;$(this,f,m,x,J,0)}let I=1,P=0;for(this[m]=f&255;++P<x&&(I*=256);)this[m+P]=f/I&255;return m+x},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(f,m,x,T){if(f=+f,m=m>>>0,x=x>>>0,!T){const J=Math.pow(2,8*x)-1;$(this,f,m,x,J,0)}let I=x-1,P=1;for(this[m+I]=f&255;--I>=0&&(P*=256);)this[m+I]=f/P&255;return m+x},a.prototype.writeUint8=a.prototype.writeUInt8=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,1,255,0),this[m]=f&255,m+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,2,65535,0),this[m]=f&255,this[m+1]=f>>>8,m+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,2,65535,0),this[m]=f>>>8,this[m+1]=f&255,m+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,4,4294967295,0),this[m+3]=f>>>24,this[m+2]=f>>>16,this[m+1]=f>>>8,this[m]=f&255,m+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,4,4294967295,0),this[m]=f>>>24,this[m+1]=f>>>16,this[m+2]=f>>>8,this[m+3]=f&255,m+4};function ae(y,f,m,x,T){se(f,x,T,y,m,7);let I=Number(f&BigInt(4294967295));y[m++]=I,I=I>>8,y[m++]=I,I=I>>8,y[m++]=I,I=I>>8,y[m++]=I;let P=Number(f>>BigInt(32)&BigInt(4294967295));return y[m++]=P,P=P>>8,y[m++]=P,P=P>>8,y[m++]=P,P=P>>8,y[m++]=P,m}function xe(y,f,m,x,T){se(f,x,T,y,m,7);let I=Number(f&BigInt(4294967295));y[m+7]=I,I=I>>8,y[m+6]=I,I=I>>8,y[m+5]=I,I=I>>8,y[m+4]=I;let P=Number(f>>BigInt(32)&BigInt(4294967295));return y[m+3]=P,P=P>>8,y[m+2]=P,P=P>>8,y[m+1]=P,P=P>>8,y[m]=P,m+8}a.prototype.writeBigUInt64LE=ft(function(f,m=0){return ae(this,f,m,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=ft(function(f,m=0){return xe(this,f,m,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(f,m,x,T){if(f=+f,m=m>>>0,!T){const Re=Math.pow(2,8*x-1);$(this,f,m,x,Re-1,-Re)}let I=0,P=1,J=0;for(this[m]=f&255;++I<x&&(P*=256);)f<0&&J===0&&this[m+I-1]!==0&&(J=1),this[m+I]=(f/P>>0)-J&255;return m+x},a.prototype.writeIntBE=function(f,m,x,T){if(f=+f,m=m>>>0,!T){const Re=Math.pow(2,8*x-1);$(this,f,m,x,Re-1,-Re)}let I=x-1,P=1,J=0;for(this[m+I]=f&255;--I>=0&&(P*=256);)f<0&&J===0&&this[m+I+1]!==0&&(J=1),this[m+I]=(f/P>>0)-J&255;return m+x},a.prototype.writeInt8=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,1,127,-128),f<0&&(f=255+f+1),this[m]=f&255,m+1},a.prototype.writeInt16LE=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,2,32767,-32768),this[m]=f&255,this[m+1]=f>>>8,m+2},a.prototype.writeInt16BE=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,2,32767,-32768),this[m]=f>>>8,this[m+1]=f&255,m+2},a.prototype.writeInt32LE=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,4,2147483647,-2147483648),this[m]=f&255,this[m+1]=f>>>8,this[m+2]=f>>>16,this[m+3]=f>>>24,m+4},a.prototype.writeInt32BE=function(f,m,x){return f=+f,m=m>>>0,x||$(this,f,m,4,2147483647,-2147483648),f<0&&(f=4294967295+f+1),this[m]=f>>>24,this[m+1]=f>>>16,this[m+2]=f>>>8,this[m+3]=f&255,m+4},a.prototype.writeBigInt64LE=ft(function(f,m=0){return ae(this,f,m,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=ft(function(f,m=0){return xe(this,f,m,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Se(y,f,m,x,T,I){if(m+x>y.length)throw new RangeError("Index out of range");if(m<0)throw new RangeError("Index out of range")}function F(y,f,m,x,T){return f=+f,m=m>>>0,T||Se(y,f,m,4),t.write(y,f,m,x,23,4),m+4}a.prototype.writeFloatLE=function(f,m,x){return F(this,f,m,!0,x)},a.prototype.writeFloatBE=function(f,m,x){return F(this,f,m,!1,x)};function fe(y,f,m,x,T){return f=+f,m=m>>>0,T||Se(y,f,m,8),t.write(y,f,m,x,52,8),m+8}a.prototype.writeDoubleLE=function(f,m,x){return fe(this,f,m,!0,x)},a.prototype.writeDoubleBE=function(f,m,x){return fe(this,f,m,!1,x)},a.prototype.copy=function(f,m,x,T){if(!a.isBuffer(f))throw new TypeError("argument should be a Buffer");if(x||(x=0),!T&&T!==0&&(T=this.length),m>=f.length&&(m=f.length),m||(m=0),T>0&&T<x&&(T=x),T===x||f.length===0||this.length===0)return 0;if(m<0)throw new RangeError("targetStart out of bounds");if(x<0||x>=this.length)throw new RangeError("Index out of range");if(T<0)throw new RangeError("sourceEnd out of bounds");T>this.length&&(T=this.length),f.length-m<T-x&&(T=f.length-m+x);const I=T-x;return this===f&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(m,x,T):Uint8Array.prototype.set.call(f,this.subarray(x,T),m),I},a.prototype.fill=function(f,m,x,T){if(typeof f=="string"){if(typeof m=="string"?(T=m,m=0,x=this.length):typeof x=="string"&&(T=x,x=this.length),T!==void 0&&typeof T!="string")throw new TypeError("encoding must be a string");if(typeof T=="string"&&!a.isEncoding(T))throw new TypeError("Unknown encoding: "+T);if(f.length===1){const P=f.charCodeAt(0);(T==="utf8"&&P<128||T==="latin1")&&(f=P)}}else typeof f=="number"?f=f&255:typeof f=="boolean"&&(f=Number(f));if(m<0||this.length<m||this.length<x)throw new RangeError("Out of range index");if(x<=m)return this;m=m>>>0,x=x===void 0?this.length:x>>>0,f||(f=0);let I;if(typeof f=="number")for(I=m;I<x;++I)this[I]=f;else{const P=a.isBuffer(f)?f:a.from(f,T),J=P.length;if(J===0)throw new TypeError('The value "'+f+'" is invalid for argument "value"');for(I=0;I<x-m;++I)this[I+m]=P[I%J]}return this};const le={};function L(y,f,m){le[y]=class extends m{constructor(){super(),Object.defineProperty(this,"message",{value:f.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${y}]`,this.stack,delete this.name}get code(){return y}set code(T){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:T,writable:!0})}toString(){return`${this.name} [${y}]: ${this.message}`}}}L("ERR_BUFFER_OUT_OF_BOUNDS",function(y){return y?`${y} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),L("ERR_INVALID_ARG_TYPE",function(y,f){return`The "${y}" argument must be of type number. Received type ${typeof f}`},TypeError),L("ERR_OUT_OF_RANGE",function(y,f,m){let x=`The value of "${y}" is out of range.`,T=m;return Number.isInteger(m)&&Math.abs(m)>2**32?T=me(String(m)):typeof m=="bigint"&&(T=String(m),(m>BigInt(2)**BigInt(32)||m<-(BigInt(2)**BigInt(32)))&&(T=me(T)),T+="n"),x+=` It must be ${f}. Received ${T}`,x},RangeError);function me(y){let f="",m=y.length;const x=y[0]==="-"?1:0;for(;m>=x+4;m-=3)f=`_${y.slice(m-3,m)}${f}`;return`${y.slice(0,m)}${f}`}function Y(y,f,m){we(f,"offset"),(y[f]===void 0||y[f+m]===void 0)&&ce(f,y.length-(m+1))}function se(y,f,m,x,T,I){if(y>m||y<f){const P=typeof f=="bigint"?"n":"";let J;throw f===0||f===BigInt(0)?J=`>= 0${P} and < 2${P} ** ${(I+1)*8}${P}`:J=`>= -(2${P} ** ${(I+1)*8-1}${P}) and < 2 ** ${(I+1)*8-1}${P}`,new le.ERR_OUT_OF_RANGE("value",J,y)}Y(x,T,I)}function we(y,f){if(typeof y!="number")throw new le.ERR_INVALID_ARG_TYPE(f,"number",y)}function ce(y,f,m){throw Math.floor(y)!==y?(we(y,m),new le.ERR_OUT_OF_RANGE("offset","an integer",y)):f<0?new le.ERR_BUFFER_OUT_OF_BOUNDS:new le.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${f}`,y)}const He=/[^+/0-9A-Za-z-_]/g;function Zt(y){if(y=y.split("=")[0],y=y.trim().replace(He,""),y.length<2)return"";for(;y.length%4!==0;)y=y+"=";return y}function Ct(y,f){f=f||1/0;let m;const x=y.length;let T=null;const I=[];for(let P=0;P<x;++P){if(m=y.charCodeAt(P),m>55295&&m<57344){if(!T){if(m>56319){(f-=3)>-1&&I.push(239,191,189);continue}else if(P+1===x){(f-=3)>-1&&I.push(239,191,189);continue}T=m;continue}if(m<56320){(f-=3)>-1&&I.push(239,191,189),T=m;continue}m=(T-55296<<10|m-56320)+65536}else T&&(f-=3)>-1&&I.push(239,191,189);if(T=null,m<128){if((f-=1)<0)break;I.push(m)}else if(m<2048){if((f-=2)<0)break;I.push(m>>6|192,m&63|128)}else if(m<65536){if((f-=3)<0)break;I.push(m>>12|224,m>>6&63|128,m&63|128)}else if(m<1114112){if((f-=4)<0)break;I.push(m>>18|240,m>>12&63|128,m>>6&63|128,m&63|128)}else throw new Error("Invalid code point")}return I}function hs(y){const f=[];for(let m=0;m<y.length;++m)f.push(y.charCodeAt(m)&255);return f}function Vs(y,f){let m,x,T;const I=[];for(let P=0;P<y.length&&!((f-=2)<0);++P)m=y.charCodeAt(P),x=m>>8,T=m%256,I.push(T),I.push(x);return I}function Bt(y){return e.toByteArray(Zt(y))}function dt(y,f,m,x){let T;for(T=0;T<x&&!(T+m>=f.length||T>=y.length);++T)f[T+m]=y[T];return T}function tt(y,f){return y instanceof f||y!=null&&y.constructor!=null&&y.constructor.name!=null&&y.constructor.name===f.name}function zs(y){return y!==y}const Mr=(function(){const y="0123456789abcdef",f=new Array(256);for(let m=0;m<16;++m){const x=m*16;for(let T=0;T<16;++T)f[x+T]=y[m]+y[T]}return f})();function ft(y){return typeof BigInt>"u"?Pr:y}function Pr(){throw new Error("BigInt not supported")}})(wo)),wo}var rv=iv();const nv="https://api.anam.ai",ov="/v1",Mu={client:"js-sdk",version:"4.12.0"};var av=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};const Pu="https://api.anam.ai",Io="/v1";var kt;(function(i){i.CLIENT_METRIC_MEASUREMENT_ERROR="client_error",i.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED="client_connection_closed",i.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED="client_connection_established",i.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",i.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success"})(kt||(kt={}));let Ro=Pu,ku=Io,Ht,Ou=!1;const lv=(i,e=Io)=>{Ro=i,ku=e},cv=i=>{Ht=i},hv=i=>{Ou=i};let Vt={sessionId:null,organizationId:null,attemptCorrelationId:null};const ks=i=>{Vt=Object.assign(Object.assign({},Vt),i)},as=(i,e,t)=>av(void 0,void 0,void 0,function*(){if(!Ou)try{const s=Object.assign(Object.assign({},Mu),t);Vt.sessionId&&(s.sessionId=Vt.sessionId),Vt.organizationId&&(s.organizationId=Vt.organizationId),Vt.attemptCorrelationId&&(s.attemptCorrelationId=Vt.attemptCorrelationId);const r=`${ku}/metrics/client`;let n,o={"Content-Type":"application/json"};Ht!=null&&Ht.enabled&&(Ht!=null&&Ht.baseUrl)?(n=`${Ht.baseUrl}${r}`,o["X-Anam-Target-Url"]=`${Ro}${r}`):n=`${Ro}${r}`,yield fetch(n,{method:"POST",headers:o,body:JSON.stringify({name:i,value:e,tags:s})})}catch(s){console.error("Failed to send error metric:",s)}}),uv=(i,e="console")=>{var t,s,r;const n={};i.forEach(u=>{n[u.type]||(n[u.type]=[]),n[u.type].push(u)});const o={issues:[]},a=((t=n["inbound-rtp"])===null||t===void 0?void 0:t.filter(u=>u.kind==="video"))||[];a.length>0&&(o.personaVideoStream=[],a.forEach(u=>{var p,d,g,_,b;const v={framesReceived:(p=u.framesReceived)!==null&&p!==void 0?p:"unknown",framesDropped:(d=u.framesDropped)!==null&&d!==void 0?d:"unknown",framesPerSecond:(g=u.framesPerSecond)!==null&&g!==void 0?g:"unknown",packetsReceived:(_=u.packetsReceived)!==null&&_!==void 0?_:"unknown",packetsLost:(b=u.packetsLost)!==null&&b!==void 0?b:"unknown",resolution:u.frameWidth&&u.frameHeight?`${u.frameWidth}x${u.frameHeight}`:void 0,jitter:u.jitter!==void 0?u.jitter:void 0};o.personaVideoStream.push(v)}));const l=((s=n["inbound-rtp"])===null||s===void 0?void 0:s.filter(u=>u.kind==="audio"))||[];l.length>0&&(o.personaAudioStream=[],l.forEach(u=>{var p,d,g;const _={packetsReceived:(p=u.packetsReceived)!==null&&p!==void 0?p:"unknown",packetsLost:(d=u.packetsLost)!==null&&d!==void 0?d:"unknown",audioLevel:(g=u.audioLevel)!==null&&g!==void 0?g:"unknown",jitter:u.jitter!==void 0?u.jitter:void 0,totalAudioEnergy:u.totalAudioEnergy!==void 0?u.totalAudioEnergy:void 0};o.personaAudioStream.push(_)}));const c=((r=n["outbound-rtp"])===null||r===void 0?void 0:r.filter(u=>u.kind==="audio"))||[];c.length>0&&(o.userAudioInput=[],c.forEach(u=>{var p,d;const g={packetsSent:(p=u.packetsSent)!==null&&p!==void 0?p:"unknown",retransmittedPackets:(d=u.retransmittedPacketsSent)!==null&&d!==void 0?d:void 0,avgPacketSendDelay:u.totalPacketSendDelay!==void 0?u.totalPacketSendDelay/(u.packetsSent||1)*1e3:void 0};o.userAudioInput.push(g)})),n.codec&&(o.codecs=[],n.codec.forEach(u=>{const p={status:u.payloadType?"Active":"Available",mimeType:u.mimeType||"Unknown",payloadType:u.payloadType||"N/A",clockRate:u.clockRate||void 0,channels:u.channels||void 0};o.codecs.push(p)})),n.transport&&(o.transportLayer=[],n.transport.forEach(u=>{const p={dtlsState:u.dtlsState||"unknown",iceState:u.iceState||"unknown",bytesSent:u.bytesSent||void 0,bytesReceived:u.bytesReceived||void 0};o.transportLayer.push(p)}));const h=[];if(a.forEach(u=>{typeof u.framesDropped=="number"&&u.framesDropped>0&&h.push(`Video: ${u.framesDropped} frames dropped`),typeof u.packetsLost=="number"&&u.packetsLost>0&&h.push(`Video: ${u.packetsLost} packets lost`),typeof u.framesPerSecond=="number"&&u.framesPerSecond<23&&h.push(`Video: Low frame rate (${u.framesPerSecond} fps)`)}),l.forEach(u=>{typeof u.packetsLost=="number"&&u.packetsLost>0&&h.push(`Audio: ${u.packetsLost} packets lost`),typeof u.jitter=="number"&&u.jitter>.1&&h.push(`Audio: High jitter (${(u.jitter*1e3).toFixed(1)}ms)`)}),o.issues=h,e==="json")return o;console.group("📊 WebRTC Session Statistics Report"),o.personaVideoStream&&o.personaVideoStream.length>0&&(console.group("📹 Persona Video Stream (Inbound)"),o.personaVideoStream.forEach(u=>{console.log(`Frames Received: ${u.framesReceived}`),console.log(`Frames Dropped: ${u.framesDropped}`),console.log(`Frames Per Second: ${u.framesPerSecond}`),console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),u.resolution&&console.log(`Resolution: ${u.resolution}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`)}),console.groupEnd()),o.personaAudioStream&&o.personaAudioStream.length>0&&(console.group("🔊 Persona Audio Stream (Inbound)"),o.personaAudioStream.forEach(u=>{console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),console.log(`Audio Level: ${u.audioLevel}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`),u.totalAudioEnergy!==void 0&&console.log(`Total Audio Energy: ${u.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),o.userAudioInput&&o.userAudioInput.length>0&&(console.group("🎤 User Audio Input (Outbound)"),o.userAudioInput.forEach(u=>{console.log(`Packets Sent: ${typeof u.packetsSent=="number"?u.packetsSent.toLocaleString():u.packetsSent}`),u.retransmittedPackets&&console.log(`Retransmitted Packets: ${u.retransmittedPackets}`),u.avgPacketSendDelay!==void 0&&console.log(`Avg Packet Send Delay: ${u.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),o.codecs&&o.codecs.length>0&&(console.group("🔧 Codecs Used"),o.codecs.forEach(u=>{console.log(`${u.status} ${u.mimeType} - Payload Type: ${u.payloadType}`),u.clockRate&&console.log(` Clock Rate: ${u.clockRate}Hz`),u.channels&&console.log(` Channels: ${u.channels}`)}),console.groupEnd()),o.transportLayer&&o.transportLayer.length>0&&(console.group("🚚 Transport Layer"),o.transportLayer.forEach(u=>{console.log(`DTLS State: ${u.dtlsState}`),console.log(`ICE State: ${u.iceState}`),(u.bytesReceived||u.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(u.bytesSent||0).toLocaleString()}, Received: ${(u.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),o.issues.length>0?(console.group("⚠️ Potential Issues Detected"),o.issues.forEach(u=>console.warn(u)),console.groupEnd()):console.log("✅ No significant issues detected"),console.groupEnd()};var ze;(function(i){i.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED="CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED",i.CLIENT_ERROR_CODE_SPEND_CAP_REACHED="CLIENT_ERROR_CODE_SPEND_CAP_REACHED",i.CLIENT_ERROR_CODE_VALIDATION_ERROR="CLIENT_ERROR_CODE_VALIDATION_ERROR",i.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR="CLIENT_ERROR_CODE_AUTHENTICATION_ERROR",i.CLIENT_ERROR_CODE_SERVER_ERROR="CLIENT_ERROR_CODE_SERVER_ERROR",i.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED="CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED",i.CLIENT_ERROR_CODE_SERVICE_BUSY="CLIENT_ERROR_CODE_SERVICE_BUSY",i.CLIENT_ERROR_CODE_NO_PLAN_FOUND="CLIENT_ERROR_CODE_NO_PLAN_FOUND",i.CLIENT_ERROR_CODE_UNKNOWN_ERROR="CLIENT_ERROR_CODE_UNKNOWN_ERROR",i.CLIENT_ERROR_CODE_CONFIGURATION_ERROR="CLIENT_ERROR_CODE_CONFIGURATION_ERROR"})(ze||(ze={}));class Ne extends Error{constructor(e,t,s=500,r){super(e),this.name="ClientError",this.code=t,this.statusCode=s,this.details=r,Object.setPrototypeOf(this,Ne.prototype),as(kt.CLIENT_METRIC_MEASUREMENT_ERROR,t,{details:r,statusCode:s})}}function Bu(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}function dv(i){if(!(!i||!i.enabled)){if(!i.baseUrl)return"API Gateway baseUrl is required when enabled";try{const e=new URL(i.baseUrl);if(!["http:","https:","ws:","wss:"].includes(e.protocol))return`Invalid API Gateway baseUrl protocol: ${e.protocol}. Must be http:, https:, ws:, or wss:`}catch{return`Invalid API Gateway baseUrl: ${i.baseUrl}`}if(i.wsPath&&!i.wsPath.startsWith("/"))return"API Gateway wsPath must start with /"}}var Xe;(function(i){i.OFFER="offer",i.ANSWER="answer",i.ICE_CANDIDATE="icecandidate",i.END_SESSION="endsession",i.HEARTBEAT="heartbeat",i.WARNING="warning",i.TALK_STREAM_INTERRUPTED="talkinputstreaminterrupted",i.TALK_STREAM_INPUT="talkstream",i.SESSION_READY="sessionready",i.AGENT_AUDIO_INPUT="agentaudioinput",i.AGENT_AUDIO_INPUT_END="agentaudioinputend"})(Xe||(Xe={}));var yt;(function(i){i.SPEECH_TEXT="speechText",i.CLIENT_TOOL_EVENT="clientToolEvent",i.TOOL_CALL_STARTED_EVENT="toolCallStarted",i.TOOL_CALL_COMPLETED_EVENT="toolCallCompleted",i.TOOL_CALL_FAILED_EVENT="toolCallFailed",i.REASONING_TEXT="reasoningText",i.USER_SPEECH_STARTED="userSpeechStarted",i.USER_SPEECH_ENDED="userSpeechEnded"})(yt||(yt={}));var zt;(function(i){i.PENDING="pending",i.GRANTED="granted",i.DENIED="denied",i.NOT_REQUESTED="not_requested"})(zt||(zt={}));var mr;(function(i){i.USER="user",i.PERSONA="persona"})(mr||(mr={}));var te;(function(i){i.MESSAGE_HISTORY_UPDATED="MESSAGE_HISTORY_UPDATED",i.MESSAGE_STREAM_EVENT_RECEIVED="MESSAGE_STREAM_EVENT_RECEIVED",i.CONNECTION_ESTABLISHED="CONNECTION_ESTABLISHED",i.CONNECTION_CLOSED="CONNECTION_CLOSED",i.INPUT_AUDIO_STREAM_STARTED="INPUT_AUDIO_STREAM_STARTED",i.VIDEO_STREAM_STARTED="VIDEO_STREAM_STARTED",i.VIDEO_PLAY_STARTED="VIDEO_PLAY_STARTED",i.AUDIO_STREAM_STARTED="AUDIO_STREAM_STARTED",i.TALK_STREAM_INTERRUPTED="TALK_STREAM_INTERRUPTED",i.SESSION_READY="SESSION_READY",i.SERVER_WARNING="SERVER_WARNING",i.MIC_PERMISSION_PENDING="MIC_PERMISSION_PENDING",i.MIC_PERMISSION_GRANTED="MIC_PERMISSION_GRANTED",i.MIC_PERMISSION_DENIED="MIC_PERMISSION_DENIED",i.INPUT_AUDIO_DEVICE_CHANGED="INPUT_AUDIO_DEVICE_CHANGED",i.CLIENT_TOOL_EVENT_RECEIVED="CLIENT_TOOL_EVENT_RECEIVED",i.TOOL_CALL_STARTED="TOOL_CALL_STARTED",i.TOOL_CALL_COMPLETED="TOOL_CALL_COMPLETED",i.TOOL_CALL_FAILED="TOOL_CALL_FAILED",i.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",i.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED",i.USER_SPEECH_STARTED="USER_SPEECH_STARTED",i.USER_SPEECH_ENDED="USER_SPEECH_ENDED"})(te||(te={}));var Ue;(function(i){i.WEB_SOCKET_OPEN="WEB_SOCKET_OPEN",i.SIGNAL_MESSAGE_RECEIVED="SIGNAL_MESSAGE_RECEIVED",i.WEBRTC_CHAT_MESSAGE_RECEIVED="WEBRTC_CHAT_MESSAGE_RECEIVED",i.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED="WEBRTC_CLIENT_TOOL_EVENT_RECEIVED",i.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED",i.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED",i.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED",i.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED"})(Ue||(Ue={}));var $t;(function(i){i.NORMAL="CONNECTION_CLOSED_CODE_NORMAL",i.MICROPHONE_PERMISSION_DENIED="CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED",i.SIGNALLING_CLIENT_CONNECTION_FAILURE="CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE",i.WEBRTC_FAILURE="CONNECTION_CLOSED_CODE_WEBRTC_FAILURE",i.SERVER_CLOSED_CONNECTION="CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION"})($t||($t={}));class fv{constructor(e,t){this.sequenceNumber=0,this.config=e,this.signallingClient=t}sendAudioChunk(e){const s={audioData:typeof e=="string"?e:this.arrayBufferToBase64(e),encoding:this.config.encoding,sampleRate:this.config.sampleRate,channels:this.config.channels,sequenceNumber:this.sequenceNumber++};this.signallingClient.sendAgentAudioInput(s)}endSequence(){this.signallingClient.sendAgentAudioInputEnd(),this.sequenceNumber=0}getSequenceNumber(){return this.sequenceNumber}getConfig(){return this.config}arrayBufferToBase64(e){const t=e instanceof Uint8Array?e:new Uint8Array(e),s=Array.from(t,r=>String.fromCharCode(r)).join("");return btoa(s)}}var Os=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};const pv=5,mv=5;class gv{constructor(e,t,s,r,n){var o,a,l,c,h;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.heartBeatIntervalRef=null,this.publicEventEmitter=s,this.internalEventEmitter=r,this.apiGatewayConfig=n,!e)throw new Error("Signalling Client: sessionId is required");this.sessionId=e;const{heartbeatIntervalSeconds:u,maxWsReconnectionAttempts:p,url:d}=t;if(this.heartbeatIntervalSeconds=u||pv,this.maxWsReconnectionAttempts=p||mv,!d.baseUrl)throw new Error("Signalling Client: baseUrl is required");if(!((o=this.apiGatewayConfig)===null||o===void 0)&&o.enabled&&(!((a=this.apiGatewayConfig)===null||a===void 0)&&a.baseUrl)){const g=new URL(this.apiGatewayConfig.baseUrl),_=(l=this.apiGatewayConfig.wsPath)!==null&&l!==void 0?l:"/ws";g.protocol=g.protocol.replace("http","ws"),g.pathname=_,this.url=g;const b=d.protocol||"https",v=b==="http"?"ws":"wss",C=`${b}://${d.baseUrl}`,E=(c=d.signallingPath)!==null&&c!==void 0?c:"/ws",S=new URL(C);S.protocol=v==="ws"?"ws:":"wss:",d.port&&(S.port=d.port),S.pathname=E,S.searchParams.append("session_id",e),this.url.searchParams.append("target_url",S.href)}else{const _=`${d.protocol||"https"}://${d.baseUrl}`;this.url=new URL(_),this.url.protocol=d.protocol==="http"?"ws:":"wss:",d.port&&(this.url.port=d.port),this.url.pathname=(h=d.signallingPath)!==null&&h!==void 0?h:"/ws",this.url.searchParams.append("session_id",e)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){return this.socket=new WebSocket(this.url.href),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.socket}sendOffer(e){return Os(this,void 0,void 0,function*(){const t={connectionDescription:e,userUid:this.sessionId},s={actionType:Xe.OFFER,sessionId:this.sessionId,payload:t};this.sendSignalMessage(s)})}sendIceCandidate(e){return Os(this,void 0,void 0,function*(){const t={actionType:Xe.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(t)})}sendSignalMessage(e){var t;if(((t=this.socket)===null||t===void 0?void 0:t.readyState)===WebSocket.OPEN)try{this.socket.send(JSON.stringify(e))}catch(s){console.error("SignallingClient - sendSignalMessage: error sending message",s)}else this.sendingBuffer.push(e)}sendTalkMessage(e){return Os(this,void 0,void 0,function*(){const t={actionType:Xe.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)})}sendAgentAudioInput(e){const t={actionType:Xe.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)}sendAgentAudioInputEnd(){const e={actionType:Xe.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(e)}closeSocket(){this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(){return Os(this,void 0,void 0,function*(){if(!this.socket)throw new Error("SignallingClient - onOpen: socket is null");try{this.wsConnectionAttempts=0,this.flushSendingBuffer(),this.socket.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(Ue.WEB_SOCKET_OPEN)}catch(e){console.error("SignallingClient - onOpen: error in onOpen",e),this.publicEventEmitter.emit(te.CONNECTION_CLOSED,$t.SIGNALLING_CLIENT_CONNECTION_FAILURE)}})}onClose(){return Os(this,void 0,void 0,function*(){this.wsConnectionAttempts+=1,!this.stopSignal&&(this.wsConnectionAttempts<=this.maxWsReconnectionAttempts?(this.socket=null,setTimeout(()=>{this.connect()},100*this.wsConnectionAttempts)):(this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.publicEventEmitter.emit(te.CONNECTION_CLOSED,$t.SIGNALLING_CLIENT_CONNECTION_FAILURE)))})}onError(e){this.stopSignal||console.error("SignallingClient - onError: ",e)}flushSendingBuffer(){const e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(t=>{var s;((s=this.socket)===null||s===void 0?void 0:s.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(t)):e.push(t)}),this.sendingBuffer=e}onMessage(e){return Os(this,void 0,void 0,function*(){const t=JSON.parse(e.data);this.internalEventEmitter.emit(Ue.SIGNAL_MESSAGE_RECEIVED,t)})}startSendingHeartBeats(){if(!this.socket)throw new Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");const e=this.heartbeatIntervalSeconds*1e3,t={actionType:Xe.HEARTBEAT,sessionId:this.sessionId,payload:""},s=JSON.stringify(t);this.heartBeatIntervalRef=setInterval(()=>{var r;this.stopSignal||((r=this.socket)===null||r===void 0?void 0:r.readyState)===WebSocket.OPEN&&this.socket.send(s)},e)}}function _v(i){return"brainType"in i||"llmId"in i}var Du=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};class yv{constructor(e,t,s){if(!e&&!t)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=t||null,this.baseUrl=(s==null?void 0:s.baseUrl)||nv,this.apiVersion=(s==null?void 0:s.apiVersion)||ov,this.apiGatewayConfig=(s==null?void 0:s.apiGateway)||void 0}buildGatewayUrlAndHeaders(e,t){var s,r;if(!((s=this.apiGatewayConfig)===null||s===void 0)&&s.enabled&&(!((r=this.apiGatewayConfig)===null||r===void 0)&&r.baseUrl)){const n=`${this.apiGatewayConfig.baseUrl}${e}`,o=new URL(`${this.baseUrl}${e}`),a=Object.assign(Object.assign({},t),{"X-Anam-Target-Url":o.href});return{url:n,headers:a}}else return{url:`${this.baseUrl}${e}`,headers:t}}startSession(e,t){return Du(this,void 0,void 0,function*(){if(!this.sessionToken){if(!e)throw new Ne("Persona configuration must be provided when using apiKey",ze.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(e)}e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");try{const s=`${this.apiVersion}/engine/session`,{url:r,headers:n}=this.buildGatewayUrlAndHeaders(s,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),o=yield fetch(r,{method:"POST",headers:n,body:JSON.stringify({personaConfig:e,sessionOptions:t,clientMetadata:Mu})}),a=yield o.json(),l=a.error;switch(o.status){case 200:case 201:return a;case 400:throw new Ne("Invalid request to start session",ze.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:a.message});case 401:throw new Ne("Authentication failed when starting session",ze.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:a.message});case 402:throw new Ne("Please sign up for a plan to start a session",ze.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:a.message});case 403:throw new Ne("Authentication failed when starting session",ze.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:a.message});case 429:throw l==="Concurrent session limit reached"?new Ne("Concurrency limit reached, please upgrade your plan",ze.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:a.message}):l==="Spend cap reached"?new Ne("Spend cap reached, please upgrade your plan",ze.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:a.message}):new Ne("Usage limit reached, please upgrade your plan",ze.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:a.message});case 503:throw new Ne("There are no available personas, please try again later",ze.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:a.message});default:throw new Ne("Unknown error when starting session",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:a.message})}}catch(s){throw s instanceof Ne?s:new Ne("Failed to start session",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:s instanceof Error?s.message:String(s)})}})}unsafe_getSessionToken(e){return Du(this,void 0,void 0,function*(){if(console.warn("Using unsecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let t={clientLabel:"js-sdk-api-key"};_v(e)&&(t=Object.assign(Object.assign({},t),{personaConfig:e}));try{const s=`${this.apiVersion}/auth/session-token`,{url:r,headers:n}=this.buildGatewayUrlAndHeaders(s,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`});return(yield(yield fetch(r,{method:"POST",headers:n,body:JSON.stringify(t)})).json()).sessionToken}catch{throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}var bv=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};class vv{constructor(e,t,s){this.baseUrl=e,this.sessionId=t,this.apiGatewayConfig=s}sendTalkCommand(e){return bv(this,void 0,void 0,function*(){var t,s;try{let r,n={"Content-Type":"application/json"};const o="/talk",a=`?session_id=${this.sessionId}`;if(!((t=this.apiGatewayConfig)===null||t===void 0)&&t.enabled&&(!((s=this.apiGatewayConfig)===null||s===void 0)&&s.baseUrl)){r=`${this.apiGatewayConfig.baseUrl}${o}${a}`;const c=new URL(`${this.baseUrl}${o}${a}`);n["X-Anam-Target-Url"]=c.href}else r=`${this.baseUrl}${o}${a}`;const l=yield fetch(r,{method:"POST",headers:n,body:JSON.stringify({content:e})});if(!l.ok)throw new Error(`Failed to send talk command: ${l.status} ${l.statusText}`)}catch(r){throw console.error(r),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}class xv{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach(s=>{s(...t)})}}class Cv{constructor(e,t){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(Ue.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,role:e.role,endOfSpeech:e.end_of_speech,interrupted:e.interrupted}}processUserMessage(e){const t={id:e.id,content:e.content,role:e.role};this.messages.push(t)}processPersonaMessage(e){const t={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},s=this.messages.findIndex(r=>r.id===t.id);if(s!==-1){const r=this.messages[s];this.messages[s]=Object.assign(Object.assign({},r),{content:r.content+t.content,interrupted:r.interrupted||t.interrupted})}else this.messages.push(t)}processWebRtcTextMessageEvent(e){const t=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(te.MESSAGE_STREAM_EVENT_RECEIVED,t),t.role){case mr.USER:this.processUserMessage(t);break;case mr.PERSONA:this.processPersonaMessage(t);break}t.endOfSpeech&&this.publicEventEmitter.emit(te.MESSAGE_HISTORY_UPDATED,this.messages)}}class Ev{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){if(e===te.CONNECTION_ESTABLISHED&&as(kt.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===te.CONNECTION_CLOSED){const[s,r]=t;as(kt.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,s,r?{details:r}:void 0)}this.listeners[e]&&this.listeners[e].forEach(s=>{s(...t)})}}var Ke;(function(i){i[i.UNSTARTED=0]="UNSTARTED",i[i.STREAMING=1]="STREAMING",i[i.INTERRUPTED=2]="INTERRUPTED",i[i.ENDED=3]="ENDED"})(Ke||(Ke={}));var Mo=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};class Sv{constructor(e,t,s){this.state=Ke.UNSTARTED,this.correlationId=e,this.internalEventEmitter=t,this.signallingClient=s,this.internalEventEmitter.addListener(Ue.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(Ue.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return Mo(this,void 0,void 0,function*(){e.actionType===Xe.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=Ke.INTERRUPTED,this.onDeactivate())})}endMessage(){return Mo(this,void 0,void 0,function*(){if(this.state===Ke.ENDED){console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");return}if(this.state!==Ke.STREAMING){console.warn("Talk stream is not active state: "+this.state);return}const e={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(e),this.state=Ke.ENDED,this.onDeactivate()})}streamMessageChunk(e,t){return Mo(this,void 0,void 0,function*(){if(this.state!==Ke.STREAMING&&this.state!==Ke.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const s={content:e,startOfSpeech:this.state===Ke.UNSTARTED,endOfSpeech:t,correlationId:this.correlationId};this.state=t?Ke.ENDED:Ke.STREAMING,this.state===Ke.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(s)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===Ke.STREAMING||this.state===Ke.UNSTARTED}getState(){return this.state}}var Po=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};const Nu=(i,e)=>{if(isNaN(i)||isNaN(e))return 0;const t=e-i;return t>0?t:0};class Uu{constructor(e){this.handlers=Object.create(null),this.pendingCalls=Object.create(null),this.publicEventEmitter=e}clearPendingCalls(){this.pendingCalls=Object.create(null)}registerHandler(e,t){return this.handlers[e]=t,()=>{delete this.handlers[e]}}processToolCallStartedEvent(e){return Po(this,void 0,void 0,function*(){const{tool_name:t,timestamp:s}=e,r=this.WebRTCToolCallStartedEventToToolCallStartedPayload(e),n=new Date(s);if(this.pendingCalls[e.tool_call_id]={payload:r,timestamp:n.getTime()},!(t in this.handlers))return;const o=this.handlers[t];if(o.onStart)try{let a=yield o.onStart(r);if(e.tool_type==="client"){yield this.processToolCallCompletedEvent(Object.assign(Object.assign({},e),{result:a,timestamp:new Date().toISOString()}));return}}catch(a){a instanceof Error?yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${a.message}`,timestamp:new Date().toISOString()})):yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${String(a)}`,timestamp:new Date().toISOString()}));return}})}processToolCallCompletedEvent(e){return Po(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:s,timestamp:r}=e,n=this.webRTCToolCallCompletedEventToToolCallCompletedPayload(e);if(s in this.pendingCalls&&delete this.pendingCalls[s],!(t in this.handlers))return;const o=this.handlers[t];if(o.onComplete){e.tool_type==="client"&&this.publicEventEmitter.emit(te.TOOL_CALL_COMPLETED,n);try{yield o.onComplete(n)}catch(a){console.error(`Error in onComplete handler for tool ${t}:`,a);return}}})}processToolCallFailedEvent(e){return Po(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:s,timestamp:r}=e,n=this.webRTCToolCallFailedEventToToolCallFailedPayload(e);if(s in this.pendingCalls&&delete this.pendingCalls[s],!(t in this.handlers))return;const o=this.handlers[t];if(o.onFail){e.tool_type==="client"&&this.publicEventEmitter.emit(te.TOOL_CALL_FAILED,n);try{yield o.onFail(n)}catch(a){console.error(`Error in onFail handler for tool ${t}:`,a);return}}})}static WebRTCClientToolEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.event_name,eventData:e.event_data,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}static WebRTCToolCallStartedEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.tool_name,eventData:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}WebRTCToolCallStartedEventToToolCallStartedPayload(e){return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,arguments:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallCompletedEventToToolCallCompletedPayload(e){const t=new Date(e.timestamp),s=this.pendingCalls[e.tool_call_id],r=s?Nu(s.timestamp,t.getTime()):0;return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,result:e.result,executionTime:r>0?r:0,timestamp:e.timestamp,documentsAccessed:e.documents_accessed,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallFailedEventToToolCallFailedPayload(e){const t=new Date(e.timestamp),s=this.pendingCalls[e.tool_call_id],r=s?Nu(s.timestamp,t.getTime()):0;return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,errorMessage:e.error_message,executionTime:r>0?r:0,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}var it=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};const Tv=15e3,Av=5e3,wv=2;class Iv{constructor(e,t,s,r,n){var o,a,l,c;this.peerConnection=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:zt.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.publicEventEmitter=s,this.internalEventEmitter=r,this.toolCallManager=n,this.apiGatewayConfig=t.apiGateway;const{inputAudio:h}=t;this.inputAudioState=h.inputAudioState,t.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=t.inputAudio.userProvidedMediaStream),this.disableInputAudio=t.inputAudio.disableInputAudio===!0,this.internalEventEmitter.addListener(Ue.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(Ue.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.internalEventEmitter.addListener(Ue.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,this.toolCallManager.processToolCallStartedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(Ue.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,this.toolCallManager.processToolCallCompletedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(Ue.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,this.toolCallManager.processToolCallFailedEvent.bind(this.toolCallManager)),this.iceServers=t.iceServers,this.signallingClient=new gv(e,t.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig),this.engineApiRestClient=new vv(t.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=t.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=(a=(o=t.metrics)===null||o===void 0?void 0:o.showPeerConnectionStatsReport)!==null&&a!==void 0?a:!1,this.peerConnectionStatsReportOutputFormat=(c=(l=t.metrics)===null||l===void 0?void 0:l.peerConnectionStatsReportOutputFormat)!==null&&c!==void 0?c:"console"}onInputAudioStateChange(e,t){e.isMuted!==t.isMuted&&(t.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(t=>{t.enabled=!1})}unmuteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(t=>{t.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>it(this,void 0,void 0,function*(){if(!(!this.peerConnection||!this.dataChannel||this.dataChannel.readyState!=="open"))try{const e=yield this.peerConnection.getStats();this.sendClientSideMetrics(e)}catch(e){console.error("Failed to collect and send stats:",e)}}),Av))}sendClientSideMetrics(e){e.forEach(t=>{if(t.type==="inbound-rtp"){const s={message_type:"remote_rtp_stats",data:t};this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(JSON.stringify(s))}})}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const e=setTimeout(()=>{this.successMetricPoller&&(console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},Tv);this.successMetricPoller=setInterval(()=>it(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired){this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e);return}try{const t=yield this.peerConnection.getStats();let s=!1,r=null;t.forEach(n=>{n.type==="inbound-rtp"&&n.kind==="video"&&(n.framesDecoded!==void 0&&n.framesDecoded>0?(s=!0,r="framesDecoded"):n.framesReceived!==void 0&&n.framesReceived>0?(s=!0,r="framesReceived"):n.bytesReceived>0&&n.packetsReceived>0&&n.bytesReceived>1e5&&(s=!0,r="bytesReceived"))}),s&&!this.successMetricFired&&(this.successMetricFired=!0,as(kt.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",r?{detectionMethod:r}:void 0),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e),this.successMetricPoller=null)}catch{}}),500)}muteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}unmuteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(e){return it(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");if(e==null)throw new Error("StreamingClient - changeAudioInputDevice: deviceId is required");const t=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(r=>{r.stop()});const s={echoCancellation:!0,deviceId:{exact:e}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:s}),this.audioDeviceId=e,yield this.setupAudioTrack(),t&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(te.INPUT_AUDIO_DEVICE_CHANGED,e)}catch(s){throw console.error("Failed to change audio input device:",s),new Error(`StreamingClient - changeAudioInputDevice: ${s instanceof Error?s.message:String(s)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}sendDataMessage(e){this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(e)}setMediaStreamTargetById(e){if(e){const t=document.getElementById(e);if(!t)throw new Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=t}}startConnection(){try{if(this.peerConnection){console.error("StreamingClient - startConnection: peer connection already exists");return}this.signallingClient.connect()}catch(e){console.error("StreamingClient - startConnection: error",e),this.handleWebrtcFailure(e)}}stopConnection(){return it(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return it(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - sendTalkCommand: peer connection is null");yield this.engineApiRestClient.sendTalkCommand(e)})}startTalkMessageStream(e){return e||(e=Math.random().toString(36).substring(2,15)),new Sv(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new fv(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return it(this,void 0,void 0,function*(){this.peerConnection=new RTCPeerConnection({iceServers:this.iceServers,iceCandidatePoolSize:wv}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?this.peerConnection.addTransceiver("audio",{direction:"recvonly"}):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?yield this.setupAudioTrack():this.requestMicrophonePermissionAsync().catch(e=>{console.error("Async microphone permission request failed:",e)}))})}onSignalMessage(e){return it(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");return}switch(e.actionType){case Xe.ANSWER:const t=e.payload;yield this.peerConnection.setRemoteDescription(t),this.connectionReceivedAnswer=!0,this.flushRemoteIceCandidateBuffer();break;case Xe.ICE_CANDIDATE:const s=e.payload,r=new RTCIceCandidate(s);this.connectionReceivedAnswer?yield this.peerConnection.addIceCandidate(r):this.remoteIceCandidateBuffer.push(r);break;case Xe.END_SESSION:const n=e.payload;this.publicEventEmitter.emit(te.CONNECTION_CLOSED,$t.SERVER_CLOSED_CONNECTION,n),this.shutdown();break;case Xe.WARNING:const o=e.payload;console.warn("Warning received from server: "+o),this.publicEventEmitter.emit(te.SERVER_WARNING,o);break;case Xe.TALK_STREAM_INTERRUPTED:const a=e.payload;this.publicEventEmitter.emit(te.TALK_STREAM_INTERRUPTED,a.correlationId);break;case Xe.SESSION_READY:const l=e.sessionId;this.publicEventEmitter.emit(te.SESSION_READY,l);break;case Xe.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your anam-sdk version up to date?",e)}})}onSignallingClientConnected(){return it(this,void 0,void 0,function*(){if(!this.peerConnection)try{yield this.initPeerConnectionAndSendOffer()}catch(e){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",e),this.handleWebrtcFailure(e)}})}flushRemoteIceCandidateBuffer(){this.remoteIceCandidateBuffer.forEach(e=>{var t;(t=this.peerConnection)===null||t===void 0||t.addIceCandidate(e)}),this.remoteIceCandidateBuffer=[]}onIceCandidate(e){e.candidate&&this.signallingClient.sendIceCandidate(e.candidate)}onIceConnectionStateChange(){var e,t;(((e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState)==="connected"||((t=this.peerConnection)===null||t===void 0?void 0:t.iceConnectionState)==="completed")&&(this.publicEventEmitter.emit(te.CONNECTION_ESTABLISHED),this.startStatsCollection())}onConnectionStateChange(){var e;((e=this.peerConnection)===null||e===void 0?void 0:e.connectionState)==="closed"&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(e){console.error({message:"StreamingClient - handleWebrtcFailure: ",err:e}),e.name==="NotAllowedError"&&e.message==="Permission denied"?this.publicEventEmitter.emit(te.CONNECTION_CLOSED,$t.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(te.CONNECTION_CLOSED,$t.WEBRTC_FAILURE);try{this.stopConnection()}catch(t){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",t)}}onTrackEventHandler(e){if(e.track.kind==="video"){if(this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(te.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const t=this.videoElement.requestVideoFrameCallback(()=>{var s;(s=this.videoElement)===null||s===void 0||s.cancelVideoFrameCallback(t),this.publicEventEmitter.emit(te.VIDEO_PLAY_STARTED),this.successMetricFired||(this.successMetricFired=!0,as(kt.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:"videoElement"}))})}}else e.track.kind==="audio"&&(this.audioStream=e.streams[0],this.publicEventEmitter.emit(te.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return it(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - setupDataChannels: peer connection is not initialized");return}if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");const e=this.peerConnection.createDataChannel("session",{ordered:!0});e.onopen=()=>{this.dataChannel=e??null},e.onclose=()=>{},e.onmessage=t=>{var s,r,n,o;try{const a=JSON.parse(t.data);switch(a.messageType){case yt.SPEECH_TEXT:this.internalEventEmitter.emit(Ue.WEBRTC_CHAT_MESSAGE_RECEIVED,a.data);break;case yt.CLIENT_TOOL_EVENT:const l=a.data;this.internalEventEmitter.emit(Ue.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,l);const c=Uu.WebRTCClientToolEventToClientToolEvent(l);this.publicEventEmitter.emit(te.CLIENT_TOOL_EVENT_RECEIVED,c);break;case yt.TOOL_CALL_STARTED_EVENT:const h=a.data;this.publicEventEmitter.emit(te.TOOL_CALL_STARTED,this.toolCallManager.WebRTCToolCallStartedEventToToolCallStartedPayload(h)),this.internalEventEmitter.emit(Ue.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,h);break;case yt.TOOL_CALL_COMPLETED_EVENT:const u=a.data;this.publicEventEmitter.emit(te.TOOL_CALL_COMPLETED,this.toolCallManager.webRTCToolCallCompletedEventToToolCallCompletedPayload(u)),this.internalEventEmitter.emit(Ue.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,u);break;case yt.TOOL_CALL_FAILED_EVENT:const p=a.data;this.publicEventEmitter.emit(te.TOOL_CALL_FAILED,this.toolCallManager.webRTCToolCallFailedEventToToolCallFailedPayload(p)),this.internalEventEmitter.emit(Ue.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,p);break;case yt.REASONING_TEXT:this.internalEventEmitter.emit(Ue.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,a.data);break;case yt.USER_SPEECH_STARTED:this.publicEventEmitter.emit(te.USER_SPEECH_STARTED,(r=(s=a.data)===null||s===void 0?void 0:s.user_action_correlation_id)!==null&&r!==void 0?r:"unknown");break;case yt.USER_SPEECH_ENDED:this.publicEventEmitter.emit(te.USER_SPEECH_ENDED,(o=(n=a.data)===null||n===void 0?void 0:n.user_action_correlation_id)!==null&&o!==void 0?o:"unknown");break;default:break}}catch(a){console.error("Failed to parse data channel message:",a)}}})}requestMicrophonePermissionAsync(){return it(this,void 0,void 0,function*(){if(this.inputAudioState.permissionState!==zt.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:zt.PENDING}),this.publicEventEmitter.emit(te.MIC_PERMISSION_PENDING);try{const e={echoCancellation:!0};this.audioDeviceId&&(e.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:e}),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:zt.GRANTED}),this.publicEventEmitter.emit(te.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(e){console.error("Failed to get microphone permission:",e),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:zt.DENIED});const t=e instanceof Error?e.message:String(e);this.publicEventEmitter.emit(te.MIC_PERMISSION_DENIED,t)}}})}setupAudioTrack(){return it(this,void 0,void 0,function*(){if(!this.peerConnection||!this.inputAudioStream)return;if(!this.inputAudioStream.getAudioTracks().length){console.error("StreamingClient - setupAudioTrack: stream does not have audio tracks");return}this.inputAudioState.isMuted&&this.muteAllAudioTracks();const e=this.inputAudioStream.getAudioTracks()[0],s=this.peerConnection.getSenders().find(r=>{var n;return((n=r.track)===null||n===void 0?void 0:n.kind)==="audio"||r.track===null&&r.dtmf!==null});if(s)try{yield s.replaceTrack(e)}catch(r){console.error("Failed to replace audio track:",r),this.peerConnection.addTrack(e,this.inputAudioStream)}else this.peerConnection.addTrack(e,this.inputAudioStream);this.publicEventEmitter.emit(te.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return it(this,void 0,void 0,function*(){if(yield this.initPeerConnection(),!this.peerConnection){console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized");return}try{const e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e)}catch(e){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",e)}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription)})}shutdown(){return it(this,void 0,void 0,function*(){var e;if(this.showPeerConnectionStatsReport){const t=yield(e=this.peerConnection)===null||e===void 0?void 0:e.getStats();if(t){const s=uv(t,this.peerConnectionStatsReportOutputFormat);s&&console.log(s,void 0,2)}}this.statsCollectionInterval&&(clearInterval(this.statsCollectionInterval),this.statsCollectionInterval=null),this.successMetricPoller&&(clearInterval(this.successMetricPoller),this.successMetricPoller=null),this.successMetricFired=!1;try{this.inputAudioStream&&this.inputAudioStream.getTracks().forEach(t=>{t.stop()}),this.inputAudioStream=null}catch(t){console.error("StreamingClient - shutdown: error stopping input audio stream",t)}try{this.signallingClient.stop()}catch(t){console.error("StreamingClient - shutdown: error stopping signallilng",t)}this.toolCallManager.clearPendingCalls();try{this.peerConnection&&this.peerConnection.connectionState!=="closed"&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(t){console.error("StreamingClient - shutdown: error closing peer connection",t)}})}}class Rv{constructor(e,t){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(Ue.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,endOfThought:e.end_of_thought,role:e.role}}processWebRtcReasoningTextMessageEvent(e){const t=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(te.REASONING_STREAM_EVENT_RECEIVED,t);const s={id:t.id,content:t.content,role:t.role},r=this.reasoning_messages.findIndex(n=>n.id===s.id);if(r!==-1){const n=this.reasoning_messages[r];n.content+=s.content,this.reasoning_messages[r]=n}else this.reasoning_messages.push(s);t.endOfThought&&this.publicEventEmitter.emit(te.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}var jt=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};class Mv{constructor(e,t,s){var r,n,o,a,l;this.inputAudioState={isMuted:!1,permissionState:zt.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const c=this.validateClientConfig(e,t,s);if(c)throw new Ne(c,ze.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=t,this.clientOptions=s,(!((r=s==null?void 0:s.api)===null||r===void 0)&&r.baseUrl||!((n=s==null?void 0:s.api)===null||n===void 0)&&n.apiVersion)&&lv(s.api.baseUrl||Pu,s.api.apiVersion||Io),!((a=(o=s==null?void 0:s.api)===null||o===void 0?void 0:o.apiGateway)===null||a===void 0)&&a.enabled&&cv(s.api.apiGateway),!((l=s==null?void 0:s.metrics)===null||l===void 0)&&l.disableClientMetrics&&hv(!0),this.publicEventEmitter=new Ev,this.internalEventEmitter=new xv,this.toolCallManager=new Uu(this.publicEventEmitter),this.apiClient=new yv(e,s==null?void 0:s.apiKey,s==null?void 0:s.api),this.messageHistoryClient=new Cv(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new Rv(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const t=e.split(".")[1],s=rv.Buffer.from(t,"base64").toString("utf8");return JSON.parse(s)}catch{throw new Error("Invalid session token format")}}validateClientConfig(e,t,s){var r,n;if(!e&&!(s!=null&&s.apiKey))return"Either sessionToken or apiKey must be provided";if(s!=null&&s.apiKey&&e)return"Only one of sessionToken or apiKey should be used";const o=dv((r=s==null?void 0:s.api)===null||r===void 0?void 0:r.apiGateway);if(o)return o;if(e){const a=this.decodeJwt(e);this.organizationId=a.accountId,ks({organizationId:this.organizationId});const l=(n=a.type)===null||n===void 0?void 0:n.toLowerCase();if(l==="legacy")return"Legacy session tokens are no longer supported. Please define your persona when creating your session token. See https://docs.anam.ai/resources/migrating-legacy for more information.";if((l==="ephemeral"||l==="stateful")&&t)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!t)return"Missing persona config. Persona configuration must be provided when using apiKey";if(s!=null&&s.voiceDetection){if(s.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(s.voiceDetection.endOfSpeechSensitivity!==void 0){if(typeof s.voiceDetection.endOfSpeechSensitivity!="number")return"End of speech sensitivity must be a number";if(s.voiceDetection.endOfSpeechSensitivity<0||s.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var e;const t={};if(!((e=this.clientOptions)===null||e===void 0)&&e.voiceDetection&&(t.voiceDetection=this.clientOptions.voiceDetection),Object.keys(t).length!==0)return t}startSession(e){return jt(this,void 0,void 0,function*(){var t,s,r,n,o,a,l,c,h,u,p,d;const g=this.personaConfig,_=this.buildStartSessionOptionsForClient(),b=yield this.apiClient.startSession(g,_),{sessionId:v,clientConfig:C,engineHost:E,engineProtocol:S,signallingEndpoint:w}=b,{heartbeatIntervalSeconds:R,maxWsReconnectionAttempts:M,iceServers:D}=C;this.sessionId=v,ks({sessionId:this.sessionId});const G=!((t=this.clientOptions)===null||t===void 0)&&t.iceServers?this.clientOptions.iceServers:D;try{this.streamingClient=new Iv(v,{engine:{baseUrl:`${S}://${E}`},signalling:{heartbeatIntervalSeconds:R,maxWsReconnectionAttempts:M,url:{baseUrl:E,protocol:S,signallingPath:w}},iceServers:G,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:!((s=this.clientOptions)===null||s===void 0)&&s.disableInputAudio?void 0:e,audioDeviceId:(r=this.clientOptions)===null||r===void 0?void 0:r.audioDeviceId,disableInputAudio:(n=this.clientOptions)===null||n===void 0?void 0:n.disableInputAudio},apiGateway:(a=(o=this.clientOptions)===null||o===void 0?void 0:o.api)===null||a===void 0?void 0:a.apiGateway,metrics:{showPeerConnectionStatsReport:(h=(c=(l=this.clientOptions)===null||l===void 0?void 0:l.metrics)===null||c===void 0?void 0:c.showPeerConnectionStatsReport)!==null&&h!==void 0?h:!1,peerConnectionStatsReportOutputFormat:(d=(p=(u=this.clientOptions)===null||u===void 0?void 0:u.metrics)===null||p===void 0?void 0:p.peerConnectionStatsReportOutputFormat)!==null&&d!==void 0?d:"console"}},this.publicEventEmitter,this.internalEventEmitter,this.toolCallManager)}catch(k){throw ks({sessionId:null}),new Ne("Failed to initialize streaming client",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:k instanceof Error?k.message:String(k),sessionId:v})}return v})}startSessionIfNeeded(e){return jt(this,void 0,void 0,function*(){if((!this.sessionId||!this.streamingClient)&&(yield this.startSession(e),!this.sessionId||!this.streamingClient))throw new Ne("Session ID or streaming client is not available after starting session",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return jt(this,void 0,void 0,function*(){var t;if(this._isStreaming)throw new Error("Already streaming");const s=Bu();return ks({attemptCorrelationId:s,sessionId:null}),as(kt.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio&&e&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored."),yield this.startSessionIfNeeded(e),this._isStreaming=!0,new Promise(r=>{var n;const o=[];let a=!1,l=!1;this.publicEventEmitter.addListener(te.VIDEO_STREAM_STARTED,c=>{o.push(c),a=!0,l&&r(o)}),this.publicEventEmitter.addListener(te.AUDIO_STREAM_STARTED,c=>{o.push(c),l=!0,a&&r(o)}),(n=this.streamingClient)===null||n===void 0||n.startConnection()})})}streamToVideoAndAudioElements(e,t,s){return jt(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(e,s)})}streamToVideoElement(e,t){return jt(this,void 0,void 0,function*(){var s;const r=Bu();ks({attemptCorrelationId:r,sessionId:null}),as(kt.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((s=this.clientOptions)===null||s===void 0)&&s.disableInputAudio&&t&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(t)}catch(n){throw n instanceof Ne?n:new Ne("Failed to start session",ze.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:n instanceof Error?n.message:String(n),sessionId:this.sessionId})}if(this._isStreaming)throw new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw new Error("Failed to stream: streaming client is not available");this.streamingClient.setMediaStreamTargetById(e),this.streamingClient.startConnection()})}talk(e){return jt(this,void 0,void 0,function*(){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(e)})}sendDataMessage(e){if(this.streamingClient)this.streamingClient.sendDataMessage(e);else throw new Error("Failed to send message: session is not started.")}sendUserMessage(e){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to send user message: no active session");const s=new Date().toISOString().replace("Z",""),r=JSON.stringify({content:e,timestamp:s,session_id:t,message_type:"speech"});this.sendDataMessage(r)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to send interrupt command: no active session");const t=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:new Date().toISOString()});this.sendDataMessage(t)}addContext(e){if(!this._isStreaming)throw new Error("Failed to add context: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to add context: no active session");const s=JSON.stringify({message_type:"context",session_id:t,content:e});this.sendDataMessage(s)}stopStreaming(){return jt(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(te.CONNECTION_CLOSED,$t.NORMAL),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,ks({attemptCorrelationId:null,sessionId:null,organizationId:this.organizationId}),this._isStreaming=!1)})}isStreaming(){return this._isStreaming}setPersonaConfig(e){this.personaConfig=e}getPersonaConfig(){return this.personaConfig}getInputAudioState(){var e;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Audio state will not be used because input audio is disabled."),this.streamingClient&&(this.inputAudioState=this.streamingClient.getInputAudioState()),this.inputAudioState}muteInputAudio(){var e,t;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."),this.streamingClient&&!(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var e,t;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(e){return jt(this,void 0,void 0,function*(){var t;if(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(e)})}createTalkMessageStream(e){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(e&&e.trim()==="")throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(e)}createAgentAudioInputStream(e){if(!this.streamingClient)throw new Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(e)}addListener(e,t){this.publicEventEmitter.addListener(e,t)}removeListener(e,t){this.publicEventEmitter.removeListener(e,t)}getActiveSessionId(){return this.sessionId}registerToolCallHandler(e,t){return this.toolCallManager.registerHandler(e,t)}}const Pv=(i,e)=>new Mv(i,void 0,e);let kv=0;class Ov{constructor(e){this.onVideoReady=null,this.onConnected=null,this.onDisconnected=null,this.onTalkStreamInterrupted=null,this.onError=null,this.audioInputStream=null,this.videoElement=null,this._connected=!1,this._closing=!1,this.inlineMode=e.inlineMode??!1,this.client=Pv(e.sessionToken,{disableInputAudio:!0,metrics:{disableClientMetrics:!0}})}get isConnected(){return this._connected}get videoEl(){return this.videoElement}async connect(){var e;try{const t=`anam-avatar-video-${++kv}`;this.videoElement=document.createElement("video"),this.videoElement.id=t,this.videoElement.autoplay=!0,this.videoElement.playsInline=!0,this.inlineMode?this.videoElement.style.cssText=`
|
|
927
927
|
width: 100%;
|
|
928
928
|
height: 100%;
|
|
929
929
|
object-fit: cover;
|
|
@@ -938,10 +938,10 @@ registerProcessor('pcm-buffer-processor', PcmBufferProcessor)
|
|
|
938
938
|
z-index: 2147483646;
|
|
939
939
|
pointer-events: none;
|
|
940
940
|
display: none;
|
|
941
|
-
`,document.body.appendChild(this.videoElement),this.client.addListener(te.CONNECTION_ESTABLISHED,()=>{var s;console.log("[AnamSession] Connection established"),this._connected=!0,(s=this.onConnected)==null||s.call(this)}),this.client.addListener(te.VIDEO_PLAY_STARTED,()=>{var s;console.log("[AnamSession] Video playing"),this.videoElement&&(this.videoElement.style.display="",(s=this.onVideoReady)==null||s.call(this,this.videoElement))}),this.client.addListener(te.TALK_STREAM_INTERRUPTED,()=>{var s;console.log("[AnamSession] Talk stream interrupted"),(s=this.onTalkStreamInterrupted)==null||s.call(this)}),this.client.addListener(te.CONNECTION_CLOSED,s=>{var r;console.log("[AnamSession] Connection closed:",s),this._connected=!1,(r=this.onDisconnected)==null||r.call(this,String(s))}),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 s=t instanceof Error?t:new Error(String(t));throw console.error("[AnamSession] Connection failed:",s.message),(e=this.onError)==null||e.call(this,s),this.close(),s}}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
|
|
942
|
-
`),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(Ov.has(t))return!e.disabled;const s=e.getAttribute("role");if(s&&Bv.has(s))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 s of Nv){const r=e.getAttribute(s);r&&r.length>0&&r.length<100&&t.push(`${s}="${r}"`)}return t.join(" ")}}const Gv=new Set(["scroll_to","click","highlight"]);class Fv{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 s;switch(e.type){case"response.output_item.added":if(((s=e.item)==null?void 0:s.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",s=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(s,{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(s,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(s,o)}async handlePageAction(e,t){try{const s=t.toLowerCase();if(s.includes("scroll")&&(s.includes("top")||s.includes("beginning"))){const l=this.pageActions.scrollTo(-1);this.sendToolResult(e,{results:[{action:"scroll_to",...l}]});return}if(s.includes("scroll")&&(s.includes("bottom")||s.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 kf(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(Gv.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(s){const r=s instanceof Error?s.message:String(s);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 s=t.parentElement;for(;s;){const n=getComputedStyle(s).overflowY;if(n==="auto"||n==="scroll"){const o=t.getBoundingClientRect().top-s.getBoundingClientRect().top+s.scrollTop;s.scrollTo({top:o-s.clientHeight/2,behavior:"smooth"});break}s=s.parentElement}const r=this.describeElement(t);return console.log(`[PageActions] Scrolled to [${e}] ${r}`),{status:"scrolled",description:r}}highlight(e,t=3e3){const s=this.analyzer.getElementByIndex(e);if(!s)return{status:"error",description:`Element [${e}] not found`};this.highlightRenderer.highlight(s,t);const r=this.describeElement(s);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 s=this.describeElement(t);return console.log(`[PageActions] Clicked [${e}] ${s}`),{status:"clicked",description:s}}fill(e,t){var a,l;const s=this.analyzer.getElementByIndex(e);if(!s)return{status:"error",description:`Element [${e}] not found`};const r=s.tagName.toLowerCase(),n=(a=s.type)==null?void 0:a.toLowerCase();if(r==="select"){const c=s,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=s;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(s,t):s.value=t,s.dispatchEvent(new Event("input",{bubbles:!0})),s.dispatchEvent(new Event("change",{bubbles:!0}))}const o=this.describeElement(s);return console.log(`[PageActions] Filled [${e}] ${o} with "${t}"`),{status:"filled",description:`${o} = "${t}"`}}describeElement(e){const t=e.tagName.toLowerCase(),s=(e.textContent??"").trim().slice(0,50),r=e.getAttribute("aria-label")||e.getAttribute("placeholder")||s;return`<${t}>${r}</${t}>`}}class Wv{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 Vv{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(s=>`${s.sender==="user"?"User":"Agent"}: ${s.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 s=`${this.backendUrl}/logConversation`,r=JSON.stringify(t);try{const n=await fetch(s,{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(i){i[i.Document=0]="Document",i[i.DocumentType=1]="DocumentType",i[i.Element=2]="Element",i[i.Text=3]="Text",i[i.CDATA=4]="CDATA",i[i.Comment=5]="Comment"})(We||(We={}));function zv(i){return i.nodeType===i.ELEMENT_NODE}function Ci(i){var e=i==null?void 0:i.host;return(e==null?void 0:e.shadowRoot)===i}function Ei(i){return Object.prototype.toString.call(i)==="[object ShadowRoot]"}function $v(i){return i.includes(" background-clip: text;")&&!i.includes(" -webkit-background-clip: text;")&&(i=i.replace(" background-clip: text;"," -webkit-background-clip: text; background-clip: text;")),i}function ko(i){try{var e=i.rules||i.cssRules;return e?$v(Array.from(e).map(Gu).join("")):null}catch{return null}}function Gu(i){var e=i.cssText;if(jv(i))try{e=ko(i.styleSheet)||e}catch{}return e}function jv(i){return"styleSheet"in i}var Fu=(function(){function i(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}return i.prototype.getId=function(e){var t;if(!e)return-1;var s=(t=this.getMeta(e))===null||t===void 0?void 0:t.id;return s??-1},i.prototype.getNode=function(e){return this.idNodeMap.get(e)||null},i.prototype.getIds=function(){return Array.from(this.idNodeMap.keys())},i.prototype.getMeta=function(e){return this.nodeMetaMap.get(e)||null},i.prototype.removeNodeFromMap=function(e){var t=this,s=this.getId(e);this.idNodeMap.delete(s),e.childNodes&&e.childNodes.forEach(function(r){return t.removeNodeFromMap(r)})},i.prototype.has=function(e){return this.idNodeMap.has(e)},i.prototype.hasNode=function(e){return this.nodeMetaMap.has(e)},i.prototype.add=function(e,t){var s=t.id;this.idNodeMap.set(s,e),this.nodeMetaMap.set(e,t)},i.prototype.replace=function(e,t){var s=this.getNode(e);if(s){var r=this.nodeMetaMap.get(s);r&&this.nodeMetaMap.set(t,r)}this.idNodeMap.set(e,t)},i.prototype.reset=function(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap},i})();function Xv(){return new Fu}function Oo(i){var e=i.maskInputOptions,t=i.tagName,s=i.type,r=i.value,n=i.maskInputFn,o=r||"";return(e[t.toLowerCase()]||e[s])&&(n?o=n(o):o="*".repeat(o.length)),o}var Lu="__rrweb_original__";function Yv(i){var e=i.getContext("2d");if(!e)return!0;for(var t=50,s=0;s<i.width;s+=t)for(var r=0;r<i.height;r+=t){var n=e.getImageData,o=Lu in n?n[Lu]:n,a=new Uint32Array(o.call(e,s,r,Math.min(t,i.width-s),Math.min(t,i.height-r)).data.buffer);if(a.some(function(l){return l!==0}))return!1}return!0}var qv=1,Kv=new RegExp("[^a-z0-9-_:]"),Si=-2;function Wu(){return qv++}function Zv(i){if(i instanceof HTMLFormElement)return"form";var e=i.tagName.toLowerCase().trim();return Kv.test(e)?"div":e}function Jv(i){return i.cssRules?Array.from(i.cssRules).map(function(e){return e.cssText||""}).join(""):""}function Qv(i){var e="";return i.indexOf("//")>-1?e=i.split("/").slice(0,3).join("/"):e=i.split("/")[0],e=e.split("?")[0],e}var Bs,Hu,ex=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,tx=/^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/|#).*/,sx=/^(data:)([^,]*),(.*)/i;function gr(i,e){return(i||"").replace(ex,function(t,s,r,n,o,a){var l=r||o||a,c=s||n||"";if(!l)return t;if(!tx.test(l)||sx.test(l))return"url(".concat(c).concat(l).concat(c,")");if(l[0]==="/")return"url(".concat(c).concat(Qv(e)+l).concat(c,")");var h=e.split("/"),u=l.split("/");h.pop();for(var p=0,d=u;p<d.length;p++){var g=d[p];g!=="."&&(g===".."?h.pop():h.push(g))}return"url(".concat(c).concat(h.join("/")).concat(c,")")})}var ix=/^[^ \t\n\r\u000c]+/,rx=/^[, \t\n\r\u000c]+/;function nx(i,e){if(e.trim()==="")return e;var t=0;function s(c){var h,u=c.exec(e.substring(t));return u?(h=u[0],t+=h.length,h):""}for(var r=[];s(rx),!(t>=e.length);){var n=s(ix);if(n.slice(-1)===",")n=Ds(i,n.substring(0,n.length-1)),r.push(n);else{var o="";n=Ds(i,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 Ds(i,e){if(!e||e.trim()==="")return e;var t=i.createElement("a");return t.href=e,t.href}function ox(i){return!!(i.tagName==="svg"||i.ownerSVGElement)}function Bo(){var i=document.createElement("a");return i.href="",i.href}function Vu(i,e,t,s){return t==="src"||t==="href"&&s&&!(e==="use"&&s[0]==="#")||t==="xlink:href"&&s&&s[0]!=="#"||t==="background"&&s&&(e==="table"||e==="td"||e==="th")?Ds(i,s):t==="srcset"&&s?nx(i,s):t==="style"&&s?gr(s,Bo()):e==="object"&&t==="data"&&s?Ds(i,s):s}function ax(i,e,t){if(typeof e=="string"){if(i.classList.contains(e))return!0}else for(var s=i.classList.length;s--;){var r=i.classList[s];if(e.test(r))return!0}return t?i.matches(t):!1}function _r(i,e,t){if(!i)return!1;if(i.nodeType!==i.ELEMENT_NODE)return t?_r(i.parentNode,e,t):!1;for(var s=i.classList.length;s--;){var r=i.classList[s];if(e.test(r))return!0}return t?_r(i.parentNode,e,t):!1}function zu(i,e,t){var s=i.nodeType===i.ELEMENT_NODE?i:i.parentElement;if(s===null)return!1;if(typeof e=="string"){if(s.classList.contains(e)||s.closest(".".concat(e)))return!0}else if(_r(s,e,!0))return!0;return!!(t&&(s.matches(t)||s.closest(t)))}function lx(i,e,t){var s=i.contentWindow;if(s){var r=!1,n;try{n=s.document.readyState}catch{return}if(n!=="complete"){var o=setTimeout(function(){r||(e(),r=!0)},t);i.addEventListener("load",function(){clearTimeout(o),r=!0,e()});return}var a="about:blank";if(s.location.href!==a||i.src===a||i.src==="")return setTimeout(e,0),i.addEventListener("load",e);i.addEventListener("load",e)}}function cx(i,e,t){var s=!1,r;try{r=i.sheet}catch{return}if(!r){var n=setTimeout(function(){s||(e(),s=!0)},t);i.addEventListener("load",function(){clearTimeout(n),s=!0,e()})}}function hx(i,e){var t=e.doc,s=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,p=e.maskInputFn,d=e.dataURLOptions,g=d===void 0?{}:d,_=e.inlineImages,b=e.recordCanvas,v=e.keepIframeSrcFn,C=e.newlyAddedElement,E=C===void 0?!1:C,S=ux(t,s);switch(i.nodeType){case i.DOCUMENT_NODE:return i.compatMode!=="CSS1Compat"?{type:We.Document,childNodes:[],compatMode:i.compatMode}:{type:We.Document,childNodes:[]};case i.DOCUMENT_TYPE_NODE:return{type:We.DocumentType,name:i.name,publicId:i.publicId,systemId:i.systemId,rootId:S};case i.ELEMENT_NODE:return fx(i,{doc:t,blockClass:r,blockSelector:n,inlineStylesheet:l,maskInputOptions:h,maskInputFn:p,dataURLOptions:g,inlineImages:_,recordCanvas:b,keepIframeSrcFn:v,newlyAddedElement:E,rootId:S});case i.TEXT_NODE:return dx(i,{maskTextClass:o,maskTextSelector:a,maskTextFn:u,rootId:S});case i.CDATA_SECTION_NODE:return{type:We.CDATA,textContent:"",rootId:S};case i.COMMENT_NODE:return{type:We.Comment,textContent:i.textContent||"",rootId:S};default:return!1}}function ux(i,e){if(e.hasNode(i)){var t=e.getId(i);return t===1?void 0:t}}function dx(i,e){var t,s=e.maskTextClass,r=e.maskTextSelector,n=e.maskTextFn,o=e.rootId,a=i.parentNode&&i.parentNode.tagName,l=i.textContent,c=a==="STYLE"?!0:void 0,h=a==="SCRIPT"?!0:void 0;if(c&&l){try{i.nextSibling||i.previousSibling||!((t=i.parentNode.sheet)===null||t===void 0)&&t.cssRules&&(l=Jv(i.parentNode.sheet))}catch(u){console.warn("Cannot get CSS styles from text's parentNode. Error: ".concat(u),i)}l=gr(l,Bo())}return h&&(l="SCRIPT_PLACEHOLDER"),!c&&!h&&l&&zu(i,s,r)&&(l=n?n(l):l.replace(/[\S]/g,"*")),{type:We.Text,textContent:l||"",isStyle:c,rootId:o}}function fx(i,e){for(var t=e.doc,s=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,p=e.recordCanvas,d=e.keepIframeSrcFn,g=e.newlyAddedElement,_=g===void 0?!1:g,b=e.rootId,v=ax(i,s,r),C=Zv(i),E={},S=i.attributes.length,w=0;w<S;w++){var R=i.attributes[w];E[R.name]=Vu(t,C,R.name,R.value)}if(C==="link"&&n){var M=Array.from(t.styleSheets).find(function(K){return K.href===i.href}),D=null;M&&(D=ko(M)),D&&(delete E.rel,delete E.href,E._cssText=gr(D,M.href))}if(C==="style"&&i.sheet&&!(i.innerText||i.textContent||"").trim().length){var D=ko(i.sheet);D&&(E._cssText=gr(D,Bo()))}if(C==="input"||C==="textarea"||C==="select"){var G=i.value,k=i.checked;E.type!=="radio"&&E.type!=="checkbox"&&E.type!=="submit"&&E.type!=="button"&&G?E.value=Oo({type:E.type,tagName:C,value:G,maskInputOptions:a,maskInputFn:l}):k&&(E.checked=k)}if(C==="option"&&(i.selected&&!a.select?E.selected=!0:delete E.selected),C==="canvas"&&p){if(i.__context==="2d")Yv(i)||(E.rr_dataURL=i.toDataURL(h.type,h.quality));else if(!("__context"in i)){var O=i.toDataURL(h.type,h.quality),V=document.createElement("canvas");V.width=i.width,V.height=i.height;var X=V.toDataURL(h.type,h.quality);O!==X&&(E.rr_dataURL=O)}}if(C==="img"&&u){Bs||(Bs=t.createElement("canvas"),Hu=Bs.getContext("2d"));var z=i,de=z.crossOrigin;z.crossOrigin="anonymous";var B=function(){try{Bs.width=z.naturalWidth,Bs.height=z.naturalHeight,Hu.drawImage(z,0,0),E.rr_dataURL=Bs.toDataURL(h.type,h.quality)}catch(K){console.warn("Cannot inline img src=".concat(z.currentSrc,"! Error: ").concat(K))}de?E.crossOrigin=de:z.removeAttribute("crossorigin")};z.complete&&z.naturalWidth!==0?B():z.onload=B}if((C==="audio"||C==="video")&&(E.rr_mediaState=i.paused?"paused":"played",E.rr_mediaCurrentTime=i.currentTime),_||(i.scrollLeft&&(E.rr_scrollLeft=i.scrollLeft),i.scrollTop&&(E.rr_scrollTop=i.scrollTop)),v){var U=i.getBoundingClientRect(),q=U.width,N=U.height;E={class:E.class,rr_width:"".concat(q,"px"),rr_height:"".concat(N,"px")}}return C==="iframe"&&!d(E.src)&&(i.contentDocument||(E.rr_src=E.src),delete E.src),{type:We.Element,tagName:C,attributes:E,childNodes:[],isSVG:ox(i)||void 0,needBlock:v,rootId:b}}function ve(i){return i===void 0?"":i.toLowerCase()}function px(i,e){if(e.comment&&i.type===We.Comment)return!0;if(i.type===We.Element){if(e.script&&(i.tagName==="script"||i.tagName==="link"&&i.attributes.rel==="preload"&&i.attributes.as==="script"||i.tagName==="link"&&i.attributes.rel==="prefetch"&&typeof i.attributes.href=="string"&&i.attributes.href.endsWith(".js")))return!0;if(e.headFavicon&&(i.tagName==="link"&&i.attributes.rel==="shortcut icon"||i.tagName==="meta"&&(ve(i.attributes.name).match(/^msapplication-tile(image|color)$/)||ve(i.attributes.name)==="application-name"||ve(i.attributes.rel)==="icon"||ve(i.attributes.rel)==="apple-touch-icon"||ve(i.attributes.rel)==="shortcut icon")))return!0;if(i.tagName==="meta"){if(e.headMetaDescKeywords&&ve(i.attributes.name).match(/^description|keywords$/))return!0;if(e.headMetaSocial&&(ve(i.attributes.property).match(/^(og|twitter|fb):/)||ve(i.attributes.name).match(/^(og|twitter):/)||ve(i.attributes.name)==="pinterest"))return!0;if(e.headMetaRobots&&(ve(i.attributes.name)==="robots"||ve(i.attributes.name)==="googlebot"||ve(i.attributes.name)==="bingbot"))return!0;if(e.headMetaHttpEquiv&&i.attributes["http-equiv"]!==void 0)return!0;if(e.headMetaAuthorship&&(ve(i.attributes.name)==="author"||ve(i.attributes.name)==="generator"||ve(i.attributes.name)==="framework"||ve(i.attributes.name)==="publisher"||ve(i.attributes.name)==="progid"||ve(i.attributes.property).match(/^article:/)||ve(i.attributes.property).match(/^product:/)))return!0;if(e.headMetaVerification&&(ve(i.attributes.name)==="google-site-verification"||ve(i.attributes.name)==="yandex-verification"||ve(i.attributes.name)==="csrf-token"||ve(i.attributes.name)==="p:domain_verify"||ve(i.attributes.name)==="verify-v1"||ve(i.attributes.name)==="verification"||ve(i.attributes.name)==="shopify-checkout-api-token"))return!0}}return!1}function Ns(i,e){var t=e.doc,s=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,p=e.maskInputOptions,d=p===void 0?{}:p,g=e.maskTextFn,_=e.maskInputFn,b=e.slimDOMOptions,v=e.dataURLOptions,C=v===void 0?{}:v,E=e.inlineImages,S=E===void 0?!1:E,w=e.recordCanvas,R=w===void 0?!1:w,M=e.onSerialize,D=e.onIframeLoad,G=e.iframeLoadTimeout,k=G===void 0?5e3:G,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=hx(i,{doc:t,mirror:s,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,dataURLOptions:C,inlineImages:S,recordCanvas:R,keepIframeSrcFn:de,newlyAddedElement:U});if(!K)return console.warn(i,"not serialized"),null;var Z;s.hasNode(i)?Z=s.getId(i):px(K,b)||!N&&K.type===We.Text&&!K.isStyle&&!K.textContent.replace(/^\s+|\s+$/gm,"").length?Z=Si:Z=Wu();var $=Object.assign(K,{id:Z});if(s.add(i,$),Z===Si)return null;M&&M(i);var ae=!c;if($.type===We.Element){ae=ae&&!$.needBlock,delete $.needBlock;var xe=i.shadowRoot;xe&&Ei(xe)&&($.isShadowHost=!0)}if(($.type===We.Document||$.type===We.Element)&&ae){b.headWhitespace&&$.type===We.Element&&$.tagName==="head"&&(N=!1);for(var Se={doc:t,mirror:s,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:c,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:b,dataURLOptions:C,inlineImages:S,recordCanvas:R,preserveWhiteSpace:N,onSerialize:M,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:X,keepIframeSrcFn:de},F=0,fe=Array.from(i.childNodes);F<fe.length;F++){var le=fe[F],L=Ns(le,Se);L&&$.childNodes.push(L)}if(zv(i)&&i.shadowRoot)for(var me=0,Y=Array.from(i.shadowRoot.childNodes);me<Y.length;me++){var le=Y[me],L=Ns(le,Se);L&&(Ei(i.shadowRoot)&&(L.isShadow=!0),$.childNodes.push(L))}}return i.parentNode&&Ci(i.parentNode)&&Ei(i.parentNode)&&($.isShadow=!0),$.type===We.Element&&$.tagName==="iframe"&&lx(i,function(){var se=i.contentDocument;if(se&&D){var we=Ns(se,{doc:se,mirror:s,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:b,dataURLOptions:C,inlineImages:S,recordCanvas:R,preserveWhiteSpace:N,onSerialize:M,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:X,keepIframeSrcFn:de});we&&D(i,we)}},k),$.type===We.Element&&$.tagName==="link"&&$.attributes.rel==="stylesheet"&&cx(i,function(){if(O){var se=Ns(i,{doc:t,mirror:s,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:b,dataURLOptions:C,inlineImages:S,recordCanvas:R,preserveWhiteSpace:N,onSerialize:M,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:X,keepIframeSrcFn:de});se&&O(i,se)}},X),$}function mx(i,e){var t=e||{},s=t.mirror,r=s===void 0?new Fu:s,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,p=u===void 0?null:u,d=t.inlineStylesheet,g=d===void 0?!0:d,_=t.inlineImages,b=_===void 0?!1:_,v=t.recordCanvas,C=v===void 0?!1:v,E=t.maskAllInputs,S=E===void 0?!1:E,w=t.maskTextFn,R=t.maskInputFn,M=t.slimDOM,D=M===void 0?!1:M,G=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=S===!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}:S===!1?{password:!0}:S,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 Ns(i,{doc:i,mirror:r,blockClass:o,blockSelector:l,maskTextClass:h,maskTextSelector:p,skipChild:!1,inlineStylesheet:g,maskInputOptions:q,maskTextFn:w,maskInputFn:R,slimDOMOptions:N,dataURLOptions:G,inlineImages:b,recordCanvas:C,preserveWhiteSpace:k,onSerialize:O,onIframeLoad:V,iframeLoadTimeout:X,onStylesheetLoad:z,stylesheetLoadTimeout:de,keepIframeSrcFn:U,newlyAddedElement:!1})}function Ze(i,e,t=document){const s={capture:!0,passive:!0};return t.addEventListener(i,e,s),()=>t.removeEventListener(i,e,s)}const Us=`Please stop import mirror directly. Instead of that,\r
|
|
941
|
+
`,document.body.appendChild(this.videoElement),this.client.addListener(te.CONNECTION_ESTABLISHED,()=>{var s;console.log("[AnamSession] Connection established"),this._connected=!0,(s=this.onConnected)==null||s.call(this)}),this.client.addListener(te.VIDEO_PLAY_STARTED,()=>{var s;console.log("[AnamSession] Video playing"),this.videoElement&&(this.videoElement.style.display="",(s=this.onVideoReady)==null||s.call(this,this.videoElement))}),this.client.addListener(te.TALK_STREAM_INTERRUPTED,()=>{var s;console.log("[AnamSession] Talk stream interrupted"),(s=this.onTalkStreamInterrupted)==null||s.call(this)}),this.client.addListener(te.CONNECTION_CLOSED,s=>{var r;console.log("[AnamSession] Connection closed:",s),this._connected=!1,(r=this.onDisconnected)==null||r.call(this,String(s))}),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 s=t instanceof Error?t:new Error(String(t));throw console.error("[AnamSession] Connection failed:",s.message),(e=this.onError)==null||e.call(this,s),this.close(),s}}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 Bv=new Set(["a","button","input","select","textarea","details","summary","label","option"]),Dv=new Set(["button","link","menuitem","menuitemcheckbox","menuitemradio","tab","switch","slider","combobox","listbox","option","radio","checkbox","textbox","searchbox","scrollbar"]),Nv=new Set(["h1","h2","h3","h4","h5","h6"]),Uv=["type","role","aria-label","placeholder","value","href","alt","title","name","checked","aria-expanded"];class Gv{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 s=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=Nv.has(o);if(a||l){const c=e++;this.elementMap.set(c,n);const h=this.getUsefulAttrs(n),u=h?" "+h:"",p=this.getDirectText(n).slice(0,200);if(l){const d=parseInt(o[1]),g="#".repeat(d);t.push(""),t.push(`${g} [${c}]${p}`)}else t.push(`[${c}]<${o}${u}>${p}</${o}>`);return}for(const c of n.childNodes)s(c)};return s(document.body),{text:t.join(`
|
|
942
|
+
`),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(Bv.has(t))return!e.disabled;const s=e.getAttribute("role");if(s&&Dv.has(s))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 s of Uv){const r=e.getAttribute(s);r&&r.length>0&&r.length<100&&t.push(`${s}="${r}"`)}return t.join(" ")}}const Fv=new Set(["scroll_to","click","highlight"]);class Lv{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 s;switch(e.type){case"response.output_item.added":if(((s=e.item)==null?void 0:s.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",s=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(s,{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(s,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(s,o)}async handlePageAction(e,t){try{const s=t.toLowerCase();if(s.includes("scroll")&&(s.includes("top")||s.includes("beginning"))){const l=this.pageActions.scrollTo(-1);this.sendToolResult(e,{results:[{action:"scroll_to",...l}]});return}if(s.includes("scroll")&&(s.includes("bottom")||s.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 Of(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(Fv.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(s){const r=s instanceof Error?s.message:String(s);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 Wv{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 s=t.parentElement;for(;s;){const n=getComputedStyle(s).overflowY;if(n==="auto"||n==="scroll"){const o=t.getBoundingClientRect().top-s.getBoundingClientRect().top+s.scrollTop;s.scrollTo({top:o-s.clientHeight/2,behavior:"smooth"});break}s=s.parentElement}const r=this.describeElement(t);return console.log(`[PageActions] Scrolled to [${e}] ${r}`),{status:"scrolled",description:r}}highlight(e,t=3e3){const s=this.analyzer.getElementByIndex(e);if(!s)return{status:"error",description:`Element [${e}] not found`};this.highlightRenderer.highlight(s,t);const r=this.describeElement(s);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 s=this.describeElement(t);return console.log(`[PageActions] Clicked [${e}] ${s}`),{status:"clicked",description:s}}fill(e,t){var a,l;const s=this.analyzer.getElementByIndex(e);if(!s)return{status:"error",description:`Element [${e}] not found`};const r=s.tagName.toLowerCase(),n=(a=s.type)==null?void 0:a.toLowerCase();if(r==="select"){const c=s,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=s;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(s,t):s.value=t,s.dispatchEvent(new Event("input",{bubbles:!0})),s.dispatchEvent(new Event("change",{bubbles:!0}))}const o=this.describeElement(s);return console.log(`[PageActions] Filled [${e}] ${o} with "${t}"`),{status:"filled",description:`${o} = "${t}"`}}describeElement(e){const t=e.tagName.toLowerCase(),s=(e.textContent??"").trim().slice(0,50),r=e.getAttribute("aria-label")||e.getAttribute("placeholder")||s;return`<${t}>${r}</${t}>`}}class Hv{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 Vv="https://us-central1-holostaff-ai.cloudfunctions.net";class zv{constructor(e){this.messages={},this.actions=[],this.msgCounter=0,this.staffId=e.staffId,this.staffName=e.staffName,this.backendUrl=e.backendUrl??Vv,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(s=>`${s.sender==="user"?"User":"Agent"}: ${s.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 s=`${this.backendUrl}/logConversation`,r=JSON.stringify(t);try{const n=await fetch(s,{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(i){i[i.Document=0]="Document",i[i.DocumentType=1]="DocumentType",i[i.Element=2]="Element",i[i.Text=3]="Text",i[i.CDATA=4]="CDATA",i[i.Comment=5]="Comment"})(We||(We={}));function $v(i){return i.nodeType===i.ELEMENT_NODE}function Ci(i){var e=i==null?void 0:i.host;return(e==null?void 0:e.shadowRoot)===i}function Ei(i){return Object.prototype.toString.call(i)==="[object ShadowRoot]"}function jv(i){return i.includes(" background-clip: text;")&&!i.includes(" -webkit-background-clip: text;")&&(i=i.replace(" background-clip: text;"," -webkit-background-clip: text; background-clip: text;")),i}function ko(i){try{var e=i.rules||i.cssRules;return e?jv(Array.from(e).map(Gu).join("")):null}catch{return null}}function Gu(i){var e=i.cssText;if(Xv(i))try{e=ko(i.styleSheet)||e}catch{}return e}function Xv(i){return"styleSheet"in i}var Fu=(function(){function i(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}return i.prototype.getId=function(e){var t;if(!e)return-1;var s=(t=this.getMeta(e))===null||t===void 0?void 0:t.id;return s??-1},i.prototype.getNode=function(e){return this.idNodeMap.get(e)||null},i.prototype.getIds=function(){return Array.from(this.idNodeMap.keys())},i.prototype.getMeta=function(e){return this.nodeMetaMap.get(e)||null},i.prototype.removeNodeFromMap=function(e){var t=this,s=this.getId(e);this.idNodeMap.delete(s),e.childNodes&&e.childNodes.forEach(function(r){return t.removeNodeFromMap(r)})},i.prototype.has=function(e){return this.idNodeMap.has(e)},i.prototype.hasNode=function(e){return this.nodeMetaMap.has(e)},i.prototype.add=function(e,t){var s=t.id;this.idNodeMap.set(s,e),this.nodeMetaMap.set(e,t)},i.prototype.replace=function(e,t){var s=this.getNode(e);if(s){var r=this.nodeMetaMap.get(s);r&&this.nodeMetaMap.set(t,r)}this.idNodeMap.set(e,t)},i.prototype.reset=function(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap},i})();function Yv(){return new Fu}function Oo(i){var e=i.maskInputOptions,t=i.tagName,s=i.type,r=i.value,n=i.maskInputFn,o=r||"";return(e[t.toLowerCase()]||e[s])&&(n?o=n(o):o="*".repeat(o.length)),o}var Lu="__rrweb_original__";function qv(i){var e=i.getContext("2d");if(!e)return!0;for(var t=50,s=0;s<i.width;s+=t)for(var r=0;r<i.height;r+=t){var n=e.getImageData,o=Lu in n?n[Lu]:n,a=new Uint32Array(o.call(e,s,r,Math.min(t,i.width-s),Math.min(t,i.height-r)).data.buffer);if(a.some(function(l){return l!==0}))return!1}return!0}var Kv=1,Zv=new RegExp("[^a-z0-9-_:]"),Si=-2;function Wu(){return Kv++}function Jv(i){if(i instanceof HTMLFormElement)return"form";var e=i.tagName.toLowerCase().trim();return Zv.test(e)?"div":e}function Qv(i){return i.cssRules?Array.from(i.cssRules).map(function(e){return e.cssText||""}).join(""):""}function ex(i){var e="";return i.indexOf("//")>-1?e=i.split("/").slice(0,3).join("/"):e=i.split("/")[0],e=e.split("?")[0],e}var Bs,Hu,tx=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,sx=/^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/|#).*/,ix=/^(data:)([^,]*),(.*)/i;function gr(i,e){return(i||"").replace(tx,function(t,s,r,n,o,a){var l=r||o||a,c=s||n||"";if(!l)return t;if(!sx.test(l)||ix.test(l))return"url(".concat(c).concat(l).concat(c,")");if(l[0]==="/")return"url(".concat(c).concat(ex(e)+l).concat(c,")");var h=e.split("/"),u=l.split("/");h.pop();for(var p=0,d=u;p<d.length;p++){var g=d[p];g!=="."&&(g===".."?h.pop():h.push(g))}return"url(".concat(c).concat(h.join("/")).concat(c,")")})}var rx=/^[^ \t\n\r\u000c]+/,nx=/^[, \t\n\r\u000c]+/;function ox(i,e){if(e.trim()==="")return e;var t=0;function s(c){var h,u=c.exec(e.substring(t));return u?(h=u[0],t+=h.length,h):""}for(var r=[];s(nx),!(t>=e.length);){var n=s(rx);if(n.slice(-1)===",")n=Ds(i,n.substring(0,n.length-1)),r.push(n);else{var o="";n=Ds(i,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 Ds(i,e){if(!e||e.trim()==="")return e;var t=i.createElement("a");return t.href=e,t.href}function ax(i){return!!(i.tagName==="svg"||i.ownerSVGElement)}function Bo(){var i=document.createElement("a");return i.href="",i.href}function Vu(i,e,t,s){return t==="src"||t==="href"&&s&&!(e==="use"&&s[0]==="#")||t==="xlink:href"&&s&&s[0]!=="#"||t==="background"&&s&&(e==="table"||e==="td"||e==="th")?Ds(i,s):t==="srcset"&&s?ox(i,s):t==="style"&&s?gr(s,Bo()):e==="object"&&t==="data"&&s?Ds(i,s):s}function lx(i,e,t){if(typeof e=="string"){if(i.classList.contains(e))return!0}else for(var s=i.classList.length;s--;){var r=i.classList[s];if(e.test(r))return!0}return t?i.matches(t):!1}function _r(i,e,t){if(!i)return!1;if(i.nodeType!==i.ELEMENT_NODE)return t?_r(i.parentNode,e,t):!1;for(var s=i.classList.length;s--;){var r=i.classList[s];if(e.test(r))return!0}return t?_r(i.parentNode,e,t):!1}function zu(i,e,t){var s=i.nodeType===i.ELEMENT_NODE?i:i.parentElement;if(s===null)return!1;if(typeof e=="string"){if(s.classList.contains(e)||s.closest(".".concat(e)))return!0}else if(_r(s,e,!0))return!0;return!!(t&&(s.matches(t)||s.closest(t)))}function cx(i,e,t){var s=i.contentWindow;if(s){var r=!1,n;try{n=s.document.readyState}catch{return}if(n!=="complete"){var o=setTimeout(function(){r||(e(),r=!0)},t);i.addEventListener("load",function(){clearTimeout(o),r=!0,e()});return}var a="about:blank";if(s.location.href!==a||i.src===a||i.src==="")return setTimeout(e,0),i.addEventListener("load",e);i.addEventListener("load",e)}}function hx(i,e,t){var s=!1,r;try{r=i.sheet}catch{return}if(!r){var n=setTimeout(function(){s||(e(),s=!0)},t);i.addEventListener("load",function(){clearTimeout(n),s=!0,e()})}}function ux(i,e){var t=e.doc,s=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,p=e.maskInputFn,d=e.dataURLOptions,g=d===void 0?{}:d,_=e.inlineImages,b=e.recordCanvas,v=e.keepIframeSrcFn,C=e.newlyAddedElement,E=C===void 0?!1:C,S=dx(t,s);switch(i.nodeType){case i.DOCUMENT_NODE:return i.compatMode!=="CSS1Compat"?{type:We.Document,childNodes:[],compatMode:i.compatMode}:{type:We.Document,childNodes:[]};case i.DOCUMENT_TYPE_NODE:return{type:We.DocumentType,name:i.name,publicId:i.publicId,systemId:i.systemId,rootId:S};case i.ELEMENT_NODE:return px(i,{doc:t,blockClass:r,blockSelector:n,inlineStylesheet:l,maskInputOptions:h,maskInputFn:p,dataURLOptions:g,inlineImages:_,recordCanvas:b,keepIframeSrcFn:v,newlyAddedElement:E,rootId:S});case i.TEXT_NODE:return fx(i,{maskTextClass:o,maskTextSelector:a,maskTextFn:u,rootId:S});case i.CDATA_SECTION_NODE:return{type:We.CDATA,textContent:"",rootId:S};case i.COMMENT_NODE:return{type:We.Comment,textContent:i.textContent||"",rootId:S};default:return!1}}function dx(i,e){if(e.hasNode(i)){var t=e.getId(i);return t===1?void 0:t}}function fx(i,e){var t,s=e.maskTextClass,r=e.maskTextSelector,n=e.maskTextFn,o=e.rootId,a=i.parentNode&&i.parentNode.tagName,l=i.textContent,c=a==="STYLE"?!0:void 0,h=a==="SCRIPT"?!0:void 0;if(c&&l){try{i.nextSibling||i.previousSibling||!((t=i.parentNode.sheet)===null||t===void 0)&&t.cssRules&&(l=Qv(i.parentNode.sheet))}catch(u){console.warn("Cannot get CSS styles from text's parentNode. Error: ".concat(u),i)}l=gr(l,Bo())}return h&&(l="SCRIPT_PLACEHOLDER"),!c&&!h&&l&&zu(i,s,r)&&(l=n?n(l):l.replace(/[\S]/g,"*")),{type:We.Text,textContent:l||"",isStyle:c,rootId:o}}function px(i,e){for(var t=e.doc,s=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,p=e.recordCanvas,d=e.keepIframeSrcFn,g=e.newlyAddedElement,_=g===void 0?!1:g,b=e.rootId,v=lx(i,s,r),C=Jv(i),E={},S=i.attributes.length,w=0;w<S;w++){var R=i.attributes[w];E[R.name]=Vu(t,C,R.name,R.value)}if(C==="link"&&n){var M=Array.from(t.styleSheets).find(function(K){return K.href===i.href}),D=null;M&&(D=ko(M)),D&&(delete E.rel,delete E.href,E._cssText=gr(D,M.href))}if(C==="style"&&i.sheet&&!(i.innerText||i.textContent||"").trim().length){var D=ko(i.sheet);D&&(E._cssText=gr(D,Bo()))}if(C==="input"||C==="textarea"||C==="select"){var G=i.value,k=i.checked;E.type!=="radio"&&E.type!=="checkbox"&&E.type!=="submit"&&E.type!=="button"&&G?E.value=Oo({type:E.type,tagName:C,value:G,maskInputOptions:a,maskInputFn:l}):k&&(E.checked=k)}if(C==="option"&&(i.selected&&!a.select?E.selected=!0:delete E.selected),C==="canvas"&&p){if(i.__context==="2d")qv(i)||(E.rr_dataURL=i.toDataURL(h.type,h.quality));else if(!("__context"in i)){var O=i.toDataURL(h.type,h.quality),V=document.createElement("canvas");V.width=i.width,V.height=i.height;var X=V.toDataURL(h.type,h.quality);O!==X&&(E.rr_dataURL=O)}}if(C==="img"&&u){Bs||(Bs=t.createElement("canvas"),Hu=Bs.getContext("2d"));var z=i,de=z.crossOrigin;z.crossOrigin="anonymous";var B=function(){try{Bs.width=z.naturalWidth,Bs.height=z.naturalHeight,Hu.drawImage(z,0,0),E.rr_dataURL=Bs.toDataURL(h.type,h.quality)}catch(K){console.warn("Cannot inline img src=".concat(z.currentSrc,"! Error: ").concat(K))}de?E.crossOrigin=de:z.removeAttribute("crossorigin")};z.complete&&z.naturalWidth!==0?B():z.onload=B}if((C==="audio"||C==="video")&&(E.rr_mediaState=i.paused?"paused":"played",E.rr_mediaCurrentTime=i.currentTime),_||(i.scrollLeft&&(E.rr_scrollLeft=i.scrollLeft),i.scrollTop&&(E.rr_scrollTop=i.scrollTop)),v){var U=i.getBoundingClientRect(),q=U.width,N=U.height;E={class:E.class,rr_width:"".concat(q,"px"),rr_height:"".concat(N,"px")}}return C==="iframe"&&!d(E.src)&&(i.contentDocument||(E.rr_src=E.src),delete E.src),{type:We.Element,tagName:C,attributes:E,childNodes:[],isSVG:ax(i)||void 0,needBlock:v,rootId:b}}function ve(i){return i===void 0?"":i.toLowerCase()}function mx(i,e){if(e.comment&&i.type===We.Comment)return!0;if(i.type===We.Element){if(e.script&&(i.tagName==="script"||i.tagName==="link"&&i.attributes.rel==="preload"&&i.attributes.as==="script"||i.tagName==="link"&&i.attributes.rel==="prefetch"&&typeof i.attributes.href=="string"&&i.attributes.href.endsWith(".js")))return!0;if(e.headFavicon&&(i.tagName==="link"&&i.attributes.rel==="shortcut icon"||i.tagName==="meta"&&(ve(i.attributes.name).match(/^msapplication-tile(image|color)$/)||ve(i.attributes.name)==="application-name"||ve(i.attributes.rel)==="icon"||ve(i.attributes.rel)==="apple-touch-icon"||ve(i.attributes.rel)==="shortcut icon")))return!0;if(i.tagName==="meta"){if(e.headMetaDescKeywords&&ve(i.attributes.name).match(/^description|keywords$/))return!0;if(e.headMetaSocial&&(ve(i.attributes.property).match(/^(og|twitter|fb):/)||ve(i.attributes.name).match(/^(og|twitter):/)||ve(i.attributes.name)==="pinterest"))return!0;if(e.headMetaRobots&&(ve(i.attributes.name)==="robots"||ve(i.attributes.name)==="googlebot"||ve(i.attributes.name)==="bingbot"))return!0;if(e.headMetaHttpEquiv&&i.attributes["http-equiv"]!==void 0)return!0;if(e.headMetaAuthorship&&(ve(i.attributes.name)==="author"||ve(i.attributes.name)==="generator"||ve(i.attributes.name)==="framework"||ve(i.attributes.name)==="publisher"||ve(i.attributes.name)==="progid"||ve(i.attributes.property).match(/^article:/)||ve(i.attributes.property).match(/^product:/)))return!0;if(e.headMetaVerification&&(ve(i.attributes.name)==="google-site-verification"||ve(i.attributes.name)==="yandex-verification"||ve(i.attributes.name)==="csrf-token"||ve(i.attributes.name)==="p:domain_verify"||ve(i.attributes.name)==="verify-v1"||ve(i.attributes.name)==="verification"||ve(i.attributes.name)==="shopify-checkout-api-token"))return!0}}return!1}function Ns(i,e){var t=e.doc,s=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,p=e.maskInputOptions,d=p===void 0?{}:p,g=e.maskTextFn,_=e.maskInputFn,b=e.slimDOMOptions,v=e.dataURLOptions,C=v===void 0?{}:v,E=e.inlineImages,S=E===void 0?!1:E,w=e.recordCanvas,R=w===void 0?!1:w,M=e.onSerialize,D=e.onIframeLoad,G=e.iframeLoadTimeout,k=G===void 0?5e3:G,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=ux(i,{doc:t,mirror:s,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,dataURLOptions:C,inlineImages:S,recordCanvas:R,keepIframeSrcFn:de,newlyAddedElement:U});if(!K)return console.warn(i,"not serialized"),null;var Z;s.hasNode(i)?Z=s.getId(i):mx(K,b)||!N&&K.type===We.Text&&!K.isStyle&&!K.textContent.replace(/^\s+|\s+$/gm,"").length?Z=Si:Z=Wu();var $=Object.assign(K,{id:Z});if(s.add(i,$),Z===Si)return null;M&&M(i);var ae=!c;if($.type===We.Element){ae=ae&&!$.needBlock,delete $.needBlock;var xe=i.shadowRoot;xe&&Ei(xe)&&($.isShadowHost=!0)}if(($.type===We.Document||$.type===We.Element)&&ae){b.headWhitespace&&$.type===We.Element&&$.tagName==="head"&&(N=!1);for(var Se={doc:t,mirror:s,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:c,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:b,dataURLOptions:C,inlineImages:S,recordCanvas:R,preserveWhiteSpace:N,onSerialize:M,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:X,keepIframeSrcFn:de},F=0,fe=Array.from(i.childNodes);F<fe.length;F++){var le=fe[F],L=Ns(le,Se);L&&$.childNodes.push(L)}if($v(i)&&i.shadowRoot)for(var me=0,Y=Array.from(i.shadowRoot.childNodes);me<Y.length;me++){var le=Y[me],L=Ns(le,Se);L&&(Ei(i.shadowRoot)&&(L.isShadow=!0),$.childNodes.push(L))}}return i.parentNode&&Ci(i.parentNode)&&Ei(i.parentNode)&&($.isShadow=!0),$.type===We.Element&&$.tagName==="iframe"&&cx(i,function(){var se=i.contentDocument;if(se&&D){var we=Ns(se,{doc:se,mirror:s,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:b,dataURLOptions:C,inlineImages:S,recordCanvas:R,preserveWhiteSpace:N,onSerialize:M,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:X,keepIframeSrcFn:de});we&&D(i,we)}},k),$.type===We.Element&&$.tagName==="link"&&$.attributes.rel==="stylesheet"&&hx(i,function(){if(O){var se=Ns(i,{doc:t,mirror:s,blockClass:r,blockSelector:n,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:u,maskInputOptions:d,maskTextFn:g,maskInputFn:_,slimDOMOptions:b,dataURLOptions:C,inlineImages:S,recordCanvas:R,preserveWhiteSpace:N,onSerialize:M,onIframeLoad:D,iframeLoadTimeout:k,onStylesheetLoad:O,stylesheetLoadTimeout:X,keepIframeSrcFn:de});se&&O(i,se)}},X),$}function gx(i,e){var t=e||{},s=t.mirror,r=s===void 0?new Fu:s,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,p=u===void 0?null:u,d=t.inlineStylesheet,g=d===void 0?!0:d,_=t.inlineImages,b=_===void 0?!1:_,v=t.recordCanvas,C=v===void 0?!1:v,E=t.maskAllInputs,S=E===void 0?!1:E,w=t.maskTextFn,R=t.maskInputFn,M=t.slimDOM,D=M===void 0?!1:M,G=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=S===!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}:S===!1?{password:!0}:S,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 Ns(i,{doc:i,mirror:r,blockClass:o,blockSelector:l,maskTextClass:h,maskTextSelector:p,skipChild:!1,inlineStylesheet:g,maskInputOptions:q,maskTextFn:w,maskInputFn:R,slimDOMOptions:N,dataURLOptions:G,inlineImages:b,recordCanvas:C,preserveWhiteSpace:k,onSerialize:O,onIframeLoad:V,iframeLoadTimeout:X,onStylesheetLoad:z,stylesheetLoadTimeout:de,keepIframeSrcFn:U,newlyAddedElement:!1})}function Ze(i,e,t=document){const s={capture:!0,passive:!0};return t.addEventListener(i,e,s),()=>t.removeEventListener(i,e,s)}const Us=`Please stop import mirror directly. Instead of that,\r
|
|
943
943
|
now you can use replayer.getMirror() to access the mirror instance of a replayer,\r
|
|
944
|
-
or you can use record.mirror to access the mirror instance during recording.`;let $u={map:{},getId(){return console.error(Us),-1},getNode(){return console.error(Us),null},removeNodeFromMap(){console.error(Us)},has(){return console.error(Us),!1},reset(){console.error(Us)}};typeof window<"u"&&window.Proxy&&window.Reflect&&($u=new Proxy($u,{get(i,e,t){return e==="map"&&console.error(Us),Reflect.get(i,e,t)}}));function Ti(i,e,t={}){let s=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?(s&&(clearTimeout(s),s=null),r=o,i.apply(l,n)):!s&&t.trailing!==!1&&(s=setTimeout(()=>{r=t.leading===!1?0:Date.now(),s=null,i.apply(l,n)},a))}}function yr(i,e,t,s,r=window){const n=r.Object.getOwnPropertyDescriptor(i,e);return r.Object.defineProperty(i,e,s?t:{set(o){setTimeout(()=>{t.set.call(this,o)},0),n&&n.set&&n.set.call(this,o)}}),()=>yr(i,e,n||{},!0)}function Gs(i,e,t){try{if(!(e in i))return()=>{};const s=i[e],r=t(s);return typeof r=="function"&&(r.prototype=r.prototype||{},Object.defineProperties(r,{__rrweb_original__:{enumerable:!1,value:s}})),i[e]=r,()=>{i[e]=s}}catch{return()=>{}}}function ju(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function Xu(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function Je(i,e,t,s){if(!i)return!1;const r=i.nodeType===i.ELEMENT_NODE?i:i.parentElement;if(!r)return!1;if(typeof e=="string"){if(r.classList.contains(e)||s&&r.closest("."+e)!==null)return!0}else if(_r(r,e,s))return!0;return!!(t&&(i.matches(t)||s&&r.closest(t)!==null))}function gx(i,e){return e.getId(i)!==-1}function Do(i,e){return e.getId(i)===Si}function Yu(i,e){if(Ci(i))return!1;const t=e.getId(i);return e.has(t)?i.parentNode&&i.parentNode.nodeType===i.DOCUMENT_NODE?!1:i.parentNode?Yu(i.parentNode,e):!0:!0}function qu(i){return!!i.changedTouches}function _x(i=window){"NodeList"in i&&!i.NodeList.prototype.forEach&&(i.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in i&&!i.DOMTokenList.prototype.forEach&&(i.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 Ku(i,e){return!!(i.nodeName==="IFRAME"&&e.getMeta(i))}function Zu(i,e){return!!(i.nodeName==="LINK"&&i.nodeType===i.ELEMENT_NODE&&i.getAttribute&&i.getAttribute("rel")==="stylesheet"&&e.getMeta(i))}function Ju(i){return!!(i!=null&&i.shadowRoot)}class yx{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 s;return t===void 0?s=this.id++:s=t,this.styleIDMap.set(e,s),this.idStyleMap.set(s,e),s}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=(i=>(i[i.DomContentLoaded=0]="DomContentLoaded",i[i.Load=1]="Load",i[i.FullSnapshot=2]="FullSnapshot",i[i.IncrementalSnapshot=3]="IncrementalSnapshot",i[i.Meta=4]="Meta",i[i.Custom=5]="Custom",i[i.Plugin=6]="Plugin",i))(ue||{}),oe=(i=>(i[i.Mutation=0]="Mutation",i[i.MouseMove=1]="MouseMove",i[i.MouseInteraction=2]="MouseInteraction",i[i.Scroll=3]="Scroll",i[i.ViewportResize=4]="ViewportResize",i[i.Input=5]="Input",i[i.TouchMove=6]="TouchMove",i[i.MediaInteraction=7]="MediaInteraction",i[i.StyleSheetRule=8]="StyleSheetRule",i[i.CanvasMutation=9]="CanvasMutation",i[i.Font=10]="Font",i[i.Log=11]="Log",i[i.Drag=12]="Drag",i[i.StyleDeclaration=13]="StyleDeclaration",i[i.Selection=14]="Selection",i[i.AdoptedStyleSheet=15]="AdoptedStyleSheet",i))(oe||{}),No=(i=>(i[i.MouseUp=0]="MouseUp",i[i.MouseDown=1]="MouseDown",i[i.Click=2]="Click",i[i.ContextMenu=3]="ContextMenu",i[i.DblClick=4]="DblClick",i[i.Focus=5]="Focus",i[i.Blur=6]="Blur",i[i.TouchStart=7]="TouchStart",i[i.TouchMove_Departed=8]="TouchMove_Departed",i[i.TouchEnd=9]="TouchEnd",i[i.TouchCancel=10]="TouchCancel",i))(No||{}),Fs=(i=>(i[i["2D"]=0]="2D",i[i.WebGL=1]="WebGL",i[i.WebGL2=2]="WebGL2",i))(Fs||{});function Qu(i){return"__ln"in i}class bx{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 s=0;s<e;s++)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&&Qu(e.previousSibling)){const s=e.previousSibling.__ln.next;t.next=s,t.previous=e.previousSibling.__ln,e.previousSibling.__ln.next=t,s&&(s.previous=t)}else if(e.nextSibling&&Qu(e.nextSibling)&&e.nextSibling.__ln.previous){const s=e.nextSibling.__ln.previous;t.previous=s,t.next=e.nextSibling.__ln,e.nextSibling.__ln.previous=t,s&&(s.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 ed=(i,e)=>`${i}@${e}`;class vx{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 bx,s=a=>{let l=a,c=Si;for(;c===Si;)l=l&&l.nextSibling,c=l&&this.mirror.getId(l);return c},r=a=>{var l,c,h,u;let p=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&&(p=a.getRootNode().host);let d=p;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 _=Ci(a.parentNode)?this.mirror.getId(p):this.mirror.getId(a.parentNode),b=s(a);if(_===-1||b===-1)return t.addNode(a);const v=Ns(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=>{Ku(C,this.mirror)&&this.iframeManager.addIframe(C),Zu(C,this.mirror)&&this.stylesheetManager.trackLinkElement(C),Ju(a)&&this.shadowDomManager.addShadowRoot(a.shadowRoot,this.doc)},onIframeLoad:(C,E)=>{this.iframeManager.attachIframe(C,E),this.shadowDomManager.observeAttachShadow(C)},onStylesheetLoad:(C,E)=>{this.stylesheetManager.attachLinkElement(C,E)}});v&&e.push({parentId:_,nextId:b,node:v})};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const a of Array.from(this.movedSet.values()))td(this.removes,a,this.mirror)&&!this.movedSet.has(a.parentNode)||r(a);for(const a of Array.from(this.addedSet.values()))!id(this.droppedSet,a)&&!td(this.removes,a,this.mirror)||id(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=s(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(s(c.value)===-1)continue;if(h!==-1){a=c;break}else{const p=c.value;if(p.parentNode&&p.parentNode.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const d=p.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(!Do(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:zu(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 s=e.target.getAttribute(e.attributeName);if(e.attributeName==="value"&&(s=Oo({maskInputOptions:this.maskInputOptions,tagName:e.target.tagName,type:e.target.getAttribute("type"),value:s,maskInputFn:this.maskInputFn})),Je(e.target,this.blockClass,this.blockSelector,!1)||s===e.oldValue)return;let r=this.attributes.find(n=>n.node===e.target);if(t.tagName==="IFRAME"&&e.attributeName==="src"&&!this.keepIframeSrcFn(s))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]=Vu(this.doc,t.tagName,e.attributeName,s);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 s=this.mirror.getId(t),r=Ci(e.target)?this.mirror.getId(e.target.host):this.mirror.getId(e.target);Je(e.target,this.blockClass,this.blockSelector,!1)||Do(t,this.mirror)||!gx(t,this.mirror)||(this.addedSet.has(t)?(Uo(this.addedSet,t),this.droppedSet.add(t)):this.addedSet.has(e.target)&&s===-1||Yu(e.target,this.mirror)||(this.movedSet.has(t)&&this.movedMap[ed(s,r)]?Uo(this.movedSet,t):this.removes.push({parentId:r,id:s,isShadow:Ci(e.target)&&Ei(e.target)?!0:void 0})),this.mapRemoves.push(t))});break}}},this.genAdds=(e,t)=>{if(this.mirror.hasNode(e)){if(Do(e,this.mirror))return;this.movedSet.add(e);let s=null;t&&this.mirror.hasNode(t)&&(s=this.mirror.getId(t)),s&&s!==-1&&(this.movedMap[ed(this.mirror.getId(e),s)]=!0)}else this.addedSet.add(e),this.droppedSet.delete(e);Je(e,this.blockClass,this.blockSelector,!1)||e.childNodes.forEach(s=>this.genAdds(s))}}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 Uo(i,e){i.delete(e),e.childNodes.forEach(t=>Uo(i,t))}function td(i,e,t){return i.length===0?!1:sd(i,e,t)}function sd(i,e,t){const{parentNode:s}=e;if(!s)return!1;const r=t.getId(s);return i.some(n=>n.id===r)?!0:sd(i,s,t)}function id(i,e){return i.size===0?!1:rd(i,e)}function rd(i,e){const{parentNode:t}=e;return t?i.has(t)?!0:rd(i,t):!1}const ls=[],nd=typeof CSSGroupingRule<"u",od=typeof CSSMediaRule<"u",ad=typeof CSSSupportsRule<"u",ld=typeof CSSConditionRule<"u";function Ai(i){try{if("composedPath"in i){const e=i.composedPath();if(e.length)return e[0]}else if("path"in i&&i.path.length)return i.path[0];return i.target}catch{return i.target}}function cd(i,e){var t,s;const r=new vx;ls.push(r),r.init(i);let n=window.MutationObserver||window.__rrMutationObserver;const o=(s=(t=window==null?void 0:window.Zone)===null||t===void 0?void 0:t.__symbol__)===null||s===void 0?void 0:s.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 xx({mousemoveCb:i,sampling:e,doc:t,mirror:s}){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=Ti(u=>{const p=Date.now()-a;i(o.map(d=>(d.timeOffset-=p,d)),u),o=[],a=null},n),c=Ti(u=>{const p=Ai(u),{clientX:d,clientY:g}=qu(u)?u.changedTouches[0]:u;a||(a=Date.now()),o.push({x:d,y:g,id:s.getId(p),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 Cx({mouseInteractionCb:i,doc:e,mirror:t,blockClass:s,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=Ai(h);if(Je(u,s,r,!0))return;const p=qu(h)?h.changedTouches[0]:h;if(!p)return;const d=t.getId(u),{clientX:g,clientY:_}=p;i({type:No[c],id:d,x:g,y:_})};return Object.keys(No).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 hd({scrollCb:i,doc:e,mirror:t,blockClass:s,blockSelector:r,sampling:n}){const o=Ti(a=>{const l=Ai(a);if(!l||Je(l,s,r,!0))return;const c=t.getId(l);if(l===e){const h=e.scrollingElement||e.documentElement;i({id:c,x:h.scrollLeft,y:h.scrollTop})}else i({id:c,x:l.scrollLeft,y:l.scrollTop})},n.scroll||100);return Ze("scroll",o,e)}function Ex({viewportResizeCb:i}){let e=-1,t=-1;const s=Ti(()=>{const r=ju(),n=Xu();(e!==r||t!==n)&&(i({width:Number(n),height:Number(r)}),e=r,t=n)},200);return Ze("resize",s,window)}function ud(i,e){const t=Object.assign({},i);return e||delete t.userTriggered,t}const Sx=["INPUT","TEXTAREA","SELECT"],dd=new WeakMap;function Tx({inputCb:i,doc:e,mirror:t,blockClass:s,blockSelector:r,ignoreClass:n,maskInputOptions:o,maskInputFn:a,sampling:l,userTriggeredOnInput:c}){function h(v){let C=Ai(v);const E=v.isTrusted;if(C&&C.tagName==="OPTION"&&(C=C.parentElement),!C||!C.tagName||Sx.indexOf(C.tagName)<0||Je(C,s,r,!0))return;const S=C.type;if(C.classList.contains(n))return;let w=C.value,R=!1;S==="radio"||S==="checkbox"?R=C.checked:(o[C.tagName.toLowerCase()]||o[S])&&(w=Oo({maskInputOptions:o,tagName:C.tagName,type:S,value:w,maskInputFn:a})),u(C,ud({text:w,isChecked:R,userTriggered:E},c));const M=C.name;S==="radio"&&M&&R&&e.querySelectorAll(`input[type="radio"][name="${M}"]`).forEach(D=>{D!==C&&u(D,ud({text:D.value,isChecked:!R,userTriggered:!1},c))})}function u(v,C){const E=dd.get(v);if(!E||E.text!==C.text||E.isChecked!==C.isChecked){dd.set(v,C);const S=t.getId(v);i(Object.assign(Object.assign({},C),{id:S}))}}const d=(l.input==="last"?["change"]:["input","change"]).map(v=>Ze(v,h,e)),g=e.defaultView;if(!g)return()=>{d.forEach(v=>v())};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(v=>yr(v[0],v[1],{set(){h({target:this})}},!1,g))),()=>{d.forEach(v=>v())}}function br(i){const e=[];function t(s,r){if(nd&&s.parentRule instanceof CSSGroupingRule||od&&s.parentRule instanceof CSSMediaRule||ad&&s.parentRule instanceof CSSSupportsRule||ld&&s.parentRule instanceof CSSConditionRule){const o=Array.from(s.parentRule.cssRules).indexOf(s);r.unshift(o)}else if(s.parentStyleSheet){const o=Array.from(s.parentStyleSheet.cssRules).indexOf(s);r.unshift(o)}return r}return t(i,e)}function Xt(i,e,t){let s,r;return i?(i.ownerNode?s=e.getId(i.ownerNode):r=t.getId(i),{styleId:r,id:s}):{}}function Ax({styleSheetRuleCb:i,mirror:e,stylesheetManager:t},{win:s}){const r=s.CSSStyleSheet.prototype.insertRule;s.CSSStyleSheet.prototype.insertRule=function(h,u){const{id:p,styleId:d}=Xt(this,e,t.styleMirror);return(p&&p!==-1||d&&d!==-1)&&i({id:p,styleId:d,adds:[{rule:h,index:u}]}),r.apply(this,[h,u])};const n=s.CSSStyleSheet.prototype.deleteRule;s.CSSStyleSheet.prototype.deleteRule=function(h){const{id:u,styleId:p}=Xt(this,e,t.styleMirror);return(u&&u!==-1||p&&p!==-1)&&i({id:u,styleId:p,removes:[{index:h}]}),n.apply(this,[h])};let o;s.CSSStyleSheet.prototype.replace&&(o=s.CSSStyleSheet.prototype.replace,s.CSSStyleSheet.prototype.replace=function(h){const{id:u,styleId:p}=Xt(this,e,t.styleMirror);return(u&&u!==-1||p&&p!==-1)&&i({id:u,styleId:p,replace:h}),o.apply(this,[h])});let a;s.CSSStyleSheet.prototype.replaceSync&&(a=s.CSSStyleSheet.prototype.replaceSync,s.CSSStyleSheet.prototype.replaceSync=function(h){const{id:u,styleId:p}=Xt(this,e,t.styleMirror);return(u&&u!==-1||p&&p!==-1)&&i({id:u,styleId:p,replaceSync:h}),a.apply(this,[h])});const l={};nd?l.CSSGroupingRule=s.CSSGroupingRule:(od&&(l.CSSMediaRule=s.CSSMediaRule),ld&&(l.CSSConditionRule=s.CSSConditionRule),ad&&(l.CSSSupportsRule=s.CSSSupportsRule));const c={};return Object.entries(l).forEach(([h,u])=>{c[h]={insertRule:u.prototype.insertRule,deleteRule:u.prototype.deleteRule},u.prototype.insertRule=function(p,d){const{id:g,styleId:_}=Xt(this.parentStyleSheet,e,t.styleMirror);return(g&&g!==-1||_&&_!==-1)&&i({id:g,styleId:_,adds:[{rule:p,index:[...br(this),d||0]}]}),c[h].insertRule.apply(this,[p,d])},u.prototype.deleteRule=function(p){const{id:d,styleId:g}=Xt(this.parentStyleSheet,e,t.styleMirror);return(d&&d!==-1||g&&g!==-1)&&i({id:d,styleId:g,removes:[{index:[...br(this),p]}]}),c[h].deleteRule.apply(this,[p])}}),()=>{s.CSSStyleSheet.prototype.insertRule=r,s.CSSStyleSheet.prototype.deleteRule=n,o&&(s.CSSStyleSheet.prototype.replace=o),a&&(s.CSSStyleSheet.prototype.replaceSync=a),Object.entries(l).forEach(([h,u])=>{u.prototype.insertRule=c[h].insertRule,u.prototype.deleteRule=c[h].deleteRule})}}function fd({mirror:i,stylesheetManager:e},t){var s,r,n;let o=null;t.nodeName==="#document"?o=i.getId(t):o=i.getId(t.host);const a=t.nodeName==="#document"?(s=t.defaultView)===null||s===void 0?void 0:s.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 wx({styleDeclarationCb:i,mirror:e,ignoreCSSAttributes:t,stylesheetManager:s},{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:p}=Xt((h=this.parentRule)===null||h===void 0?void 0:h.parentStyleSheet,e,s.styleMirror);return(u&&u!==-1||p&&p!==-1)&&i({id:u,styleId:p,set:{property:a,value:l,priority:c},index:br(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}=Xt((l=this.parentRule)===null||l===void 0?void 0:l.parentStyleSheet,e,s.styleMirror);return(c&&c!==-1||h&&h!==-1)&&i({id:c,styleId:h,remove:{property:a},index:br(this.parentRule)}),o.apply(this,[a])},()=>{r.CSSStyleDeclaration.prototype.setProperty=n,r.CSSStyleDeclaration.prototype.removeProperty=o}}function Ix({mediaInteractionCb:i,blockClass:e,blockSelector:t,mirror:s,sampling:r}){const n=a=>Ti(l=>{const c=Ai(l);if(!c||Je(c,e,t,!0))return;const{currentTime:h,volume:u,muted:p,playbackRate:d}=c;i({type:a,id:s.getId(c),currentTime:h,volume:u,muted:p,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 Rx({fontCb:i,doc:e}){const t=e.defaultView;if(!t)return()=>{};const s=[],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=Gs(e.fonts,"add",function(a){return function(l){return setTimeout(()=>{const c=r.get(l);c&&(i(c),r.delete(l))},0),a.apply(this,[l])}});return s.push(()=>{t.FontFace=n}),s.push(o),()=>{s.forEach(a=>a())}}function Mx(i){const{doc:e,mirror:t,blockClass:s,blockSelector:r,selectionCb:n}=i;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 p=l.getRangeAt(u),{startContainer:d,startOffset:g,endContainer:_,endOffset:b}=p;Je(d,s,r,!0)||Je(_,s,r,!0)||c.push({start:t.getId(d),startOffset:g,end:t.getId(_),endOffset:b})}n({ranges:c})};return a(),Ze("selectionchange",a)}function Px(i,e){const{mutationCb:t,mousemoveCb:s,mouseInteractionCb:r,scrollCb:n,viewportResizeCb:o,inputCb:a,mediaInteractionCb:l,styleSheetRuleCb:c,styleDeclarationCb:h,canvasMutationCb:u,fontCb:p,selectionCb:d}=i;i.mutationCb=(...g)=>{e.mutation&&e.mutation(...g),t(...g)},i.mousemoveCb=(...g)=>{e.mousemove&&e.mousemove(...g),s(...g)},i.mouseInteractionCb=(...g)=>{e.mouseInteraction&&e.mouseInteraction(...g),r(...g)},i.scrollCb=(...g)=>{e.scroll&&e.scroll(...g),n(...g)},i.viewportResizeCb=(...g)=>{e.viewportResize&&e.viewportResize(...g),o(...g)},i.inputCb=(...g)=>{e.input&&e.input(...g),a(...g)},i.mediaInteractionCb=(...g)=>{e.mediaInteaction&&e.mediaInteaction(...g),l(...g)},i.styleSheetRuleCb=(...g)=>{e.styleSheetRule&&e.styleSheetRule(...g),c(...g)},i.styleDeclarationCb=(...g)=>{e.styleDeclaration&&e.styleDeclaration(...g),h(...g)},i.canvasMutationCb=(...g)=>{e.canvasMutation&&e.canvasMutation(...g),u(...g)},i.fontCb=(...g)=>{e.font&&e.font(...g),p(...g)},i.selectionCb=(...g)=>{e.selection&&e.selection(...g),d(...g)}}function kx(i,e={}){const t=i.doc.defaultView;if(!t)return()=>{};Px(i,e);const s=cd(i,i.doc),r=xx(i),n=Cx(i),o=hd(i),a=Ex(i),l=Tx(i),c=Ix(i),h=Ax(i,{win:t}),u=fd(i,i.doc),p=wx(i,{win:t}),d=i.collectFonts?Rx(i):()=>{},g=Mx(i),_=[];for(const b of i.plugins)_.push(b.observer(b.callback,t,b.options));return()=>{ls.forEach(b=>b.reset()),s.disconnect(),r(),n(),o(),a(),l(),c(),h(),u(),p(),d(),g(),_.forEach(b=>b())}}class pd{constructor(e){this.generateIdFn=e,this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap}getId(e,t,s,r){const n=s||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 s=this.getIdToRemoteIdMap(e),r=this.getRemoteIdToIdMap(e);return t.map(n=>this.getId(e,n,s,r))}getRemoteId(e,t,s){const r=s||this.getRemoteIdToIdMap(e);if(typeof t!="number")return t;const n=r.get(t);return n||-1}getRemoteIds(e,t){const s=this.getRemoteIdToIdMap(e);return t.map(r=>this.getRemoteId(e,r,s))}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 Ox{constructor(e){this.iframes=new WeakMap,this.crossOriginIframeMap=new WeakMap,this.crossOriginIframeMirror=new pd(Wu),this.mutationCb=e.mutationCb,this.wrappedEmit=e.wrappedEmit,this.stylesheetManager=e.stylesheetManager,this.recordCrossOriginIframes=e.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new pd(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 s;this.mutationCb({adds:[{parentId:this.mirror.getId(e),nextId:null,node:t}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),(s=this.loadListener)===null||s===void 0||s.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 s=this.crossOriginIframeMap.get(e.source);if(!s)return;const r=this.transformCrossOriginEvent(s,e.data.event);r&&this.wrappedEmit(r,e.data.isCheckout)}}transformCrossOriginEvent(e,t){var s;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"]),(s=t.data.styles)===null||s===void 0||s.forEach(r=>{this.replaceStyleIds(r,e,["styleId"])}),t}}}replace(e,t,s,r){for(const n of r)!Array.isArray(t[n])&&typeof t[n]!="number"||(Array.isArray(t[n])?t[n]=e.getIds(s,t[n]):t[n]=e.getId(s,t[n]));return t}replaceIds(e,t,s){return this.replace(this.crossOriginIframeMirror,e,t,s)}replaceStyleIds(e,t,s){return this.replace(this.crossOriginIframeStyleMirror,e,t,s)}replaceIdOnNode(e,t){this.replaceIds(e,t,["id"]),"childNodes"in e&&e.childNodes.forEach(s=>{this.replaceIdOnNode(s,t)})}}class Bx{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(Gs(Element.prototype,"attachShadow",function(s){return function(r){const n=s.call(this,r);return this.shadowRoot&&t.addShadowRoot(this.shadowRoot,this.ownerDocument),n}}))}addShadowRoot(e,t){Ei(e)&&(this.shadowDoms.has(e)||(this.shadowDoms.add(e),cd(Object.assign(Object.assign({},this.bypassOptions),{doc:t,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this}),e),hd(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)),fd({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},e)},0)))}observeAttachShadow(e){if(e.contentWindow){const t=this;this.restorePatches.push(Gs(e.contentWindow.HTMLElement.prototype,"attachShadow",function(s){return function(r){const n=s.call(this,r);return this.shadowRoot&&t.addShadowRoot(this.shadowRoot,e.contentDocument),n}}))}}reset(){this.restorePatches.forEach(e=>e()),this.shadowDoms=new WeakSet}}/*! *****************************************************************************
|
|
944
|
+
or you can use record.mirror to access the mirror instance during recording.`;let $u={map:{},getId(){return console.error(Us),-1},getNode(){return console.error(Us),null},removeNodeFromMap(){console.error(Us)},has(){return console.error(Us),!1},reset(){console.error(Us)}};typeof window<"u"&&window.Proxy&&window.Reflect&&($u=new Proxy($u,{get(i,e,t){return e==="map"&&console.error(Us),Reflect.get(i,e,t)}}));function Ti(i,e,t={}){let s=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?(s&&(clearTimeout(s),s=null),r=o,i.apply(l,n)):!s&&t.trailing!==!1&&(s=setTimeout(()=>{r=t.leading===!1?0:Date.now(),s=null,i.apply(l,n)},a))}}function yr(i,e,t,s,r=window){const n=r.Object.getOwnPropertyDescriptor(i,e);return r.Object.defineProperty(i,e,s?t:{set(o){setTimeout(()=>{t.set.call(this,o)},0),n&&n.set&&n.set.call(this,o)}}),()=>yr(i,e,n||{},!0)}function Gs(i,e,t){try{if(!(e in i))return()=>{};const s=i[e],r=t(s);return typeof r=="function"&&(r.prototype=r.prototype||{},Object.defineProperties(r,{__rrweb_original__:{enumerable:!1,value:s}})),i[e]=r,()=>{i[e]=s}}catch{return()=>{}}}function ju(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function Xu(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function Je(i,e,t,s){if(!i)return!1;const r=i.nodeType===i.ELEMENT_NODE?i:i.parentElement;if(!r)return!1;if(typeof e=="string"){if(r.classList.contains(e)||s&&r.closest("."+e)!==null)return!0}else if(_r(r,e,s))return!0;return!!(t&&(i.matches(t)||s&&r.closest(t)!==null))}function _x(i,e){return e.getId(i)!==-1}function Do(i,e){return e.getId(i)===Si}function Yu(i,e){if(Ci(i))return!1;const t=e.getId(i);return e.has(t)?i.parentNode&&i.parentNode.nodeType===i.DOCUMENT_NODE?!1:i.parentNode?Yu(i.parentNode,e):!0:!0}function qu(i){return!!i.changedTouches}function yx(i=window){"NodeList"in i&&!i.NodeList.prototype.forEach&&(i.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in i&&!i.DOMTokenList.prototype.forEach&&(i.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 Ku(i,e){return!!(i.nodeName==="IFRAME"&&e.getMeta(i))}function Zu(i,e){return!!(i.nodeName==="LINK"&&i.nodeType===i.ELEMENT_NODE&&i.getAttribute&&i.getAttribute("rel")==="stylesheet"&&e.getMeta(i))}function Ju(i){return!!(i!=null&&i.shadowRoot)}class bx{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 s;return t===void 0?s=this.id++:s=t,this.styleIDMap.set(e,s),this.idStyleMap.set(s,e),s}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=(i=>(i[i.DomContentLoaded=0]="DomContentLoaded",i[i.Load=1]="Load",i[i.FullSnapshot=2]="FullSnapshot",i[i.IncrementalSnapshot=3]="IncrementalSnapshot",i[i.Meta=4]="Meta",i[i.Custom=5]="Custom",i[i.Plugin=6]="Plugin",i))(ue||{}),oe=(i=>(i[i.Mutation=0]="Mutation",i[i.MouseMove=1]="MouseMove",i[i.MouseInteraction=2]="MouseInteraction",i[i.Scroll=3]="Scroll",i[i.ViewportResize=4]="ViewportResize",i[i.Input=5]="Input",i[i.TouchMove=6]="TouchMove",i[i.MediaInteraction=7]="MediaInteraction",i[i.StyleSheetRule=8]="StyleSheetRule",i[i.CanvasMutation=9]="CanvasMutation",i[i.Font=10]="Font",i[i.Log=11]="Log",i[i.Drag=12]="Drag",i[i.StyleDeclaration=13]="StyleDeclaration",i[i.Selection=14]="Selection",i[i.AdoptedStyleSheet=15]="AdoptedStyleSheet",i))(oe||{}),No=(i=>(i[i.MouseUp=0]="MouseUp",i[i.MouseDown=1]="MouseDown",i[i.Click=2]="Click",i[i.ContextMenu=3]="ContextMenu",i[i.DblClick=4]="DblClick",i[i.Focus=5]="Focus",i[i.Blur=6]="Blur",i[i.TouchStart=7]="TouchStart",i[i.TouchMove_Departed=8]="TouchMove_Departed",i[i.TouchEnd=9]="TouchEnd",i[i.TouchCancel=10]="TouchCancel",i))(No||{}),Fs=(i=>(i[i["2D"]=0]="2D",i[i.WebGL=1]="WebGL",i[i.WebGL2=2]="WebGL2",i))(Fs||{});function Qu(i){return"__ln"in i}class vx{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 s=0;s<e;s++)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&&Qu(e.previousSibling)){const s=e.previousSibling.__ln.next;t.next=s,t.previous=e.previousSibling.__ln,e.previousSibling.__ln.next=t,s&&(s.previous=t)}else if(e.nextSibling&&Qu(e.nextSibling)&&e.nextSibling.__ln.previous){const s=e.nextSibling.__ln.previous;t.previous=s,t.next=e.nextSibling.__ln,e.nextSibling.__ln.previous=t,s&&(s.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 ed=(i,e)=>`${i}@${e}`;class xx{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 vx,s=a=>{let l=a,c=Si;for(;c===Si;)l=l&&l.nextSibling,c=l&&this.mirror.getId(l);return c},r=a=>{var l,c,h,u;let p=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&&(p=a.getRootNode().host);let d=p;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 _=Ci(a.parentNode)?this.mirror.getId(p):this.mirror.getId(a.parentNode),b=s(a);if(_===-1||b===-1)return t.addNode(a);const v=Ns(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=>{Ku(C,this.mirror)&&this.iframeManager.addIframe(C),Zu(C,this.mirror)&&this.stylesheetManager.trackLinkElement(C),Ju(a)&&this.shadowDomManager.addShadowRoot(a.shadowRoot,this.doc)},onIframeLoad:(C,E)=>{this.iframeManager.attachIframe(C,E),this.shadowDomManager.observeAttachShadow(C)},onStylesheetLoad:(C,E)=>{this.stylesheetManager.attachLinkElement(C,E)}});v&&e.push({parentId:_,nextId:b,node:v})};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const a of Array.from(this.movedSet.values()))td(this.removes,a,this.mirror)&&!this.movedSet.has(a.parentNode)||r(a);for(const a of Array.from(this.addedSet.values()))!id(this.droppedSet,a)&&!td(this.removes,a,this.mirror)||id(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=s(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(s(c.value)===-1)continue;if(h!==-1){a=c;break}else{const p=c.value;if(p.parentNode&&p.parentNode.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const d=p.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(!Do(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:zu(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 s=e.target.getAttribute(e.attributeName);if(e.attributeName==="value"&&(s=Oo({maskInputOptions:this.maskInputOptions,tagName:e.target.tagName,type:e.target.getAttribute("type"),value:s,maskInputFn:this.maskInputFn})),Je(e.target,this.blockClass,this.blockSelector,!1)||s===e.oldValue)return;let r=this.attributes.find(n=>n.node===e.target);if(t.tagName==="IFRAME"&&e.attributeName==="src"&&!this.keepIframeSrcFn(s))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]=Vu(this.doc,t.tagName,e.attributeName,s);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 s=this.mirror.getId(t),r=Ci(e.target)?this.mirror.getId(e.target.host):this.mirror.getId(e.target);Je(e.target,this.blockClass,this.blockSelector,!1)||Do(t,this.mirror)||!_x(t,this.mirror)||(this.addedSet.has(t)?(Uo(this.addedSet,t),this.droppedSet.add(t)):this.addedSet.has(e.target)&&s===-1||Yu(e.target,this.mirror)||(this.movedSet.has(t)&&this.movedMap[ed(s,r)]?Uo(this.movedSet,t):this.removes.push({parentId:r,id:s,isShadow:Ci(e.target)&&Ei(e.target)?!0:void 0})),this.mapRemoves.push(t))});break}}},this.genAdds=(e,t)=>{if(this.mirror.hasNode(e)){if(Do(e,this.mirror))return;this.movedSet.add(e);let s=null;t&&this.mirror.hasNode(t)&&(s=this.mirror.getId(t)),s&&s!==-1&&(this.movedMap[ed(this.mirror.getId(e),s)]=!0)}else this.addedSet.add(e),this.droppedSet.delete(e);Je(e,this.blockClass,this.blockSelector,!1)||e.childNodes.forEach(s=>this.genAdds(s))}}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 Uo(i,e){i.delete(e),e.childNodes.forEach(t=>Uo(i,t))}function td(i,e,t){return i.length===0?!1:sd(i,e,t)}function sd(i,e,t){const{parentNode:s}=e;if(!s)return!1;const r=t.getId(s);return i.some(n=>n.id===r)?!0:sd(i,s,t)}function id(i,e){return i.size===0?!1:rd(i,e)}function rd(i,e){const{parentNode:t}=e;return t?i.has(t)?!0:rd(i,t):!1}const ls=[],nd=typeof CSSGroupingRule<"u",od=typeof CSSMediaRule<"u",ad=typeof CSSSupportsRule<"u",ld=typeof CSSConditionRule<"u";function Ai(i){try{if("composedPath"in i){const e=i.composedPath();if(e.length)return e[0]}else if("path"in i&&i.path.length)return i.path[0];return i.target}catch{return i.target}}function cd(i,e){var t,s;const r=new xx;ls.push(r),r.init(i);let n=window.MutationObserver||window.__rrMutationObserver;const o=(s=(t=window==null?void 0:window.Zone)===null||t===void 0?void 0:t.__symbol__)===null||s===void 0?void 0:s.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 Cx({mousemoveCb:i,sampling:e,doc:t,mirror:s}){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=Ti(u=>{const p=Date.now()-a;i(o.map(d=>(d.timeOffset-=p,d)),u),o=[],a=null},n),c=Ti(u=>{const p=Ai(u),{clientX:d,clientY:g}=qu(u)?u.changedTouches[0]:u;a||(a=Date.now()),o.push({x:d,y:g,id:s.getId(p),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 Ex({mouseInteractionCb:i,doc:e,mirror:t,blockClass:s,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=Ai(h);if(Je(u,s,r,!0))return;const p=qu(h)?h.changedTouches[0]:h;if(!p)return;const d=t.getId(u),{clientX:g,clientY:_}=p;i({type:No[c],id:d,x:g,y:_})};return Object.keys(No).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 hd({scrollCb:i,doc:e,mirror:t,blockClass:s,blockSelector:r,sampling:n}){const o=Ti(a=>{const l=Ai(a);if(!l||Je(l,s,r,!0))return;const c=t.getId(l);if(l===e){const h=e.scrollingElement||e.documentElement;i({id:c,x:h.scrollLeft,y:h.scrollTop})}else i({id:c,x:l.scrollLeft,y:l.scrollTop})},n.scroll||100);return Ze("scroll",o,e)}function Sx({viewportResizeCb:i}){let e=-1,t=-1;const s=Ti(()=>{const r=ju(),n=Xu();(e!==r||t!==n)&&(i({width:Number(n),height:Number(r)}),e=r,t=n)},200);return Ze("resize",s,window)}function ud(i,e){const t=Object.assign({},i);return e||delete t.userTriggered,t}const Tx=["INPUT","TEXTAREA","SELECT"],dd=new WeakMap;function Ax({inputCb:i,doc:e,mirror:t,blockClass:s,blockSelector:r,ignoreClass:n,maskInputOptions:o,maskInputFn:a,sampling:l,userTriggeredOnInput:c}){function h(v){let C=Ai(v);const E=v.isTrusted;if(C&&C.tagName==="OPTION"&&(C=C.parentElement),!C||!C.tagName||Tx.indexOf(C.tagName)<0||Je(C,s,r,!0))return;const S=C.type;if(C.classList.contains(n))return;let w=C.value,R=!1;S==="radio"||S==="checkbox"?R=C.checked:(o[C.tagName.toLowerCase()]||o[S])&&(w=Oo({maskInputOptions:o,tagName:C.tagName,type:S,value:w,maskInputFn:a})),u(C,ud({text:w,isChecked:R,userTriggered:E},c));const M=C.name;S==="radio"&&M&&R&&e.querySelectorAll(`input[type="radio"][name="${M}"]`).forEach(D=>{D!==C&&u(D,ud({text:D.value,isChecked:!R,userTriggered:!1},c))})}function u(v,C){const E=dd.get(v);if(!E||E.text!==C.text||E.isChecked!==C.isChecked){dd.set(v,C);const S=t.getId(v);i(Object.assign(Object.assign({},C),{id:S}))}}const d=(l.input==="last"?["change"]:["input","change"]).map(v=>Ze(v,h,e)),g=e.defaultView;if(!g)return()=>{d.forEach(v=>v())};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(v=>yr(v[0],v[1],{set(){h({target:this})}},!1,g))),()=>{d.forEach(v=>v())}}function br(i){const e=[];function t(s,r){if(nd&&s.parentRule instanceof CSSGroupingRule||od&&s.parentRule instanceof CSSMediaRule||ad&&s.parentRule instanceof CSSSupportsRule||ld&&s.parentRule instanceof CSSConditionRule){const o=Array.from(s.parentRule.cssRules).indexOf(s);r.unshift(o)}else if(s.parentStyleSheet){const o=Array.from(s.parentStyleSheet.cssRules).indexOf(s);r.unshift(o)}return r}return t(i,e)}function Xt(i,e,t){let s,r;return i?(i.ownerNode?s=e.getId(i.ownerNode):r=t.getId(i),{styleId:r,id:s}):{}}function wx({styleSheetRuleCb:i,mirror:e,stylesheetManager:t},{win:s}){const r=s.CSSStyleSheet.prototype.insertRule;s.CSSStyleSheet.prototype.insertRule=function(h,u){const{id:p,styleId:d}=Xt(this,e,t.styleMirror);return(p&&p!==-1||d&&d!==-1)&&i({id:p,styleId:d,adds:[{rule:h,index:u}]}),r.apply(this,[h,u])};const n=s.CSSStyleSheet.prototype.deleteRule;s.CSSStyleSheet.prototype.deleteRule=function(h){const{id:u,styleId:p}=Xt(this,e,t.styleMirror);return(u&&u!==-1||p&&p!==-1)&&i({id:u,styleId:p,removes:[{index:h}]}),n.apply(this,[h])};let o;s.CSSStyleSheet.prototype.replace&&(o=s.CSSStyleSheet.prototype.replace,s.CSSStyleSheet.prototype.replace=function(h){const{id:u,styleId:p}=Xt(this,e,t.styleMirror);return(u&&u!==-1||p&&p!==-1)&&i({id:u,styleId:p,replace:h}),o.apply(this,[h])});let a;s.CSSStyleSheet.prototype.replaceSync&&(a=s.CSSStyleSheet.prototype.replaceSync,s.CSSStyleSheet.prototype.replaceSync=function(h){const{id:u,styleId:p}=Xt(this,e,t.styleMirror);return(u&&u!==-1||p&&p!==-1)&&i({id:u,styleId:p,replaceSync:h}),a.apply(this,[h])});const l={};nd?l.CSSGroupingRule=s.CSSGroupingRule:(od&&(l.CSSMediaRule=s.CSSMediaRule),ld&&(l.CSSConditionRule=s.CSSConditionRule),ad&&(l.CSSSupportsRule=s.CSSSupportsRule));const c={};return Object.entries(l).forEach(([h,u])=>{c[h]={insertRule:u.prototype.insertRule,deleteRule:u.prototype.deleteRule},u.prototype.insertRule=function(p,d){const{id:g,styleId:_}=Xt(this.parentStyleSheet,e,t.styleMirror);return(g&&g!==-1||_&&_!==-1)&&i({id:g,styleId:_,adds:[{rule:p,index:[...br(this),d||0]}]}),c[h].insertRule.apply(this,[p,d])},u.prototype.deleteRule=function(p){const{id:d,styleId:g}=Xt(this.parentStyleSheet,e,t.styleMirror);return(d&&d!==-1||g&&g!==-1)&&i({id:d,styleId:g,removes:[{index:[...br(this),p]}]}),c[h].deleteRule.apply(this,[p])}}),()=>{s.CSSStyleSheet.prototype.insertRule=r,s.CSSStyleSheet.prototype.deleteRule=n,o&&(s.CSSStyleSheet.prototype.replace=o),a&&(s.CSSStyleSheet.prototype.replaceSync=a),Object.entries(l).forEach(([h,u])=>{u.prototype.insertRule=c[h].insertRule,u.prototype.deleteRule=c[h].deleteRule})}}function fd({mirror:i,stylesheetManager:e},t){var s,r,n;let o=null;t.nodeName==="#document"?o=i.getId(t):o=i.getId(t.host);const a=t.nodeName==="#document"?(s=t.defaultView)===null||s===void 0?void 0:s.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 Ix({styleDeclarationCb:i,mirror:e,ignoreCSSAttributes:t,stylesheetManager:s},{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:p}=Xt((h=this.parentRule)===null||h===void 0?void 0:h.parentStyleSheet,e,s.styleMirror);return(u&&u!==-1||p&&p!==-1)&&i({id:u,styleId:p,set:{property:a,value:l,priority:c},index:br(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}=Xt((l=this.parentRule)===null||l===void 0?void 0:l.parentStyleSheet,e,s.styleMirror);return(c&&c!==-1||h&&h!==-1)&&i({id:c,styleId:h,remove:{property:a},index:br(this.parentRule)}),o.apply(this,[a])},()=>{r.CSSStyleDeclaration.prototype.setProperty=n,r.CSSStyleDeclaration.prototype.removeProperty=o}}function Rx({mediaInteractionCb:i,blockClass:e,blockSelector:t,mirror:s,sampling:r}){const n=a=>Ti(l=>{const c=Ai(l);if(!c||Je(c,e,t,!0))return;const{currentTime:h,volume:u,muted:p,playbackRate:d}=c;i({type:a,id:s.getId(c),currentTime:h,volume:u,muted:p,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 Mx({fontCb:i,doc:e}){const t=e.defaultView;if(!t)return()=>{};const s=[],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=Gs(e.fonts,"add",function(a){return function(l){return setTimeout(()=>{const c=r.get(l);c&&(i(c),r.delete(l))},0),a.apply(this,[l])}});return s.push(()=>{t.FontFace=n}),s.push(o),()=>{s.forEach(a=>a())}}function Px(i){const{doc:e,mirror:t,blockClass:s,blockSelector:r,selectionCb:n}=i;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 p=l.getRangeAt(u),{startContainer:d,startOffset:g,endContainer:_,endOffset:b}=p;Je(d,s,r,!0)||Je(_,s,r,!0)||c.push({start:t.getId(d),startOffset:g,end:t.getId(_),endOffset:b})}n({ranges:c})};return a(),Ze("selectionchange",a)}function kx(i,e){const{mutationCb:t,mousemoveCb:s,mouseInteractionCb:r,scrollCb:n,viewportResizeCb:o,inputCb:a,mediaInteractionCb:l,styleSheetRuleCb:c,styleDeclarationCb:h,canvasMutationCb:u,fontCb:p,selectionCb:d}=i;i.mutationCb=(...g)=>{e.mutation&&e.mutation(...g),t(...g)},i.mousemoveCb=(...g)=>{e.mousemove&&e.mousemove(...g),s(...g)},i.mouseInteractionCb=(...g)=>{e.mouseInteraction&&e.mouseInteraction(...g),r(...g)},i.scrollCb=(...g)=>{e.scroll&&e.scroll(...g),n(...g)},i.viewportResizeCb=(...g)=>{e.viewportResize&&e.viewportResize(...g),o(...g)},i.inputCb=(...g)=>{e.input&&e.input(...g),a(...g)},i.mediaInteractionCb=(...g)=>{e.mediaInteaction&&e.mediaInteaction(...g),l(...g)},i.styleSheetRuleCb=(...g)=>{e.styleSheetRule&&e.styleSheetRule(...g),c(...g)},i.styleDeclarationCb=(...g)=>{e.styleDeclaration&&e.styleDeclaration(...g),h(...g)},i.canvasMutationCb=(...g)=>{e.canvasMutation&&e.canvasMutation(...g),u(...g)},i.fontCb=(...g)=>{e.font&&e.font(...g),p(...g)},i.selectionCb=(...g)=>{e.selection&&e.selection(...g),d(...g)}}function Ox(i,e={}){const t=i.doc.defaultView;if(!t)return()=>{};kx(i,e);const s=cd(i,i.doc),r=Cx(i),n=Ex(i),o=hd(i),a=Sx(i),l=Ax(i),c=Rx(i),h=wx(i,{win:t}),u=fd(i,i.doc),p=Ix(i,{win:t}),d=i.collectFonts?Mx(i):()=>{},g=Px(i),_=[];for(const b of i.plugins)_.push(b.observer(b.callback,t,b.options));return()=>{ls.forEach(b=>b.reset()),s.disconnect(),r(),n(),o(),a(),l(),c(),h(),u(),p(),d(),g(),_.forEach(b=>b())}}class pd{constructor(e){this.generateIdFn=e,this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap}getId(e,t,s,r){const n=s||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 s=this.getIdToRemoteIdMap(e),r=this.getRemoteIdToIdMap(e);return t.map(n=>this.getId(e,n,s,r))}getRemoteId(e,t,s){const r=s||this.getRemoteIdToIdMap(e);if(typeof t!="number")return t;const n=r.get(t);return n||-1}getRemoteIds(e,t){const s=this.getRemoteIdToIdMap(e);return t.map(r=>this.getRemoteId(e,r,s))}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 Bx{constructor(e){this.iframes=new WeakMap,this.crossOriginIframeMap=new WeakMap,this.crossOriginIframeMirror=new pd(Wu),this.mutationCb=e.mutationCb,this.wrappedEmit=e.wrappedEmit,this.stylesheetManager=e.stylesheetManager,this.recordCrossOriginIframes=e.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new pd(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 s;this.mutationCb({adds:[{parentId:this.mirror.getId(e),nextId:null,node:t}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),(s=this.loadListener)===null||s===void 0||s.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 s=this.crossOriginIframeMap.get(e.source);if(!s)return;const r=this.transformCrossOriginEvent(s,e.data.event);r&&this.wrappedEmit(r,e.data.isCheckout)}}transformCrossOriginEvent(e,t){var s;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"]),(s=t.data.styles)===null||s===void 0||s.forEach(r=>{this.replaceStyleIds(r,e,["styleId"])}),t}}}replace(e,t,s,r){for(const n of r)!Array.isArray(t[n])&&typeof t[n]!="number"||(Array.isArray(t[n])?t[n]=e.getIds(s,t[n]):t[n]=e.getId(s,t[n]));return t}replaceIds(e,t,s){return this.replace(this.crossOriginIframeMirror,e,t,s)}replaceStyleIds(e,t,s){return this.replace(this.crossOriginIframeStyleMirror,e,t,s)}replaceIdOnNode(e,t){this.replaceIds(e,t,["id"]),"childNodes"in e&&e.childNodes.forEach(s=>{this.replaceIdOnNode(s,t)})}}class Dx{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(Gs(Element.prototype,"attachShadow",function(s){return function(r){const n=s.call(this,r);return this.shadowRoot&&t.addShadowRoot(this.shadowRoot,this.ownerDocument),n}}))}addShadowRoot(e,t){Ei(e)&&(this.shadowDoms.has(e)||(this.shadowDoms.add(e),cd(Object.assign(Object.assign({},this.bypassOptions),{doc:t,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this}),e),hd(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)),fd({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},e)},0)))}observeAttachShadow(e){if(e.contentWindow){const t=this;this.restorePatches.push(Gs(e.contentWindow.HTMLElement.prototype,"attachShadow",function(s){return function(r){const n=s.call(this,r);return this.shadowRoot&&t.addShadowRoot(this.shadowRoot,e.contentDocument),n}}))}}reset(){this.restorePatches.forEach(e=>e()),this.shadowDoms=new WeakSet}}/*! *****************************************************************************
|
|
945
945
|
Copyright (c) Microsoft Corporation.
|
|
946
946
|
|
|
947
947
|
Permission to use, copy, modify, and/or distribute this software for any
|
|
@@ -954,10 +954,10 @@ or you can use record.mirror to access the mirror instance during recording.`;le
|
|
|
954
954
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
955
955
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
956
956
|
PERFORMANCE OF THIS SOFTWARE.
|
|
957
|
-
***************************************************************************** */function
|
|
958
|
-
`,10)+1,n=s.substring(r)+"";return function(a){return new xd(n,Object.assign({},a,{eval:!0}))}}function
|
|
959
|
-
`,10)+1,n=s.substring(r)+"",o=new Blob([n],{type:"application/javascript"});return URL.createObjectURL(o)}function Xx(i,e,t){var s;return function(n){return s=s||jx(i),new Worker(s,n)}}var Yx=Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]";function qx(){return Yx}function Kx(i,e,t){return qx()?zx(i):Xx(i)}var Zx=Kx("Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewogICAgJ3VzZSBzdHJpY3QnOwoKICAgIC8qISAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKg0KICAgIENvcHlyaWdodCAoYykgTWljcm9zb2Z0IENvcnBvcmF0aW9uLg0KDQogICAgUGVybWlzc2lvbiB0byB1c2UsIGNvcHksIG1vZGlmeSwgYW5kL29yIGRpc3RyaWJ1dGUgdGhpcyBzb2Z0d2FyZSBmb3IgYW55DQogICAgcHVycG9zZSB3aXRoIG9yIHdpdGhvdXQgZmVlIGlzIGhlcmVieSBncmFudGVkLg0KDQogICAgVEhFIFNPRlRXQVJFIElTIFBST1ZJREVEICJBUyBJUyIgQU5EIFRIRSBBVVRIT1IgRElTQ0xBSU1TIEFMTCBXQVJSQU5USUVTIFdJVEgNCiAgICBSRUdBUkQgVE8gVEhJUyBTT0ZUV0FSRSBJTkNMVURJTkcgQUxMIElNUExJRUQgV0FSUkFOVElFUyBPRiBNRVJDSEFOVEFCSUxJVFkNCiAgICBBTkQgRklUTkVTUy4gSU4gTk8gRVZFTlQgU0hBTEwgVEhFIEFVVEhPUiBCRSBMSUFCTEUgRk9SIEFOWSBTUEVDSUFMLCBESVJFQ1QsDQogICAgSU5ESVJFQ1QsIE9SIENPTlNFUVVFTlRJQUwgREFNQUdFUyBPUiBBTlkgREFNQUdFUyBXSEFUU09FVkVSIFJFU1VMVElORyBGUk9NDQogICAgTE9TUyBPRiBVU0UsIERBVEEgT1IgUFJPRklUUywgV0hFVEhFUiBJTiBBTiBBQ1RJT04gT0YgQ09OVFJBQ1QsIE5FR0xJR0VOQ0UgT1INCiAgICBPVEhFUiBUT1JUSU9VUyBBQ1RJT04sIEFSSVNJTkcgT1VUIE9GIE9SIElOIENPTk5FQ1RJT04gV0lUSCBUSEUgVVNFIE9SDQogICAgUEVSRk9STUFOQ0UgT0YgVEhJUyBTT0ZUV0FSRS4NCiAgICAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKiAqLw0KDQogICAgZnVuY3Rpb24gX19hd2FpdGVyKHRoaXNBcmcsIF9hcmd1bWVudHMsIFAsIGdlbmVyYXRvcikgew0KICAgICAgICBmdW5jdGlvbiBhZG9wdCh2YWx1ZSkgeyByZXR1cm4gdmFsdWUgaW5zdGFuY2VvZiBQID8gdmFsdWUgOiBuZXcgUChmdW5jdGlvbiAocmVzb2x2ZSkgeyByZXNvbHZlKHZhbHVlKTsgfSk7IH0NCiAgICAgICAgcmV0dXJuIG5ldyAoUCB8fCAoUCA9IFByb21pc2UpKShmdW5jdGlvbiAocmVzb2x2ZSwgcmVqZWN0KSB7DQogICAgICAgICAgICBmdW5jdGlvbiBmdWxmaWxsZWQodmFsdWUpIHsgdHJ5IHsgc3RlcChnZW5lcmF0b3IubmV4dCh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiByZWplY3RlZCh2YWx1ZSkgeyB0cnkgeyBzdGVwKGdlbmVyYXRvclsidGhyb3ciXSh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiBzdGVwKHJlc3VsdCkgeyByZXN1bHQuZG9uZSA/IHJlc29sdmUocmVzdWx0LnZhbHVlKSA6IGFkb3B0KHJlc3VsdC52YWx1ZSkudGhlbihmdWxmaWxsZWQsIHJlamVjdGVkKTsgfQ0KICAgICAgICAgICAgc3RlcCgoZ2VuZXJhdG9yID0gZ2VuZXJhdG9yLmFwcGx5KHRoaXNBcmcsIF9hcmd1bWVudHMgfHwgW10pKS5uZXh0KCkpOw0KICAgICAgICB9KTsNCiAgICB9CgogICAgLyoKICAgICAqIGJhc2U2NC1hcnJheWJ1ZmZlciAxLjAuMSA8aHR0cHM6Ly9naXRodWIuY29tL25pa2xhc3ZoL2Jhc2U2NC1hcnJheWJ1ZmZlcj4KICAgICAqIENvcHlyaWdodCAoYykgMjAyMSBOaWtsYXMgdm9uIEhlcnR6ZW4gPGh0dHBzOi8vaGVydHplbi5jb20+CiAgICAgKiBSZWxlYXNlZCB1bmRlciBNSVQgTGljZW5zZQogICAgICovCiAgICB2YXIgY2hhcnMgPSAnQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyc7CiAgICAvLyBVc2UgYSBsb29rdXAgdGFibGUgdG8gZmluZCB0aGUgaW5kZXguCiAgICB2YXIgbG9va3VwID0gdHlwZW9mIFVpbnQ4QXJyYXkgPT09ICd1bmRlZmluZWQnID8gW10gOiBuZXcgVWludDhBcnJheSgyNTYpOwogICAgZm9yICh2YXIgaSA9IDA7IGkgPCBjaGFycy5sZW5ndGg7IGkrKykgewogICAgICAgIGxvb2t1cFtjaGFycy5jaGFyQ29kZUF0KGkpXSA9IGk7CiAgICB9CiAgICB2YXIgZW5jb2RlID0gZnVuY3Rpb24gKGFycmF5YnVmZmVyKSB7CiAgICAgICAgdmFyIGJ5dGVzID0gbmV3IFVpbnQ4QXJyYXkoYXJyYXlidWZmZXIpLCBpLCBsZW4gPSBieXRlcy5sZW5ndGgsIGJhc2U2NCA9ICcnOwogICAgICAgIGZvciAoaSA9IDA7IGkgPCBsZW47IGkgKz0gMykgewogICAgICAgICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaV0gPj4gMl07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1soKGJ5dGVzW2ldICYgMykgPDwgNCkgfCAoYnl0ZXNbaSArIDFdID4+IDQpXTsKICAgICAgICAgICAgYmFzZTY0ICs9IGNoYXJzWygoYnl0ZXNbaSArIDFdICYgMTUpIDw8IDIpIHwgKGJ5dGVzW2kgKyAyXSA+PiA2KV07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1tieXRlc1tpICsgMl0gJiA2M107CiAgICAgICAgfQogICAgICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgJz0nOwogICAgICAgIH0KICAgICAgICBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgJz09JzsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIGJhc2U2NDsKICAgIH07CgogICAgY29uc3QgbGFzdEJsb2JNYXAgPSBuZXcgTWFwKCk7DQogICAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gbmV3IE1hcCgpOw0KICAgIGZ1bmN0aW9uIGdldFRyYW5zcGFyZW50QmxvYkZvcih3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucykgew0KICAgICAgICByZXR1cm4gX19hd2FpdGVyKHRoaXMsIHZvaWQgMCwgdm9pZCAwLCBmdW5jdGlvbiogKCkgew0KICAgICAgICAgICAgY29uc3QgaWQgPSBgJHt3aWR0aH0tJHtoZWlnaHR9YDsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgaWYgKHRyYW5zcGFyZW50QmxvYk1hcC5oYXMoaWQpKQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gdHJhbnNwYXJlbnRCbG9iTWFwLmdldChpZCk7DQogICAgICAgICAgICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsNCiAgICAgICAgICAgICAgICBvZmZzY3JlZW4uZ2V0Q29udGV4dCgnMmQnKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0geWllbGQgYmxvYi5hcnJheUJ1ZmZlcigpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7DQogICAgICAgICAgICAgICAgdHJhbnNwYXJlbnRCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICByZXR1cm4gYmFzZTY0Ow0KICAgICAgICAgICAgfQ0KICAgICAgICAgICAgZWxzZSB7DQogICAgICAgICAgICAgICAgcmV0dXJuICcnOw0KICAgICAgICAgICAgfQ0KICAgICAgICB9KTsNCiAgICB9DQogICAgY29uc3Qgd29ya2VyID0gc2VsZjsNCiAgICB3b3JrZXIub25tZXNzYWdlID0gZnVuY3Rpb24gKGUpIHsNCiAgICAgICAgcmV0dXJuIF9fYXdhaXRlcih0aGlzLCB2b2lkIDAsIHZvaWQgMCwgZnVuY3Rpb24qICgpIHsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgY29uc3QgeyBpZCwgYml0bWFwLCB3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucyB9ID0gZS5kYXRhOw0KICAgICAgICAgICAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zKTsNCiAgICAgICAgICAgICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGN0eCA9IG9mZnNjcmVlbi5nZXRDb250ZXh0KCcyZCcpOw0KICAgICAgICAgICAgICAgIGN0eC5kcmF3SW1hZ2UoYml0bWFwLCAwLCAwKTsNCiAgICAgICAgICAgICAgICBiaXRtYXAuY2xvc2UoKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IHR5cGUgPSBibG9iLnR5cGU7DQogICAgICAgICAgICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSB5aWVsZCBibG9iLmFycmF5QnVmZmVyKCk7DQogICAgICAgICAgICAgICAgY29uc3QgYmFzZTY0ID0gZW5jb2RlKGFycmF5QnVmZmVyKTsNCiAgICAgICAgICAgICAgICBpZiAoIWxhc3RCbG9iTWFwLmhhcyhpZCkgJiYgKHlpZWxkIHRyYW5zcGFyZW50QmFzZTY0KSA9PT0gYmFzZTY0KSB7DQogICAgICAgICAgICAgICAgICAgIGxhc3RCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHdvcmtlci5wb3N0TWVzc2FnZSh7IGlkIH0pOw0KICAgICAgICAgICAgICAgIH0NCiAgICAgICAgICAgICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7DQogICAgICAgICAgICAgICAgd29ya2VyLnBvc3RNZXNzYWdlKHsNCiAgICAgICAgICAgICAgICAgICAgaWQsDQogICAgICAgICAgICAgICAgICAgIHR5cGUsDQogICAgICAgICAgICAgICAgICAgIGJhc2U2NCwNCiAgICAgICAgICAgICAgICAgICAgd2lkdGgsDQogICAgICAgICAgICAgICAgICAgIGhlaWdodCwNCiAgICAgICAgICAgICAgICB9KTsNCiAgICAgICAgICAgICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7DQogICAgICAgICAgICB9DQogICAgICAgICAgICBlbHNlIHsNCiAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsNCiAgICAgICAgICAgIH0NCiAgICAgICAgfSk7DQogICAgfTsKCn0pKCk7Cgo=");class Jx{constructor(e){this.pendingCanvasMutations=new Map,this.rafStamps={latestId:0,invokeId:null},this.frozen=!1,this.locked=!1,this.processMutation=(l,c)=>{(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId||!this.rafStamps.invokeId)&&(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(l)||this.pendingCanvasMutations.set(l,[]),this.pendingCanvasMutations.get(l).push(c)};const{sampling:t="all",win:s,blockClass:r,blockSelector:n,recordCanvas:o,dataURLOptions:a}=e;this.mutationCb=e.mutationCb,this.mirror=e.mirror,o&&t==="all"&&this.initCanvasMutationObserver(s,r,n),o&&typeof t=="number"&&this.initCanvasFPSObserver(t,s,r,n,{dataURLOptions:a})}reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}initCanvasFPSObserver(e,t,s,r,n){const o=bd(t,s,r),a=new Map,l=new Zx;l.onmessage=g=>{const{id:_}=g.data;if(a.set(_,!1),!("base64"in g.data))return;const{base64:b,type:v,width:C,height:E}=g.data;this.mutationCb({id:_,type:Fs["2D"],commands:[{property:"clearRect",args:[0,0,C,E]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:b}],type:v}]},0,0]}]})};const c=1e3/e;let h=0,u;const p=()=>{const g=[];return t.document.querySelectorAll("canvas").forEach(_=>{Je(_,s,r,!0)||g.push(_)}),g},d=g=>{if(h&&g-h<c){u=requestAnimationFrame(d);return}h=g,p().forEach(_=>Nx(this,void 0,void 0,function*(){var b;const v=this.mirror.getId(_);if(a.get(v))return;if(a.set(v,!0),["webgl","webgl2"].includes(_.__context)){const E=_.getContext(_.__context);((b=E==null?void 0:E.getContextAttributes())===null||b===void 0?void 0:b.preserveDrawingBuffer)===!1&&(E==null||E.clear(E.COLOR_BUFFER_BIT))}const C=yield createImageBitmap(_);l.postMessage({id:v,bitmap:C,width:_.width,height:_.height,dataURLOptions:n.dataURLOptions},[C])})),u=requestAnimationFrame(d)};u=requestAnimationFrame(d),this.resetObservers=()=>{o(),cancelAnimationFrame(u)}}initCanvasMutationObserver(e,t,s){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();const r=bd(e,t,s),n=Lx(this.processMutation.bind(this),e,t,s),o=Wx(this.processMutation.bind(this),e,t,s,this.mirror);this.resetObservers=()=>{r(),n(),o()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){const e=t=>{this.rafStamps.latestId=t,requestAnimationFrame(e)};requestAnimationFrame(e)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((e,t)=>{const s=this.mirror.getId(t);this.flushPendingCanvasMutationFor(t,s)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(e,t){if(this.frozen||this.locked)return;const s=this.pendingCanvasMutations.get(e);if(!s||t===-1)return;const r=s.map(o=>Dx(o,["type"])),{type:n}=s[0];this.mutationCb({id:t,type:n,commands:r}),this.pendingCanvasMutations.delete(e)}}class Qx{constructor(e){this.trackedLinkElements=new WeakSet,this.styleMirror=new yx,this.mutationCb=e.mutationCb,this.adoptedStyleSheetCb=e.adoptedStyleSheetCb}attachLinkElement(e,t){"_cssText"in t.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:t.id,attributes:t.attributes}]}),this.trackLinkElement(e)}trackLinkElement(e){this.trackedLinkElements.has(e)||(this.trackedLinkElements.add(e),this.trackStylesheetInLinkElement(e))}adoptStyleSheets(e,t){if(e.length===0)return;const s={id:t,styleIds:[]},r=[];for(const n of e){let o;if(this.styleMirror.has(n))o=this.styleMirror.getId(n);else{o=this.styleMirror.add(n);const a=Array.from(n.rules||CSSRule);r.push({styleId:o,rules:a.map((l,c)=>({rule:Gu(l),index:c}))})}s.styleIds.push(o)}r.length>0&&(s.styles=r),this.adoptedStyleSheetCb(s)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(e){}}function Ge(i){return Object.assign(Object.assign({},i),{timestamp:Date.now()})}let Oe,Cr,Go,Er=!1;const ut=Xv();function Ws(i={}){const{emit:e,checkoutEveryNms:t,checkoutEveryNth:s,blockClass:r="rr-block",blockSelector:n=null,ignoreClass:o="rr-ignore",maskTextClass:a="rr-mask",maskTextSelector:l=null,inlineStylesheet:c=!0,maskAllInputs:h,maskInputOptions:u,slimDOMOptions:p,maskInputFn:d,maskTextFn:g,hooks:_,packFn:b,sampling:v={},dataURLOptions:C={},mousemoveWait:E,recordCanvas:S=!1,recordCrossOriginIframes:w=!1,userTriggeredOnInput:R=!1,collectFonts:M=!1,inlineImages:D=!1,plugins:G,keepIframeSrcFn:k=()=>!1,ignoreCSSAttributes:O=new Set([])}=i,V=w?window.parent===window:!0;let X=!1;if(!V)try{window.parent.document,X=!1}catch{X=!0}if(V&&!e)throw new Error("emit function is required");E!==void 0&&v.mousemove===void 0&&(v.mousemove=E),ut.reset();const z=h===!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}:u!==void 0?u:{password:!0},de=p===!0||p==="all"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:p==="all",headMetaDescKeywords:p==="all"}:p||{};_x();let B,U=0;const q=F=>{for(const fe of G||[])fe.eventProcessor&&(F=fe.eventProcessor(F));return b&&(F=b(F)),F};Oe=(F,fe)=>{var le;if(!((le=ls[0])===null||le===void 0)&&le.isFrozen()&&F.type!==ue.FullSnapshot&&!(F.type===ue.IncrementalSnapshot&&F.data.source===oe.Mutation)&&ls.forEach(L=>L.unfreeze()),V)e==null||e(q(F),fe);else if(X){const L={type:"rrweb",event:q(F),isCheckout:fe};window.parent.postMessage(L,"*")}if(F.type===ue.FullSnapshot)B=F,U=0;else if(F.type===ue.IncrementalSnapshot){if(F.data.source===oe.Mutation&&F.data.isAttachIframe)return;U++;const L=s&&U>=s,me=t&&F.timestamp-B.timestamp>t;(L||me)&&Cr(!0)}};const N=F=>{Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Mutation},F)}))},K=F=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Scroll},F)})),Z=F=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.CanvasMutation},F)})),$=F=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.AdoptedStyleSheet},F)})),ae=new Qx({mutationCb:N,adoptedStyleSheetCb:$}),xe=new Ox({mirror:ut,mutationCb:N,stylesheetManager:ae,recordCrossOriginIframes:w,wrappedEmit:Oe});for(const F of G||[])F.getMirror&&F.getMirror({nodeMirror:ut,crossOriginIframeMirror:xe.crossOriginIframeMirror,crossOriginIframeStyleMirror:xe.crossOriginIframeStyleMirror});Go=new Jx({recordCanvas:S,mutationCb:Z,win:window,blockClass:r,blockSelector:n,mirror:ut,sampling:v.canvas,dataURLOptions:C});const Se=new Bx({mutationCb:N,scrollCb:K,bypassOptions:{blockClass:r,blockSelector:n,maskTextClass:a,maskTextSelector:l,inlineStylesheet:c,maskInputOptions:z,dataURLOptions:C,maskTextFn:g,maskInputFn:d,recordCanvas:S,inlineImages:D,sampling:v,slimDOMOptions:de,iframeManager:xe,stylesheetManager:ae,canvasManager:Go,keepIframeSrcFn:k},mirror:ut});Cr=(F=!1)=>{var fe,le,L,me,Y,se;Oe(Ge({type:ue.Meta,data:{href:window.location.href,width:Xu(),height:ju()}}),F),ae.reset(),ls.forEach(ce=>ce.lock());const we=mx(document,{mirror:ut,blockClass:r,blockSelector:n,maskTextClass:a,maskTextSelector:l,inlineStylesheet:c,maskAllInputs:z,maskTextFn:g,slimDOM:de,dataURLOptions:C,recordCanvas:S,inlineImages:D,onSerialize:ce=>{Ku(ce,ut)&&xe.addIframe(ce),Zu(ce,ut)&&ae.trackLinkElement(ce),Ju(ce)&&Se.addShadowRoot(ce.shadowRoot,document)},onIframeLoad:(ce,He)=>{xe.attachIframe(ce,He),Se.observeAttachShadow(ce)},onStylesheetLoad:(ce,He)=>{ae.attachLinkElement(ce,He)},keepIframeSrcFn:k});if(!we)return console.warn("Failed to snapshot the document");Oe(Ge({type:ue.FullSnapshot,data:{node:we,initialOffset:{left:window.pageXOffset!==void 0?window.pageXOffset:(document==null?void 0:document.documentElement.scrollLeft)||((le=(fe=document==null?void 0:document.body)===null||fe===void 0?void 0:fe.parentElement)===null||le===void 0?void 0:le.scrollLeft)||((L=document==null?void 0:document.body)===null||L===void 0?void 0:L.scrollLeft)||0,top:window.pageYOffset!==void 0?window.pageYOffset:(document==null?void 0:document.documentElement.scrollTop)||((Y=(me=document==null?void 0:document.body)===null||me===void 0?void 0:me.parentElement)===null||Y===void 0?void 0:Y.scrollTop)||((se=document==null?void 0:document.body)===null||se===void 0?void 0:se.scrollTop)||0}}})),ls.forEach(ce=>ce.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&ae.adoptStyleSheets(document.adoptedStyleSheets,ut.getId(document))};try{const F=[];F.push(Ze("DOMContentLoaded",()=>{Oe(Ge({type:ue.DomContentLoaded,data:{}}))}));const fe=L=>{var me;return kx({mutationCb:N,mousemoveCb:(Y,se)=>Oe(Ge({type:ue.IncrementalSnapshot,data:{source:se,positions:Y}})),mouseInteractionCb:Y=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.MouseInteraction},Y)})),scrollCb:K,viewportResizeCb:Y=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.ViewportResize},Y)})),inputCb:Y=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Input},Y)})),mediaInteractionCb:Y=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.MediaInteraction},Y)})),styleSheetRuleCb:Y=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.StyleSheetRule},Y)})),styleDeclarationCb:Y=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.StyleDeclaration},Y)})),canvasMutationCb:Z,fontCb:Y=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Font},Y)})),selectionCb:Y=>{Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Selection},Y)}))},blockClass:r,ignoreClass:o,maskTextClass:a,maskTextSelector:l,maskInputOptions:z,inlineStylesheet:c,sampling:v,recordCanvas:S,inlineImages:D,userTriggeredOnInput:R,collectFonts:M,doc:L,maskInputFn:d,maskTextFn:g,keepIframeSrcFn:k,blockSelector:n,slimDOMOptions:de,dataURLOptions:C,mirror:ut,iframeManager:xe,stylesheetManager:ae,shadowDomManager:Se,canvasManager:Go,ignoreCSSAttributes:O,plugins:((me=G==null?void 0:G.filter(Y=>Y.observer))===null||me===void 0?void 0:me.map(Y=>({observer:Y.observer,options:Y.options,callback:se=>Oe(Ge({type:ue.Plugin,data:{plugin:Y.name,payload:se}}))})))||[]},_)};xe.addLoadListener(L=>{F.push(fe(L.contentDocument))});const le=()=>{Cr(),F.push(fe(document)),Er=!0};return document.readyState==="interactive"||document.readyState==="complete"?le():F.push(Ze("load",()=>{Oe(Ge({type:ue.Load,data:{}})),le()},window)),()=>{F.forEach(L=>L()),Er=!1}}catch(F){console.warn(F)}}Ws.addCustomEvent=(i,e)=>{if(!Er)throw new Error("please add custom event after start recording");Oe(Ge({type:ue.Custom,data:{tag:i,payload:e}}))},Ws.freezePage=()=>{ls.forEach(i=>i.freeze())},Ws.takeFullSnapshot=i=>{if(!Er)throw new Error("please take full snapshot after start recording");Cr(i)},Ws.mirror=ut;const e0=3e4,t0=3,s0=0;function i0(i){if(i.type!==t0)return!1;const e=i.data;if(!e||e.source!==s0)return!1;const{adds:t,removes:s,texts:r,attributes:n}=e;return t&&t.length||s&&s.length||r&&r.length?!1:n&&n.length>0?n.every(o=>o.attributes&&Object.keys(o.attributes).length===1&&"style"in o.attributes):!0}function r0(){for(const i of[Text,Comment,CDATASection,ProcessingInstruction])i.prototype.matches||(i.prototype.matches=function(){return!1})}class Cd{constructor(){this.onEvent=null,this.stopFn=null,this._recording=!1,this._paused=!1}get isRecording(){return this._recording}get isPaused(){return this._paused}start(){if(this._recording)return;r0();const e=Ws({emit:t=>{var s;this._paused||i0(t)||(s=this.onEvent)==null||s.call(this,t)},checkoutEveryNms:e0,blockClass:"hs-no-record",blockSelector:'#holostaff-widget-root, #holostaff-agent, [id^="anam-avatar"], video, [autocomplete^="cc-"], [data-hs-no-record]',maskAllInputs:!1,maskInputOptions:{password:!0,email:!0,tel:!0},maskTextSelector:"[data-hs-mask]",sampling:{mousemove:100,scroll:150,input:"last"}});e?(this.stopFn=e,this._recording=!0,this._paused=!1,console.log("[RRWebRecorder] Started recording")):console.warn("[RRWebRecorder] record() returned undefined — recording may have failed")}stop(){var e;this._recording&&((e=this.stopFn)==null||e.call(this),this.stopFn=null,this._recording=!1,this._paused=!1,console.log("[RRWebRecorder] Stopped recording"))}pause(){!this._recording||this._paused||(this._paused=!0,console.log("[RRWebRecorder] Paused"))}resume(){!this._recording||!this._paused||(this._paused=!1,Ws.takeFullSnapshot(),console.log("[RRWebRecorder] Resumed (full snapshot taken)"))}}function n0(i){return i.startsWith("ws://")||i.startsWith("wss://")?i:`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}${i.startsWith("/")?"":"/"}${i}`}const Ed=1e3,o0=3e4,a0=500;class Sd{constructor(e,t){this.onIntervention=null,this.onStatus=null,this.onConnected=null,this.onDisconnected=null,this.ws=null,this.eventBuffer=[],this.reconnectDelay=Ed,this.reconnectTimer=null,this._connected=!1,this._closed=!1,this.url=n0(e),this.initPayload={type:"init",...t}}get isConnected(){return this._connected}connect(){this._closed||this.doConnect()}close(){if(this._closed=!0,this.clearReconnectTimer(),this.ws){try{this.ws.close()}catch{}this.ws=null}this._connected=!1}sendRRWebEvent(e){this.send({type:"rrweb",event:e})}sendActionComplete(e,t){this.send({type:"action_complete",actionId:e,result:t})}sendConversationStarted(){this.send({type:"conversation_started"})}sendConversationEnded(e){this.send({type:"conversation_ended",summary:e})}sendPageChanged(e,t,s){this.send({type:"page_changed",url:e,pathname:t,title:s})}doConnect(){if(!this._closed){try{this.ws=new WebSocket(this.url)}catch(e){console.warn("[VisionWS] Failed to create WebSocket:",e),this.scheduleReconnect();return}this.ws.onopen=()=>{var e;console.log("[VisionWS] Connected"),this._connected=!0,this.reconnectDelay=Ed,this.ws.send(JSON.stringify(this.initPayload)),this.flushBuffer(),(e=this.onConnected)==null||e.call(this)},this.ws.onmessage=e=>{const t=e.data;typeof t=="string"?this.parseAndHandle(t):t instanceof Blob?t.text().then(s=>this.parseAndHandle(s)):t instanceof ArrayBuffer?this.parseAndHandle(new TextDecoder().decode(t)):console.warn("[VisionWS] Unknown message data type:",typeof t)},this.ws.onclose=()=>{var t;const e=this._connected;this._connected=!1,this.ws=null,e&&(console.log("[VisionWS] Disconnected"),(t=this.onDisconnected)==null||t.call(this)),this._closed||this.scheduleReconnect()},this.ws.onerror=e=>{console.warn("[VisionWS] Error:",e)}}}parseAndHandle(e){var t,s;try{const r=JSON.parse(e);switch(r.type){case"suggest_intervention":(t=this.onIntervention)==null||t.call(this,r);break;case"status":(s=this.onStatus)==null||s.call(this,r);break;default:console.log("[VisionWS] Unknown message type:",r.type)}}catch(r){console.warn("[VisionWS] Failed to parse message:",r)}}send(e){var t;this._connected&&((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN?this.ws.send(JSON.stringify(e)):(this.eventBuffer.length>=a0&&this.eventBuffer.shift(),this.eventBuffer.push(e))}flushBuffer(){if(!(!this._connected||!this.ws)){for(const e of this.eventBuffer)this.ws.send(JSON.stringify(e));this.eventBuffer.length>0&&console.log(`[VisionWS] Flushed ${this.eventBuffer.length} buffered messages`),this.eventBuffer=[]}}scheduleReconnect(){if(this._closed||this.reconnectTimer)return;const e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*2,o0),console.log(`[VisionWS] Reconnecting in ${e}ms...`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.doConnect()},e)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}}const l0={sm:"var(--hs-radius-sm)",md:"var(--hs-radius-md)",lg:"var(--hs-radius-lg)",pill:"var(--hs-radius-pill)"},c0={base:"var(--hs-glass-bg)",elevated:"var(--hs-glass-bg-elevated)",solid:"var(--hs-glass-bg-solid)"};function Yt(i={}){const{tag:e="div",radius:t="md",elevation:s="base",interactive:r=!1,className:n,role:o}=i,a=document.createElement(e);return n&&(a.className=n),o&&a.setAttribute("role",o),Object.assign(a.style,{background:c0[s],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)",borderRadius:l0[t],boxShadow:s==="elevated"?"var(--hs-glass-shadow-elevated)":"var(--hs-glass-shadow)",color:"var(--hs-text-primary)",fontFamily:"var(--hs-font)",fontSize:"var(--hs-text-base)",lineHeight:"var(--hs-line-height)",boxSizing:"border-box"}),r&&(a.style.transition=`border-color var(--hs-fade-duration) var(--hs-ease-fast),
|
|
960
|
-
box-shadow var(--hs-fade-duration) var(--hs-ease-fast)`,a.style.cursor="pointer",a.addEventListener("mouseenter",()=>{a.style.borderColor="var(--hs-glass-border-hover)"}),a.addEventListener("mouseleave",()=>{a.style.borderColor="var(--hs-glass-border)"})),a}function bt(i,e="primary",t="base",s="normal"){const r={primary:"var(--hs-text-primary)",secondary:"var(--hs-text-secondary)",tertiary:"var(--hs-text-tertiary)"},n={xs:"var(--hs-text-xs)",sm:"var(--hs-text-sm)",base:"var(--hs-text-base)",lg:"var(--hs-text-lg)",xl:"var(--hs-text-xl)"},o={normal:"var(--hs-weight-normal)",medium:"var(--hs-weight-medium)",semibold:"var(--hs-weight-semibold)"};return Object.assign(i.style,{color:r[e],fontSize:n[t],fontWeight:o[s],fontFamily:"var(--hs-font)",lineHeight:"var(--hs-line-height)",margin:"0"}),i}function vt(i){const{label:e,variant:t="default",size:s="md",icon:r,onClick:n}=i,o=document.createElement("button");o.textContent=r?`${r} ${e}`:e;const a=s==="sm"?"4px 10px":"8px 16px",l=s==="sm"?"var(--hs-text-sm)":"var(--hs-text-base)";switch(Object.assign(o.style,{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"var(--hs-space-1)",padding:a,fontSize:l,fontWeight:"var(--hs-weight-medium)",fontFamily:"var(--hs-font)",lineHeight:"1",border:"none",borderRadius:"var(--hs-radius-pill)",cursor:"pointer",transition:"all var(--hs-fade-duration) var(--hs-ease-fast)",outline:"none",whiteSpace:"nowrap"}),t){case"accent":Object.assign(o.style,{background:"var(--hs-accent)",color:"var(--hs-accent-text)",boxShadow:"0 2px 12px var(--hs-accent-glow)"}),o.addEventListener("mouseenter",()=>{o.style.filter="brightness(1.12)",o.style.transform="scale(1.03)"}),o.addEventListener("mouseleave",()=>{o.style.filter="",o.style.transform=""});break;case"ghost":Object.assign(o.style,{background:"transparent",color:"var(--hs-text-secondary)"}),o.addEventListener("mouseenter",()=>{o.style.background="var(--hs-glass-bg)",o.style.color="var(--hs-text-primary)"}),o.addEventListener("mouseleave",()=>{o.style.background="transparent",o.style.color="var(--hs-text-secondary)"});break;default:Object.assign(o.style,{background:"var(--hs-glass-bg-elevated)",color:"var(--hs-text-primary)",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)"}),o.addEventListener("mouseenter",()=>{o.style.borderColor="var(--hs-glass-border-hover)",o.style.transform="scale(1.03)"}),o.addEventListener("mouseleave",()=>{o.style.borderColor="var(--hs-glass-border)",o.style.transform=""});break}return n&&o.addEventListener("click",c=>{c.stopPropagation(),n(c)}),o}function Td(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t}var Ad=function(){};const Fo=(i,e,t)=>Math.min(Math.max(t,i),e),Lo=.001,h0=.01,u0=10,d0=.05,f0=1;function p0({duration:i=800,bounce:e=.25,velocity:t=0,mass:s=1}){let r,n,o=1-e;o=Fo(d0,f0,o),i=Fo(h0,u0,i/1e3),o<1?(r=c=>{const h=c*o,u=h*i,p=h-t,d=Wo(c,o),g=Math.exp(-u);return Lo-p/d*g},n=c=>{const u=c*o*i,p=u*t+t,d=Math.pow(o,2)*Math.pow(c,2)*i,g=Math.exp(-u),_=Wo(Math.pow(c,2),o);return(-r(c)+Lo>0?-1:1)*((p-d)*g)/_}):(r=c=>{const h=Math.exp(-c*i),u=(c-t)*i+1;return-Lo+h*u},n=c=>{const h=Math.exp(-c*i),u=(t-c)*(i*i);return h*u});const a=5/i,l=g0(r,n,a);if(i=i*1e3,isNaN(l))return{stiffness:100,damping:10,duration:i};{const c=Math.pow(l,2)*s;return{stiffness:c,damping:o*2*Math.sqrt(s*c),duration:i}}}const m0=12;function g0(i,e,t){let s=t;for(let r=1;r<m0;r++)s=s-i(s)/e(s);return s}function Wo(i,e){return i*Math.sqrt(1-e*e)}const _0=["duration","bounce"],y0=["stiffness","damping","mass"];function wd(i,e){return e.some(t=>i[t]!==void 0)}function b0(i){let e=Object.assign({velocity:0,stiffness:100,damping:10,mass:1,isResolvedFromDuration:!1},i);if(!wd(i,y0)&&wd(i,_0)){const t=p0(i);e=Object.assign(Object.assign(Object.assign({},e),t),{velocity:0,mass:1}),e.isResolvedFromDuration=!0}return e}function Ho(i){var{from:e=0,to:t=1,restSpeed:s=2,restDelta:r}=i,n=Td(i,["from","to","restSpeed","restDelta"]);const o={done:!1,value:e};let{stiffness:a,damping:l,mass:c,velocity:h,duration:u,isResolvedFromDuration:p}=b0(n),d=Id,g=Id;function _(){const b=h?-(h/1e3):0,v=t-e,C=l/(2*Math.sqrt(a*c)),E=Math.sqrt(a/c)/1e3;if(r===void 0&&(r=Math.min(Math.abs(t-e)/100,.4)),C<1){const S=Wo(E,C);d=w=>{const R=Math.exp(-C*E*w);return t-R*((b+C*E*v)/S*Math.sin(S*w)+v*Math.cos(S*w))},g=w=>{const R=Math.exp(-C*E*w);return C*E*R*(Math.sin(S*w)*(b+C*E*v)/S+v*Math.cos(S*w))-R*(Math.cos(S*w)*(b+C*E*v)-S*v*Math.sin(S*w))}}else if(C===1)d=S=>t-Math.exp(-E*S)*(v+(b+E*v)*S);else{const S=E*Math.sqrt(C*C-1);d=w=>{const R=Math.exp(-C*E*w),M=Math.min(S*w,300);return t-R*((b+C*E*v)*Math.sinh(M)+S*v*Math.cosh(M))/S}}}return _(),{next:b=>{const v=d(b);if(p)o.done=b>=u;else{const C=g(b)*1e3,E=Math.abs(C)<=s,S=Math.abs(t-v)<=r;o.done=E&&S}return o.value=o.done?t:v,o},flipTarget:()=>{h=-h,[e,t]=[t,e],_()}}}Ho.needsInterpolation=(i,e)=>typeof i=="string"||typeof e=="string";const Id=i=>0,Rd=(i,e,t)=>{const s=e-i;return s===0?1:(t-i)/s},Vo=(i,e,t)=>-t*i+t*e+i,Md=(i,e)=>t=>Math.max(Math.min(t,e),i),wi=i=>i%1?Number(i.toFixed(5)):i,Sr=/(-)?([\d]*\.?[\d])+/g,zo=/(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))/gi,v0=/^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))$/i;function Ii(i){return typeof i=="string"}const Tr={test:i=>typeof i=="number",parse:parseFloat,transform:i=>i},Pd=Object.assign(Object.assign({},Tr),{transform:Md(0,1)});Object.assign(Object.assign({},Tr),{default:1});const Ri=(i=>({test:e=>Ii(e)&&e.endsWith(i)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${i}`}))("%");Object.assign(Object.assign({},Ri),{parse:i=>Ri.parse(i)/100,transform:i=>Ri.transform(i*100)});const $o=(i,e)=>t=>!!(Ii(t)&&v0.test(t)&&t.startsWith(i)||e&&Object.prototype.hasOwnProperty.call(t,e)),kd=(i,e,t)=>s=>{if(!Ii(s))return s;const[r,n,o,a]=s.match(Sr);return{[i]:parseFloat(r),[e]:parseFloat(n),[t]:parseFloat(o),alpha:a!==void 0?parseFloat(a):1}},cs={test:$o("hsl","hue"),parse:kd("hue","saturation","lightness"),transform:({hue:i,saturation:e,lightness:t,alpha:s=1})=>"hsla("+Math.round(i)+", "+Ri.transform(wi(e))+", "+Ri.transform(wi(t))+", "+wi(Pd.transform(s))+")"},x0=Md(0,255),jo=Object.assign(Object.assign({},Tr),{transform:i=>Math.round(x0(i))}),qt={test:$o("rgb","red"),parse:kd("red","green","blue"),transform:({red:i,green:e,blue:t,alpha:s=1})=>"rgba("+jo.transform(i)+", "+jo.transform(e)+", "+jo.transform(t)+", "+wi(Pd.transform(s))+")"};function C0(i){let e="",t="",s="",r="";return i.length>5?(e=i.substr(1,2),t=i.substr(3,2),s=i.substr(5,2),r=i.substr(7,2)):(e=i.substr(1,1),t=i.substr(2,1),s=i.substr(3,1),r=i.substr(4,1),e+=e,t+=t,s+=s,r+=r),{red:parseInt(e,16),green:parseInt(t,16),blue:parseInt(s,16),alpha:r?parseInt(r,16)/255:1}}const Xo={test:$o("#"),parse:C0,transform:qt.transform},Ar={test:i=>qt.test(i)||Xo.test(i)||cs.test(i),parse:i=>qt.test(i)?qt.parse(i):cs.test(i)?cs.parse(i):Xo.parse(i),transform:i=>Ii(i)?i:i.hasOwnProperty("red")?qt.transform(i):cs.transform(i)},Od="${c}",Bd="${n}";function E0(i){var e,t,s,r;return isNaN(i)&&Ii(i)&&((t=(e=i.match(Sr))===null||e===void 0?void 0:e.length)!==null&&t!==void 0?t:0)+((r=(s=i.match(zo))===null||s===void 0?void 0:s.length)!==null&&r!==void 0?r:0)>0}function Dd(i){typeof i=="number"&&(i=`${i}`);const e=[];let t=0;const s=i.match(zo);s&&(t=s.length,i=i.replace(zo,Od),e.push(...s.map(Ar.parse)));const r=i.match(Sr);return r&&(i=i.replace(Sr,Bd),e.push(...r.map(Tr.parse))),{values:e,numColors:t,tokenised:i}}function Nd(i){return Dd(i).values}function Ud(i){const{values:e,numColors:t,tokenised:s}=Dd(i),r=e.length;return n=>{let o=s;for(let a=0;a<r;a++)o=o.replace(a<t?Od:Bd,a<t?Ar.transform(n[a]):wi(n[a]));return o}}const S0=i=>typeof i=="number"?0:i;function T0(i){const e=Nd(i);return Ud(i)(e.map(S0))}const Gd={test:E0,parse:Nd,createTransformer:Ud,getAnimatableNone:T0};function Yo(i,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?i+(e-i)*6*t:t<1/2?e:t<2/3?i+(e-i)*(2/3-t)*6:i}function Fd({hue:i,saturation:e,lightness:t,alpha:s}){i/=360,e/=100,t/=100;let r=0,n=0,o=0;if(!e)r=n=o=t;else{const a=t<.5?t*(1+e):t+e-t*e,l=2*t-a;r=Yo(l,a,i+1/3),n=Yo(l,a,i),o=Yo(l,a,i-1/3)}return{red:Math.round(r*255),green:Math.round(n*255),blue:Math.round(o*255),alpha:s}}const A0=(i,e,t)=>{const s=i*i,r=e*e;return Math.sqrt(Math.max(0,t*(r-s)+s))},w0=[Xo,qt,cs],Ld=i=>w0.find(e=>e.test(i)),Wd=(i,e)=>{let t=Ld(i),s=Ld(e),r=t.parse(i),n=s.parse(e);t===cs&&(r=Fd(r),t=qt),s===cs&&(n=Fd(n),s=qt);const o=Object.assign({},r);return a=>{for(const l in o)l!=="alpha"&&(o[l]=A0(r[l],n[l],a));return o.alpha=Vo(r.alpha,n.alpha,a),t.transform(o)}},I0=i=>typeof i=="number",R0=(i,e)=>t=>e(i(t)),Hd=(...i)=>i.reduce(R0);function Vd(i,e){return I0(i)?t=>Vo(i,e,t):Ar.test(i)?Wd(i,e):jd(i,e)}const zd=(i,e)=>{const t=[...i],s=t.length,r=i.map((n,o)=>Vd(n,e[o]));return n=>{for(let o=0;o<s;o++)t[o]=r[o](n);return t}},M0=(i,e)=>{const t=Object.assign(Object.assign({},i),e),s={};for(const r in t)i[r]!==void 0&&e[r]!==void 0&&(s[r]=Vd(i[r],e[r]));return r=>{for(const n in s)t[n]=s[n](r);return t}};function $d(i){const e=Gd.parse(i),t=e.length;let s=0,r=0,n=0;for(let o=0;o<t;o++)s||typeof e[o]=="number"?s++:e[o].hue!==void 0?n++:r++;return{parsed:e,numNumbers:s,numRGB:r,numHSL:n}}const jd=(i,e)=>{const t=Gd.createTransformer(e),s=$d(i),r=$d(e);return s.numHSL===r.numHSL&&s.numRGB===r.numRGB&&s.numNumbers>=r.numNumbers?Hd(zd(s.parsed,r.parsed),t):o=>`${o>0?e:i}`},P0=(i,e)=>t=>Vo(i,e,t);function k0(i){if(typeof i=="number")return P0;if(typeof i=="string")return Ar.test(i)?Wd:jd;if(Array.isArray(i))return zd;if(typeof i=="object")return M0}function O0(i,e,t){const s=[],r=t||k0(i[0]),n=i.length-1;for(let o=0;o<n;o++){let a=r(i[o],i[o+1]);if(e){const l=Array.isArray(e)?e[o]:e;a=Hd(l,a)}s.push(a)}return s}function B0([i,e],[t]){return s=>t(Rd(i,e,s))}function D0(i,e){const t=i.length,s=t-1;return r=>{let n=0,o=!1;if(r<=i[0]?o=!0:r>=i[s]&&(n=s-1,o=!0),!o){let l=1;for(;l<t&&!(i[l]>r||l===s);l++);n=l-1}const a=Rd(i[n],i[n+1],r);return e[n](a)}}function Xd(i,e,{clamp:t=!0,ease:s,mixer:r}={}){const n=i.length;Ad(n===e.length),Ad(!s||!Array.isArray(s)||s.length===n-1),i[0]>i[n-1]&&(i=[].concat(i),e=[].concat(e),i.reverse(),e.reverse());const o=O0(e,s,r),a=n===2?B0(i,o):D0(i,o);return t?l=>a(Fo(i[0],i[n-1],l)):a}const N0=i=>e=>e<=.5?i(2*e)/2:(2-i(2*(1-e)))/2,U0=(i=>e=>Math.pow(e,i))(2),G0=N0(U0);function F0(i,e){return i.map(()=>e||G0).splice(0,i.length-1)}function L0(i){const e=i.length;return i.map((t,s)=>s!==0?s/(e-1):0)}function W0(i,e){return i.map(t=>t*e)}function wr({from:i=0,to:e=1,ease:t,offset:s,duration:r=300}){const n={done:!1,value:i},o=Array.isArray(e)?e:[i,e],a=W0(s&&s.length===o.length?s:L0(o),r);function l(){return Xd(a,o,{ease:Array.isArray(t)?t:F0(o,t)})}let c=l();return{next:h=>(n.value=c(h),n.done=h>=r,n),flipTarget:()=>{o.reverse(),c=l()}}}function H0({velocity:i=0,from:e=0,power:t=.8,timeConstant:s=350,restDelta:r=.5,modifyTarget:n}){const o={done:!1,value:e};let a=t*i;const l=e+a,c=n===void 0?l:n(l);return c!==l&&(a=c-e),{next:h=>{const u=-a*Math.exp(-h/s);return o.done=!(u>r||u<-r),o.value=o.done?c:c+u,o},flipTarget:()=>{}}}const Yd={keyframes:wr,spring:Ho,decay:H0};function V0(i){if(Array.isArray(i.to))return wr;if(Yd[i.type])return Yd[i.type];const e=new Set(Object.keys(i));return e.has("ease")||e.has("duration")&&!e.has("dampingRatio")?wr:e.has("dampingRatio")||e.has("stiffness")||e.has("mass")||e.has("damping")||e.has("restSpeed")||e.has("restDelta")?Ho:wr}const qd=1/60*1e3,z0=typeof performance<"u"?()=>performance.now():()=>Date.now(),Kd=typeof window<"u"?i=>window.requestAnimationFrame(i):i=>setTimeout(()=>i(z0()),qd);function $0(i){let e=[],t=[],s=0,r=!1,n=!1;const o=new WeakSet,a={schedule:(l,c=!1,h=!1)=>{const u=h&&r,p=u?e:t;return c&&o.add(l),p.indexOf(l)===-1&&(p.push(l),u&&r&&(s=e.length)),l},cancel:l=>{const c=t.indexOf(l);c!==-1&&t.splice(c,1),o.delete(l)},process:l=>{if(r){n=!0;return}if(r=!0,[e,t]=[t,e],t.length=0,s=e.length,s)for(let c=0;c<s;c++){const h=e[c];h(l),o.has(h)&&(a.schedule(h),i())}r=!1,n&&(n=!1,a.process(l))}};return a}const j0=40;let qo=!0,Mi=!1,Ko=!1;const Pi={delta:0,timestamp:0},ki=["read","update","preRender","render","postRender"],Ir=ki.reduce((i,e)=>(i[e]=$0(()=>Mi=!0),i),{}),X0=ki.reduce((i,e)=>{const t=Ir[e];return i[e]=(s,r=!1,n=!1)=>(Mi||K0(),t.schedule(s,r,n)),i},{}),Y0=ki.reduce((i,e)=>(i[e]=Ir[e].cancel,i),{});ki.reduce((i,e)=>(i[e]=()=>Ir[e].process(Pi),i),{});const q0=i=>Ir[i].process(Pi),Zd=i=>{Mi=!1,Pi.delta=qo?qd:Math.max(Math.min(i-Pi.timestamp,j0),1),Pi.timestamp=i,Ko=!0,ki.forEach(q0),Ko=!1,Mi&&(qo=!1,Kd(Zd))},K0=()=>{Mi=!0,qo=!0,Ko||Kd(Zd)};function Jd(i,e,t=0){return i-e-t}function Z0(i,e,t=0,s=!0){return s?Jd(e+-i,e,t):e-(i-e)+t}function J0(i,e,t,s){return s?i>=e+t:i<=-t}const Q0=i=>{const e=({delta:t})=>i(t);return{start:()=>X0.update(e,!0),stop:()=>Y0.update(e)}};function eC(i){var e,t,{from:s,autoplay:r=!0,driver:n=Q0,elapsed:o=0,repeat:a=0,repeatType:l="loop",repeatDelay:c=0,onPlay:h,onStop:u,onComplete:p,onRepeat:d,onUpdate:g}=i,_=Td(i,["from","autoplay","driver","elapsed","repeat","repeatType","repeatDelay","onPlay","onStop","onComplete","onRepeat","onUpdate"]);let{to:b}=_,v,C=0,E=_.duration,S,w=!1,R=!0,M;const D=V0(_);!((t=(e=D).needsInterpolation)===null||t===void 0)&&t.call(e,s,b)&&(M=Xd([0,100],[s,b],{clamp:!1}),s=0,b=100);const G=D(Object.assign(Object.assign({},_),{from:s,to:b}));function k(){C++,l==="reverse"?(R=C%2===0,o=Z0(o,E,c,R)):(o=Jd(o,E,c),l==="mirror"&&G.flipTarget()),w=!1,d&&d()}function O(){v.stop(),p&&p()}function V(z){if(R||(z=-z),o+=z,!w){const de=G.next(Math.max(0,o));S=de.value,M&&(S=M(S)),w=R?de.done:o<=0}g==null||g(S),w&&(C===0&&(E??(E=o)),C<a?J0(o,E,c,R)&&k():O())}function X(){h==null||h(),v=n(V),v.start()}return r&&X(),{stop:()=>{u==null||u(),v.stop()}}}const tC={snappy:{stiffness:300,damping:28,mass:.8},gentle:{stiffness:170,damping:26,mass:1},bouncy:{stiffness:400,damping:20,mass:.6},smooth:{stiffness:200,damping:30,mass:1}};function Kt(i){const e=i.preset?tC[i.preset]:void 0,t=eC({from:i.from,to:i.to,type:"spring",stiffness:i.stiffness??(e==null?void 0:e.stiffness)??170,damping:i.damping??(e==null?void 0:e.damping)??26,mass:i.mass??(e==null?void 0:e.mass)??1,onUpdate:i.onUpdate,onComplete:i.onComplete});return{stop:()=>t.stop()}}function sC(i,e,t,s="smooth",r){return Kt({from:e,to:t,preset:s,onUpdate:n=>{i.style.opacity=String(n)},onComplete:r})}function rt(i,e={}){const{from:t={},preset:s="snappy",onComplete:r}=e,n=t.opacity??0,o=t.scale??.92,a=t.y??8;i.style.opacity=String(n),i.style.transform=`scale(${o}) translateY(${a}px)`;const l=[];let c=0;const h=3,u=()=>{++c>=h&&(r==null||r())};return l.push(Kt({from:n,to:1,preset:s,onUpdate:p=>{i.style.opacity=String(p)},onComplete:u})),l.push(Kt({from:o,to:1,preset:s,onUpdate:p=>{var g;const d=parseFloat(((g=i.style.transform.match(/translateY\(([^)]+)\)/))==null?void 0:g[1])??"0");i.style.transform=`scale(${p}) translateY(${d}px)`},onComplete:u})),l.push(Kt({from:a,to:0,preset:s,onUpdate:p=>{var g;const d=parseFloat(((g=i.style.transform.match(/scale\(([^)]+)\)/))==null?void 0:g[1])??"1");i.style.transform=`scale(${d}) translateY(${p}px)`},onComplete:u})),{stop:()=>l.forEach(p=>p.stop())}}function Ot(i,e={}){const{to:t={},preset:s="smooth",remove:r=!0,onComplete:n}=e,o=t.opacity??0,a=t.scale??.92,l=t.y??8,c=[];let h=0;const u=3,p=()=>{++h>=u&&(r&&i.remove(),n==null||n())};return c.push(Kt({from:parseFloat(i.style.opacity||"1"),to:o,preset:s,onUpdate:d=>{i.style.opacity=String(d)},onComplete:p})),c.push(Kt({from:1,to:a,preset:s,onUpdate:d=>{var _;const g=parseFloat(((_=i.style.transform.match(/translateY\(([^)]+)\)/))==null?void 0:_[1])??"0");i.style.transform=`scale(${d}) translateY(${g}px)`},onComplete:p})),c.push(Kt({from:0,to:l,preset:s,onUpdate:d=>{var _;const g=parseFloat(((_=i.style.transform.match(/scale\(([^)]+)\)/))==null?void 0:_[1])??"1");i.style.transform=`scale(${g}) translateY(${d}px)`},onComplete:p})),{stop:()=>c.forEach(d=>d.stop())}}const Qd="holostaff-liquid-tokens",W={glassBlur:"20px",glassSaturate:"180%",dark:{glassBg:"rgba(255, 255, 255, 0.10)",glassBgElevated:"rgba(255, 255, 255, 0.16)",glassBgSolid:"rgba(30, 30, 40, 0.85)",glassBorder:"rgba(255, 255, 255, 0.14)",glassBorderHover:"rgba(255, 255, 255, 0.28)",glassShadow:"0 8px 32px rgba(0, 0, 0, 0.24)",glassShadowElevated:"0 12px 48px rgba(0, 0, 0, 0.32)",textPrimary:"rgba(255, 255, 255, 0.92)",textSecondary:"rgba(255, 255, 255, 0.56)",textTertiary:"rgba(255, 255, 255, 0.32)",divider:"rgba(255, 255, 255, 0.08)"},light:{glassBg:"rgba(255, 255, 255, 0.55)",glassBgElevated:"rgba(255, 255, 255, 0.72)",glassBgSolid:"rgba(255, 255, 255, 0.92)",glassBorder:"rgba(0, 0, 0, 0.06)",glassBorderHover:"rgba(0, 0, 0, 0.12)",glassShadow:"0 8px 32px rgba(0, 0, 0, 0.08)",glassShadowElevated:"0 12px 48px rgba(0, 0, 0, 0.12)",textPrimary:"rgba(0, 0, 0, 0.85)",textSecondary:"rgba(0, 0, 0, 0.50)",textTertiary:"rgba(0, 0, 0, 0.28)",divider:"rgba(0, 0, 0, 0.06)"},radiusSm:"10px",radiusMd:"16px",radiusLg:"24px",radiusPill:"9999px",font:"-apple-system, 'Inter', 'Segoe UI', system-ui, sans-serif",textXs:"11px",textSm:"12px",textBase:"14px",textLg:"16px",textXl:"20px",weightNormal:"400",weightMedium:"500",weightSemibold:"600",lineHeight:"1.45",springDuration:"500ms",springEasing:"cubic-bezier(0.34, 1.56, 0.64, 1)",easeFast:"cubic-bezier(0.25, 0.1, 0.25, 1)",fadeDuration:"200ms",accent:"#7C5CFF",accentGlow:"rgba(124, 92, 255, 0.35)",accentText:"#ffffff",space1:"4px",space2:"8px",space3:"12px",space4:"16px",space5:"20px",space6:"24px",space8:"32px",zOverlay:"2147483644",zControls:"2147483646",zTop:"2147483647"};function xt(){if(document.getElementById(Qd))return;const i=document.createElement("style");i.id=Qd,i.textContent=`
|
|
957
|
+
***************************************************************************** */function Nx(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t}function Ux(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,[])).next())})}for(var Ls="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Gx=typeof Uint8Array>"u"?[]:new Uint8Array(256),vr=0;vr<Ls.length;vr++)Gx[Ls.charCodeAt(vr)]=vr;var Fx=function(i){var e=new Uint8Array(i),t,s=e.length,r="";for(t=0;t<s;t+=3)r+=Ls[e[t]>>2],r+=Ls[(e[t]&3)<<4|e[t+1]>>4],r+=Ls[(e[t+1]&15)<<2|e[t+2]>>6],r+=Ls[e[t+2]&63];return s%3===2?r=r.substring(0,r.length-1)+"=":s%3===1&&(r=r.substring(0,r.length-2)+"=="),r};const md=new Map;function Lx(i,e){let t=md.get(i);return t||(t=new Map,md.set(i,t)),t.has(e)||t.set(e,[]),t.get(e)}const gd=(i,e,t)=>{if(!i||!(yd(i,e)||typeof i=="object"))return;const s=i.constructor.name,r=Lx(t,s);let n=r.indexOf(i);return n===-1&&(n=r.length,r.push(i)),n};function xr(i,e,t){if(i instanceof Array)return i.map(s=>xr(s,e,t));if(i===null)return i;if(i instanceof Float32Array||i instanceof Float64Array||i instanceof Int32Array||i instanceof Uint32Array||i instanceof Uint8Array||i instanceof Uint16Array||i instanceof Int16Array||i instanceof Int8Array||i instanceof Uint8ClampedArray)return{rr_type:i.constructor.name,args:[Object.values(i)]};if(i instanceof ArrayBuffer){const s=i.constructor.name,r=Fx(i);return{rr_type:s,base64:r}}else{if(i instanceof DataView)return{rr_type:i.constructor.name,args:[xr(i.buffer,e,t),i.byteOffset,i.byteLength]};if(i instanceof HTMLImageElement){const s=i.constructor.name,{src:r}=i;return{rr_type:s,src:r}}else if(i instanceof HTMLCanvasElement){const s="HTMLImageElement",r=i.toDataURL();return{rr_type:s,src:r}}else{if(i instanceof ImageData)return{rr_type:i.constructor.name,args:[xr(i.data,e,t),i.width,i.height]};if(yd(i,e)||typeof i=="object"){const s=i.constructor.name,r=gd(i,e,t);return{rr_type:s,index:r}}}}return i}const _d=(i,e,t)=>[...i].map(s=>xr(s,e,t)),yd=(i,e)=>!!["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter(r=>typeof e[r]=="function").find(r=>i instanceof e[r]);function Wx(i,e,t,s){const r=[],n=Object.getOwnPropertyNames(e.CanvasRenderingContext2D.prototype);for(const o of n)try{if(typeof e.CanvasRenderingContext2D.prototype[o]!="function")continue;const a=Gs(e.CanvasRenderingContext2D.prototype,o,function(l){return function(...c){return Je(this.canvas,t,s,!0)||setTimeout(()=>{const h=_d([...c],e,this);i(this.canvas,{type:Fs["2D"],property:o,args:h})},0),l.apply(this,c)}});r.push(a)}catch{const l=yr(e.CanvasRenderingContext2D.prototype,o,{set(c){i(this.canvas,{type:Fs["2D"],property:o,args:[c],setter:!0})}});r.push(l)}return()=>{r.forEach(o=>o())}}function bd(i,e,t){const s=[];try{const r=Gs(i.HTMLCanvasElement.prototype,"getContext",function(n){return function(o,...a){return Je(this,e,t,!0)||"__context"in this||(this.__context=o),n.apply(this,[o,...a])}});s.push(r)}catch{console.error("failed to patch HTMLCanvasElement.prototype.getContext")}return()=>{s.forEach(r=>r())}}function vd(i,e,t,s,r,n,o){const a=[],l=Object.getOwnPropertyNames(i);for(const c of l)if(!["isContextLost","canvas","drawingBufferWidth","drawingBufferHeight"].includes(c))try{if(typeof i[c]!="function")continue;const h=Gs(i,c,function(u){return function(...p){const d=u.apply(this,p);if(gd(d,o,this),!Je(this.canvas,s,r,!0)){const g=_d([...p],o,this),_={type:e,property:c,args:g};t(this.canvas,_)}return d}});a.push(h)}catch{const u=yr(i,c,{set(p){t(this.canvas,{type:e,property:c,args:[p],setter:!0})}});a.push(u)}return a}function Hx(i,e,t,s,r){const n=[];return n.push(...vd(e.WebGLRenderingContext.prototype,Fs.WebGL,i,t,s,r,e)),typeof e.WebGL2RenderingContext<"u"&&n.push(...vd(e.WebGL2RenderingContext.prototype,Fs.WebGL2,i,t,s,r,e)),()=>{n.forEach(o=>o())}}var xd=null;try{var Vx=typeof module<"u"&&typeof module.require=="function"&&module.require("worker_threads")||typeof __non_webpack_require__=="function"&&__non_webpack_require__("worker_threads")||typeof require=="function"&&require("worker_threads");xd=Vx.Worker}catch{}function zx(i,e){return Buffer.from(i,"base64").toString("utf8")}function $x(i,e,t){var s=zx(i),r=s.indexOf(`
|
|
958
|
+
`,10)+1,n=s.substring(r)+"";return function(a){return new xd(n,Object.assign({},a,{eval:!0}))}}function jx(i,e){var t=atob(i);return t}function Xx(i,e,t){var s=jx(i),r=s.indexOf(`
|
|
959
|
+
`,10)+1,n=s.substring(r)+"",o=new Blob([n],{type:"application/javascript"});return URL.createObjectURL(o)}function Yx(i,e,t){var s;return function(n){return s=s||Xx(i),new Worker(s,n)}}var qx=Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]";function Kx(){return qx}function Zx(i,e,t){return Kx()?$x(i):Yx(i)}var Jx=Zx("Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewogICAgJ3VzZSBzdHJpY3QnOwoKICAgIC8qISAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKg0KICAgIENvcHlyaWdodCAoYykgTWljcm9zb2Z0IENvcnBvcmF0aW9uLg0KDQogICAgUGVybWlzc2lvbiB0byB1c2UsIGNvcHksIG1vZGlmeSwgYW5kL29yIGRpc3RyaWJ1dGUgdGhpcyBzb2Z0d2FyZSBmb3IgYW55DQogICAgcHVycG9zZSB3aXRoIG9yIHdpdGhvdXQgZmVlIGlzIGhlcmVieSBncmFudGVkLg0KDQogICAgVEhFIFNPRlRXQVJFIElTIFBST1ZJREVEICJBUyBJUyIgQU5EIFRIRSBBVVRIT1IgRElTQ0xBSU1TIEFMTCBXQVJSQU5USUVTIFdJVEgNCiAgICBSRUdBUkQgVE8gVEhJUyBTT0ZUV0FSRSBJTkNMVURJTkcgQUxMIElNUExJRUQgV0FSUkFOVElFUyBPRiBNRVJDSEFOVEFCSUxJVFkNCiAgICBBTkQgRklUTkVTUy4gSU4gTk8gRVZFTlQgU0hBTEwgVEhFIEFVVEhPUiBCRSBMSUFCTEUgRk9SIEFOWSBTUEVDSUFMLCBESVJFQ1QsDQogICAgSU5ESVJFQ1QsIE9SIENPTlNFUVVFTlRJQUwgREFNQUdFUyBPUiBBTlkgREFNQUdFUyBXSEFUU09FVkVSIFJFU1VMVElORyBGUk9NDQogICAgTE9TUyBPRiBVU0UsIERBVEEgT1IgUFJPRklUUywgV0hFVEhFUiBJTiBBTiBBQ1RJT04gT0YgQ09OVFJBQ1QsIE5FR0xJR0VOQ0UgT1INCiAgICBPVEhFUiBUT1JUSU9VUyBBQ1RJT04sIEFSSVNJTkcgT1VUIE9GIE9SIElOIENPTk5FQ1RJT04gV0lUSCBUSEUgVVNFIE9SDQogICAgUEVSRk9STUFOQ0UgT0YgVEhJUyBTT0ZUV0FSRS4NCiAgICAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKiAqLw0KDQogICAgZnVuY3Rpb24gX19hd2FpdGVyKHRoaXNBcmcsIF9hcmd1bWVudHMsIFAsIGdlbmVyYXRvcikgew0KICAgICAgICBmdW5jdGlvbiBhZG9wdCh2YWx1ZSkgeyByZXR1cm4gdmFsdWUgaW5zdGFuY2VvZiBQID8gdmFsdWUgOiBuZXcgUChmdW5jdGlvbiAocmVzb2x2ZSkgeyByZXNvbHZlKHZhbHVlKTsgfSk7IH0NCiAgICAgICAgcmV0dXJuIG5ldyAoUCB8fCAoUCA9IFByb21pc2UpKShmdW5jdGlvbiAocmVzb2x2ZSwgcmVqZWN0KSB7DQogICAgICAgICAgICBmdW5jdGlvbiBmdWxmaWxsZWQodmFsdWUpIHsgdHJ5IHsgc3RlcChnZW5lcmF0b3IubmV4dCh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiByZWplY3RlZCh2YWx1ZSkgeyB0cnkgeyBzdGVwKGdlbmVyYXRvclsidGhyb3ciXSh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiBzdGVwKHJlc3VsdCkgeyByZXN1bHQuZG9uZSA/IHJlc29sdmUocmVzdWx0LnZhbHVlKSA6IGFkb3B0KHJlc3VsdC52YWx1ZSkudGhlbihmdWxmaWxsZWQsIHJlamVjdGVkKTsgfQ0KICAgICAgICAgICAgc3RlcCgoZ2VuZXJhdG9yID0gZ2VuZXJhdG9yLmFwcGx5KHRoaXNBcmcsIF9hcmd1bWVudHMgfHwgW10pKS5uZXh0KCkpOw0KICAgICAgICB9KTsNCiAgICB9CgogICAgLyoKICAgICAqIGJhc2U2NC1hcnJheWJ1ZmZlciAxLjAuMSA8aHR0cHM6Ly9naXRodWIuY29tL25pa2xhc3ZoL2Jhc2U2NC1hcnJheWJ1ZmZlcj4KICAgICAqIENvcHlyaWdodCAoYykgMjAyMSBOaWtsYXMgdm9uIEhlcnR6ZW4gPGh0dHBzOi8vaGVydHplbi5jb20+CiAgICAgKiBSZWxlYXNlZCB1bmRlciBNSVQgTGljZW5zZQogICAgICovCiAgICB2YXIgY2hhcnMgPSAnQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyc7CiAgICAvLyBVc2UgYSBsb29rdXAgdGFibGUgdG8gZmluZCB0aGUgaW5kZXguCiAgICB2YXIgbG9va3VwID0gdHlwZW9mIFVpbnQ4QXJyYXkgPT09ICd1bmRlZmluZWQnID8gW10gOiBuZXcgVWludDhBcnJheSgyNTYpOwogICAgZm9yICh2YXIgaSA9IDA7IGkgPCBjaGFycy5sZW5ndGg7IGkrKykgewogICAgICAgIGxvb2t1cFtjaGFycy5jaGFyQ29kZUF0KGkpXSA9IGk7CiAgICB9CiAgICB2YXIgZW5jb2RlID0gZnVuY3Rpb24gKGFycmF5YnVmZmVyKSB7CiAgICAgICAgdmFyIGJ5dGVzID0gbmV3IFVpbnQ4QXJyYXkoYXJyYXlidWZmZXIpLCBpLCBsZW4gPSBieXRlcy5sZW5ndGgsIGJhc2U2NCA9ICcnOwogICAgICAgIGZvciAoaSA9IDA7IGkgPCBsZW47IGkgKz0gMykgewogICAgICAgICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaV0gPj4gMl07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1soKGJ5dGVzW2ldICYgMykgPDwgNCkgfCAoYnl0ZXNbaSArIDFdID4+IDQpXTsKICAgICAgICAgICAgYmFzZTY0ICs9IGNoYXJzWygoYnl0ZXNbaSArIDFdICYgMTUpIDw8IDIpIHwgKGJ5dGVzW2kgKyAyXSA+PiA2KV07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1tieXRlc1tpICsgMl0gJiA2M107CiAgICAgICAgfQogICAgICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgJz0nOwogICAgICAgIH0KICAgICAgICBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgJz09JzsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIGJhc2U2NDsKICAgIH07CgogICAgY29uc3QgbGFzdEJsb2JNYXAgPSBuZXcgTWFwKCk7DQogICAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gbmV3IE1hcCgpOw0KICAgIGZ1bmN0aW9uIGdldFRyYW5zcGFyZW50QmxvYkZvcih3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucykgew0KICAgICAgICByZXR1cm4gX19hd2FpdGVyKHRoaXMsIHZvaWQgMCwgdm9pZCAwLCBmdW5jdGlvbiogKCkgew0KICAgICAgICAgICAgY29uc3QgaWQgPSBgJHt3aWR0aH0tJHtoZWlnaHR9YDsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgaWYgKHRyYW5zcGFyZW50QmxvYk1hcC5oYXMoaWQpKQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gdHJhbnNwYXJlbnRCbG9iTWFwLmdldChpZCk7DQogICAgICAgICAgICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsNCiAgICAgICAgICAgICAgICBvZmZzY3JlZW4uZ2V0Q29udGV4dCgnMmQnKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0geWllbGQgYmxvYi5hcnJheUJ1ZmZlcigpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7DQogICAgICAgICAgICAgICAgdHJhbnNwYXJlbnRCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICByZXR1cm4gYmFzZTY0Ow0KICAgICAgICAgICAgfQ0KICAgICAgICAgICAgZWxzZSB7DQogICAgICAgICAgICAgICAgcmV0dXJuICcnOw0KICAgICAgICAgICAgfQ0KICAgICAgICB9KTsNCiAgICB9DQogICAgY29uc3Qgd29ya2VyID0gc2VsZjsNCiAgICB3b3JrZXIub25tZXNzYWdlID0gZnVuY3Rpb24gKGUpIHsNCiAgICAgICAgcmV0dXJuIF9fYXdhaXRlcih0aGlzLCB2b2lkIDAsIHZvaWQgMCwgZnVuY3Rpb24qICgpIHsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgY29uc3QgeyBpZCwgYml0bWFwLCB3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucyB9ID0gZS5kYXRhOw0KICAgICAgICAgICAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zKTsNCiAgICAgICAgICAgICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGN0eCA9IG9mZnNjcmVlbi5nZXRDb250ZXh0KCcyZCcpOw0KICAgICAgICAgICAgICAgIGN0eC5kcmF3SW1hZ2UoYml0bWFwLCAwLCAwKTsNCiAgICAgICAgICAgICAgICBiaXRtYXAuY2xvc2UoKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IHR5cGUgPSBibG9iLnR5cGU7DQogICAgICAgICAgICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSB5aWVsZCBibG9iLmFycmF5QnVmZmVyKCk7DQogICAgICAgICAgICAgICAgY29uc3QgYmFzZTY0ID0gZW5jb2RlKGFycmF5QnVmZmVyKTsNCiAgICAgICAgICAgICAgICBpZiAoIWxhc3RCbG9iTWFwLmhhcyhpZCkgJiYgKHlpZWxkIHRyYW5zcGFyZW50QmFzZTY0KSA9PT0gYmFzZTY0KSB7DQogICAgICAgICAgICAgICAgICAgIGxhc3RCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHdvcmtlci5wb3N0TWVzc2FnZSh7IGlkIH0pOw0KICAgICAgICAgICAgICAgIH0NCiAgICAgICAgICAgICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7DQogICAgICAgICAgICAgICAgd29ya2VyLnBvc3RNZXNzYWdlKHsNCiAgICAgICAgICAgICAgICAgICAgaWQsDQogICAgICAgICAgICAgICAgICAgIHR5cGUsDQogICAgICAgICAgICAgICAgICAgIGJhc2U2NCwNCiAgICAgICAgICAgICAgICAgICAgd2lkdGgsDQogICAgICAgICAgICAgICAgICAgIGhlaWdodCwNCiAgICAgICAgICAgICAgICB9KTsNCiAgICAgICAgICAgICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7DQogICAgICAgICAgICB9DQogICAgICAgICAgICBlbHNlIHsNCiAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsNCiAgICAgICAgICAgIH0NCiAgICAgICAgfSk7DQogICAgfTsKCn0pKCk7Cgo=");class Qx{constructor(e){this.pendingCanvasMutations=new Map,this.rafStamps={latestId:0,invokeId:null},this.frozen=!1,this.locked=!1,this.processMutation=(l,c)=>{(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId||!this.rafStamps.invokeId)&&(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(l)||this.pendingCanvasMutations.set(l,[]),this.pendingCanvasMutations.get(l).push(c)};const{sampling:t="all",win:s,blockClass:r,blockSelector:n,recordCanvas:o,dataURLOptions:a}=e;this.mutationCb=e.mutationCb,this.mirror=e.mirror,o&&t==="all"&&this.initCanvasMutationObserver(s,r,n),o&&typeof t=="number"&&this.initCanvasFPSObserver(t,s,r,n,{dataURLOptions:a})}reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}initCanvasFPSObserver(e,t,s,r,n){const o=bd(t,s,r),a=new Map,l=new Jx;l.onmessage=g=>{const{id:_}=g.data;if(a.set(_,!1),!("base64"in g.data))return;const{base64:b,type:v,width:C,height:E}=g.data;this.mutationCb({id:_,type:Fs["2D"],commands:[{property:"clearRect",args:[0,0,C,E]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:b}],type:v}]},0,0]}]})};const c=1e3/e;let h=0,u;const p=()=>{const g=[];return t.document.querySelectorAll("canvas").forEach(_=>{Je(_,s,r,!0)||g.push(_)}),g},d=g=>{if(h&&g-h<c){u=requestAnimationFrame(d);return}h=g,p().forEach(_=>Ux(this,void 0,void 0,function*(){var b;const v=this.mirror.getId(_);if(a.get(v))return;if(a.set(v,!0),["webgl","webgl2"].includes(_.__context)){const E=_.getContext(_.__context);((b=E==null?void 0:E.getContextAttributes())===null||b===void 0?void 0:b.preserveDrawingBuffer)===!1&&(E==null||E.clear(E.COLOR_BUFFER_BIT))}const C=yield createImageBitmap(_);l.postMessage({id:v,bitmap:C,width:_.width,height:_.height,dataURLOptions:n.dataURLOptions},[C])})),u=requestAnimationFrame(d)};u=requestAnimationFrame(d),this.resetObservers=()=>{o(),cancelAnimationFrame(u)}}initCanvasMutationObserver(e,t,s){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();const r=bd(e,t,s),n=Wx(this.processMutation.bind(this),e,t,s),o=Hx(this.processMutation.bind(this),e,t,s,this.mirror);this.resetObservers=()=>{r(),n(),o()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){const e=t=>{this.rafStamps.latestId=t,requestAnimationFrame(e)};requestAnimationFrame(e)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((e,t)=>{const s=this.mirror.getId(t);this.flushPendingCanvasMutationFor(t,s)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(e,t){if(this.frozen||this.locked)return;const s=this.pendingCanvasMutations.get(e);if(!s||t===-1)return;const r=s.map(o=>Nx(o,["type"])),{type:n}=s[0];this.mutationCb({id:t,type:n,commands:r}),this.pendingCanvasMutations.delete(e)}}class e0{constructor(e){this.trackedLinkElements=new WeakSet,this.styleMirror=new bx,this.mutationCb=e.mutationCb,this.adoptedStyleSheetCb=e.adoptedStyleSheetCb}attachLinkElement(e,t){"_cssText"in t.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:t.id,attributes:t.attributes}]}),this.trackLinkElement(e)}trackLinkElement(e){this.trackedLinkElements.has(e)||(this.trackedLinkElements.add(e),this.trackStylesheetInLinkElement(e))}adoptStyleSheets(e,t){if(e.length===0)return;const s={id:t,styleIds:[]},r=[];for(const n of e){let o;if(this.styleMirror.has(n))o=this.styleMirror.getId(n);else{o=this.styleMirror.add(n);const a=Array.from(n.rules||CSSRule);r.push({styleId:o,rules:a.map((l,c)=>({rule:Gu(l),index:c}))})}s.styleIds.push(o)}r.length>0&&(s.styles=r),this.adoptedStyleSheetCb(s)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(e){}}function Ge(i){return Object.assign(Object.assign({},i),{timestamp:Date.now()})}let Oe,Cr,Go,Er=!1;const ut=Yv();function Ws(i={}){const{emit:e,checkoutEveryNms:t,checkoutEveryNth:s,blockClass:r="rr-block",blockSelector:n=null,ignoreClass:o="rr-ignore",maskTextClass:a="rr-mask",maskTextSelector:l=null,inlineStylesheet:c=!0,maskAllInputs:h,maskInputOptions:u,slimDOMOptions:p,maskInputFn:d,maskTextFn:g,hooks:_,packFn:b,sampling:v={},dataURLOptions:C={},mousemoveWait:E,recordCanvas:S=!1,recordCrossOriginIframes:w=!1,userTriggeredOnInput:R=!1,collectFonts:M=!1,inlineImages:D=!1,plugins:G,keepIframeSrcFn:k=()=>!1,ignoreCSSAttributes:O=new Set([])}=i,V=w?window.parent===window:!0;let X=!1;if(!V)try{window.parent.document,X=!1}catch{X=!0}if(V&&!e)throw new Error("emit function is required");E!==void 0&&v.mousemove===void 0&&(v.mousemove=E),ut.reset();const z=h===!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}:u!==void 0?u:{password:!0},de=p===!0||p==="all"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:p==="all",headMetaDescKeywords:p==="all"}:p||{};yx();let B,U=0;const q=F=>{for(const fe of G||[])fe.eventProcessor&&(F=fe.eventProcessor(F));return b&&(F=b(F)),F};Oe=(F,fe)=>{var le;if(!((le=ls[0])===null||le===void 0)&&le.isFrozen()&&F.type!==ue.FullSnapshot&&!(F.type===ue.IncrementalSnapshot&&F.data.source===oe.Mutation)&&ls.forEach(L=>L.unfreeze()),V)e==null||e(q(F),fe);else if(X){const L={type:"rrweb",event:q(F),isCheckout:fe};window.parent.postMessage(L,"*")}if(F.type===ue.FullSnapshot)B=F,U=0;else if(F.type===ue.IncrementalSnapshot){if(F.data.source===oe.Mutation&&F.data.isAttachIframe)return;U++;const L=s&&U>=s,me=t&&F.timestamp-B.timestamp>t;(L||me)&&Cr(!0)}};const N=F=>{Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Mutation},F)}))},K=F=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Scroll},F)})),Z=F=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.CanvasMutation},F)})),$=F=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.AdoptedStyleSheet},F)})),ae=new e0({mutationCb:N,adoptedStyleSheetCb:$}),xe=new Bx({mirror:ut,mutationCb:N,stylesheetManager:ae,recordCrossOriginIframes:w,wrappedEmit:Oe});for(const F of G||[])F.getMirror&&F.getMirror({nodeMirror:ut,crossOriginIframeMirror:xe.crossOriginIframeMirror,crossOriginIframeStyleMirror:xe.crossOriginIframeStyleMirror});Go=new Qx({recordCanvas:S,mutationCb:Z,win:window,blockClass:r,blockSelector:n,mirror:ut,sampling:v.canvas,dataURLOptions:C});const Se=new Dx({mutationCb:N,scrollCb:K,bypassOptions:{blockClass:r,blockSelector:n,maskTextClass:a,maskTextSelector:l,inlineStylesheet:c,maskInputOptions:z,dataURLOptions:C,maskTextFn:g,maskInputFn:d,recordCanvas:S,inlineImages:D,sampling:v,slimDOMOptions:de,iframeManager:xe,stylesheetManager:ae,canvasManager:Go,keepIframeSrcFn:k},mirror:ut});Cr=(F=!1)=>{var fe,le,L,me,Y,se;Oe(Ge({type:ue.Meta,data:{href:window.location.href,width:Xu(),height:ju()}}),F),ae.reset(),ls.forEach(ce=>ce.lock());const we=gx(document,{mirror:ut,blockClass:r,blockSelector:n,maskTextClass:a,maskTextSelector:l,inlineStylesheet:c,maskAllInputs:z,maskTextFn:g,slimDOM:de,dataURLOptions:C,recordCanvas:S,inlineImages:D,onSerialize:ce=>{Ku(ce,ut)&&xe.addIframe(ce),Zu(ce,ut)&&ae.trackLinkElement(ce),Ju(ce)&&Se.addShadowRoot(ce.shadowRoot,document)},onIframeLoad:(ce,He)=>{xe.attachIframe(ce,He),Se.observeAttachShadow(ce)},onStylesheetLoad:(ce,He)=>{ae.attachLinkElement(ce,He)},keepIframeSrcFn:k});if(!we)return console.warn("Failed to snapshot the document");Oe(Ge({type:ue.FullSnapshot,data:{node:we,initialOffset:{left:window.pageXOffset!==void 0?window.pageXOffset:(document==null?void 0:document.documentElement.scrollLeft)||((le=(fe=document==null?void 0:document.body)===null||fe===void 0?void 0:fe.parentElement)===null||le===void 0?void 0:le.scrollLeft)||((L=document==null?void 0:document.body)===null||L===void 0?void 0:L.scrollLeft)||0,top:window.pageYOffset!==void 0?window.pageYOffset:(document==null?void 0:document.documentElement.scrollTop)||((Y=(me=document==null?void 0:document.body)===null||me===void 0?void 0:me.parentElement)===null||Y===void 0?void 0:Y.scrollTop)||((se=document==null?void 0:document.body)===null||se===void 0?void 0:se.scrollTop)||0}}})),ls.forEach(ce=>ce.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&ae.adoptStyleSheets(document.adoptedStyleSheets,ut.getId(document))};try{const F=[];F.push(Ze("DOMContentLoaded",()=>{Oe(Ge({type:ue.DomContentLoaded,data:{}}))}));const fe=L=>{var me;return Ox({mutationCb:N,mousemoveCb:(Y,se)=>Oe(Ge({type:ue.IncrementalSnapshot,data:{source:se,positions:Y}})),mouseInteractionCb:Y=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.MouseInteraction},Y)})),scrollCb:K,viewportResizeCb:Y=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.ViewportResize},Y)})),inputCb:Y=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Input},Y)})),mediaInteractionCb:Y=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.MediaInteraction},Y)})),styleSheetRuleCb:Y=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.StyleSheetRule},Y)})),styleDeclarationCb:Y=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.StyleDeclaration},Y)})),canvasMutationCb:Z,fontCb:Y=>Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Font},Y)})),selectionCb:Y=>{Oe(Ge({type:ue.IncrementalSnapshot,data:Object.assign({source:oe.Selection},Y)}))},blockClass:r,ignoreClass:o,maskTextClass:a,maskTextSelector:l,maskInputOptions:z,inlineStylesheet:c,sampling:v,recordCanvas:S,inlineImages:D,userTriggeredOnInput:R,collectFonts:M,doc:L,maskInputFn:d,maskTextFn:g,keepIframeSrcFn:k,blockSelector:n,slimDOMOptions:de,dataURLOptions:C,mirror:ut,iframeManager:xe,stylesheetManager:ae,shadowDomManager:Se,canvasManager:Go,ignoreCSSAttributes:O,plugins:((me=G==null?void 0:G.filter(Y=>Y.observer))===null||me===void 0?void 0:me.map(Y=>({observer:Y.observer,options:Y.options,callback:se=>Oe(Ge({type:ue.Plugin,data:{plugin:Y.name,payload:se}}))})))||[]},_)};xe.addLoadListener(L=>{F.push(fe(L.contentDocument))});const le=()=>{Cr(),F.push(fe(document)),Er=!0};return document.readyState==="interactive"||document.readyState==="complete"?le():F.push(Ze("load",()=>{Oe(Ge({type:ue.Load,data:{}})),le()},window)),()=>{F.forEach(L=>L()),Er=!1}}catch(F){console.warn(F)}}Ws.addCustomEvent=(i,e)=>{if(!Er)throw new Error("please add custom event after start recording");Oe(Ge({type:ue.Custom,data:{tag:i,payload:e}}))},Ws.freezePage=()=>{ls.forEach(i=>i.freeze())},Ws.takeFullSnapshot=i=>{if(!Er)throw new Error("please take full snapshot after start recording");Cr(i)},Ws.mirror=ut;const t0=3e4,s0=3,i0=0;function r0(i){if(i.type!==s0)return!1;const e=i.data;if(!e||e.source!==i0)return!1;const{adds:t,removes:s,texts:r,attributes:n}=e;return t&&t.length||s&&s.length||r&&r.length?!1:n&&n.length>0?n.every(o=>o.attributes&&Object.keys(o.attributes).length===1&&"style"in o.attributes):!0}function n0(){for(const i of[Text,Comment,CDATASection,ProcessingInstruction])i.prototype.matches||(i.prototype.matches=function(){return!1})}class Cd{constructor(){this.onEvent=null,this.stopFn=null,this._recording=!1,this._paused=!1}get isRecording(){return this._recording}get isPaused(){return this._paused}start(){if(this._recording)return;n0();const e=Ws({emit:t=>{var s;this._paused||r0(t)||(s=this.onEvent)==null||s.call(this,t)},checkoutEveryNms:t0,blockClass:"hs-no-record",blockSelector:'#holostaff-widget-root, #holostaff-agent, [id^="anam-avatar"], video, [autocomplete^="cc-"], [data-hs-no-record]',maskAllInputs:!1,maskInputOptions:{password:!0,email:!0,tel:!0},maskTextSelector:"[data-hs-mask]",sampling:{mousemove:100,scroll:150,input:"last"}});e?(this.stopFn=e,this._recording=!0,this._paused=!1,console.log("[RRWebRecorder] Started recording")):console.warn("[RRWebRecorder] record() returned undefined — recording may have failed")}stop(){var e;this._recording&&((e=this.stopFn)==null||e.call(this),this.stopFn=null,this._recording=!1,this._paused=!1,console.log("[RRWebRecorder] Stopped recording"))}pause(){!this._recording||this._paused||(this._paused=!0,console.log("[RRWebRecorder] Paused"))}resume(){!this._recording||!this._paused||(this._paused=!1,Ws.takeFullSnapshot(),console.log("[RRWebRecorder] Resumed (full snapshot taken)"))}}function o0(i){return i.startsWith("ws://")||i.startsWith("wss://")?i:`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}${i.startsWith("/")?"":"/"}${i}`}const Ed=1e3,a0=3e4,l0=500;class Sd{constructor(e,t){this.onIntervention=null,this.onStatus=null,this.onConnected=null,this.onDisconnected=null,this.ws=null,this.eventBuffer=[],this.reconnectDelay=Ed,this.reconnectTimer=null,this._connected=!1,this._closed=!1,this.url=o0(e),this.initPayload={type:"init",...t}}get isConnected(){return this._connected}connect(){this._closed||this.doConnect()}close(){if(this._closed=!0,this.clearReconnectTimer(),this.ws){try{this.ws.close()}catch{}this.ws=null}this._connected=!1}sendRRWebEvent(e){this.send({type:"rrweb",event:e})}sendActionComplete(e,t){this.send({type:"action_complete",actionId:e,result:t})}sendConversationStarted(){this.send({type:"conversation_started"})}sendConversationEnded(e){this.send({type:"conversation_ended",summary:e})}sendPageChanged(e,t,s){this.send({type:"page_changed",url:e,pathname:t,title:s})}doConnect(){if(!this._closed){try{this.ws=new WebSocket(this.url)}catch(e){console.warn("[VisionWS] Failed to create WebSocket:",e),this.scheduleReconnect();return}this.ws.onopen=()=>{var e;console.log("[VisionWS] Connected"),this._connected=!0,this.reconnectDelay=Ed,this.ws.send(JSON.stringify(this.initPayload)),this.flushBuffer(),(e=this.onConnected)==null||e.call(this)},this.ws.onmessage=e=>{const t=e.data;typeof t=="string"?this.parseAndHandle(t):t instanceof Blob?t.text().then(s=>this.parseAndHandle(s)):t instanceof ArrayBuffer?this.parseAndHandle(new TextDecoder().decode(t)):console.warn("[VisionWS] Unknown message data type:",typeof t)},this.ws.onclose=()=>{var t;const e=this._connected;this._connected=!1,this.ws=null,e&&(console.log("[VisionWS] Disconnected"),(t=this.onDisconnected)==null||t.call(this)),this._closed||this.scheduleReconnect()},this.ws.onerror=e=>{console.warn("[VisionWS] Error:",e)}}}parseAndHandle(e){var t,s;try{const r=JSON.parse(e);switch(r.type){case"suggest_intervention":(t=this.onIntervention)==null||t.call(this,r);break;case"status":(s=this.onStatus)==null||s.call(this,r);break;default:console.log("[VisionWS] Unknown message type:",r.type)}}catch(r){console.warn("[VisionWS] Failed to parse message:",r)}}send(e){var t;this._connected&&((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN?this.ws.send(JSON.stringify(e)):(this.eventBuffer.length>=l0&&this.eventBuffer.shift(),this.eventBuffer.push(e))}flushBuffer(){if(!(!this._connected||!this.ws)){for(const e of this.eventBuffer)this.ws.send(JSON.stringify(e));this.eventBuffer.length>0&&console.log(`[VisionWS] Flushed ${this.eventBuffer.length} buffered messages`),this.eventBuffer=[]}}scheduleReconnect(){if(this._closed||this.reconnectTimer)return;const e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*2,a0),console.log(`[VisionWS] Reconnecting in ${e}ms...`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.doConnect()},e)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}}const c0={sm:"var(--hs-radius-sm)",md:"var(--hs-radius-md)",lg:"var(--hs-radius-lg)",pill:"var(--hs-radius-pill)"},h0={base:"var(--hs-glass-bg)",elevated:"var(--hs-glass-bg-elevated)",solid:"var(--hs-glass-bg-solid)"};function Yt(i={}){const{tag:e="div",radius:t="md",elevation:s="base",interactive:r=!1,className:n,role:o}=i,a=document.createElement(e);return n&&(a.className=n),o&&a.setAttribute("role",o),Object.assign(a.style,{background:h0[s],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)",borderRadius:c0[t],boxShadow:s==="elevated"?"var(--hs-glass-shadow-elevated)":"var(--hs-glass-shadow)",color:"var(--hs-text-primary)",fontFamily:"var(--hs-font)",fontSize:"var(--hs-text-base)",lineHeight:"var(--hs-line-height)",boxSizing:"border-box"}),r&&(a.style.transition=`border-color var(--hs-fade-duration) var(--hs-ease-fast),
|
|
960
|
+
box-shadow var(--hs-fade-duration) var(--hs-ease-fast)`,a.style.cursor="pointer",a.addEventListener("mouseenter",()=>{a.style.borderColor="var(--hs-glass-border-hover)"}),a.addEventListener("mouseleave",()=>{a.style.borderColor="var(--hs-glass-border)"})),a}function bt(i,e="primary",t="base",s="normal"){const r={primary:"var(--hs-text-primary)",secondary:"var(--hs-text-secondary)",tertiary:"var(--hs-text-tertiary)"},n={xs:"var(--hs-text-xs)",sm:"var(--hs-text-sm)",base:"var(--hs-text-base)",lg:"var(--hs-text-lg)",xl:"var(--hs-text-xl)"},o={normal:"var(--hs-weight-normal)",medium:"var(--hs-weight-medium)",semibold:"var(--hs-weight-semibold)"};return Object.assign(i.style,{color:r[e],fontSize:n[t],fontWeight:o[s],fontFamily:"var(--hs-font)",lineHeight:"var(--hs-line-height)",margin:"0"}),i}function vt(i){const{label:e,variant:t="default",size:s="md",icon:r,onClick:n}=i,o=document.createElement("button");o.textContent=r?`${r} ${e}`:e;const a=s==="sm"?"4px 10px":"8px 16px",l=s==="sm"?"var(--hs-text-sm)":"var(--hs-text-base)";switch(Object.assign(o.style,{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"var(--hs-space-1)",padding:a,fontSize:l,fontWeight:"var(--hs-weight-medium)",fontFamily:"var(--hs-font)",lineHeight:"1",border:"none",borderRadius:"var(--hs-radius-pill)",cursor:"pointer",transition:"all var(--hs-fade-duration) var(--hs-ease-fast)",outline:"none",whiteSpace:"nowrap"}),t){case"accent":Object.assign(o.style,{background:"var(--hs-accent)",color:"var(--hs-accent-text)",boxShadow:"0 2px 12px var(--hs-accent-glow)"}),o.addEventListener("mouseenter",()=>{o.style.filter="brightness(1.12)",o.style.transform="scale(1.03)"}),o.addEventListener("mouseleave",()=>{o.style.filter="",o.style.transform=""});break;case"ghost":Object.assign(o.style,{background:"transparent",color:"var(--hs-text-secondary)"}),o.addEventListener("mouseenter",()=>{o.style.background="var(--hs-glass-bg)",o.style.color="var(--hs-text-primary)"}),o.addEventListener("mouseleave",()=>{o.style.background="transparent",o.style.color="var(--hs-text-secondary)"});break;default:Object.assign(o.style,{background:"var(--hs-glass-bg-elevated)",color:"var(--hs-text-primary)",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)"}),o.addEventListener("mouseenter",()=>{o.style.borderColor="var(--hs-glass-border-hover)",o.style.transform="scale(1.03)"}),o.addEventListener("mouseleave",()=>{o.style.borderColor="var(--hs-glass-border)",o.style.transform=""});break}return n&&o.addEventListener("click",c=>{c.stopPropagation(),n(c)}),o}function Td(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t}var Ad=function(){};const Fo=(i,e,t)=>Math.min(Math.max(t,i),e),Lo=.001,u0=.01,d0=10,f0=.05,p0=1;function m0({duration:i=800,bounce:e=.25,velocity:t=0,mass:s=1}){let r,n,o=1-e;o=Fo(f0,p0,o),i=Fo(u0,d0,i/1e3),o<1?(r=c=>{const h=c*o,u=h*i,p=h-t,d=Wo(c,o),g=Math.exp(-u);return Lo-p/d*g},n=c=>{const u=c*o*i,p=u*t+t,d=Math.pow(o,2)*Math.pow(c,2)*i,g=Math.exp(-u),_=Wo(Math.pow(c,2),o);return(-r(c)+Lo>0?-1:1)*((p-d)*g)/_}):(r=c=>{const h=Math.exp(-c*i),u=(c-t)*i+1;return-Lo+h*u},n=c=>{const h=Math.exp(-c*i),u=(t-c)*(i*i);return h*u});const a=5/i,l=_0(r,n,a);if(i=i*1e3,isNaN(l))return{stiffness:100,damping:10,duration:i};{const c=Math.pow(l,2)*s;return{stiffness:c,damping:o*2*Math.sqrt(s*c),duration:i}}}const g0=12;function _0(i,e,t){let s=t;for(let r=1;r<g0;r++)s=s-i(s)/e(s);return s}function Wo(i,e){return i*Math.sqrt(1-e*e)}const y0=["duration","bounce"],b0=["stiffness","damping","mass"];function wd(i,e){return e.some(t=>i[t]!==void 0)}function v0(i){let e=Object.assign({velocity:0,stiffness:100,damping:10,mass:1,isResolvedFromDuration:!1},i);if(!wd(i,b0)&&wd(i,y0)){const t=m0(i);e=Object.assign(Object.assign(Object.assign({},e),t),{velocity:0,mass:1}),e.isResolvedFromDuration=!0}return e}function Ho(i){var{from:e=0,to:t=1,restSpeed:s=2,restDelta:r}=i,n=Td(i,["from","to","restSpeed","restDelta"]);const o={done:!1,value:e};let{stiffness:a,damping:l,mass:c,velocity:h,duration:u,isResolvedFromDuration:p}=v0(n),d=Id,g=Id;function _(){const b=h?-(h/1e3):0,v=t-e,C=l/(2*Math.sqrt(a*c)),E=Math.sqrt(a/c)/1e3;if(r===void 0&&(r=Math.min(Math.abs(t-e)/100,.4)),C<1){const S=Wo(E,C);d=w=>{const R=Math.exp(-C*E*w);return t-R*((b+C*E*v)/S*Math.sin(S*w)+v*Math.cos(S*w))},g=w=>{const R=Math.exp(-C*E*w);return C*E*R*(Math.sin(S*w)*(b+C*E*v)/S+v*Math.cos(S*w))-R*(Math.cos(S*w)*(b+C*E*v)-S*v*Math.sin(S*w))}}else if(C===1)d=S=>t-Math.exp(-E*S)*(v+(b+E*v)*S);else{const S=E*Math.sqrt(C*C-1);d=w=>{const R=Math.exp(-C*E*w),M=Math.min(S*w,300);return t-R*((b+C*E*v)*Math.sinh(M)+S*v*Math.cosh(M))/S}}}return _(),{next:b=>{const v=d(b);if(p)o.done=b>=u;else{const C=g(b)*1e3,E=Math.abs(C)<=s,S=Math.abs(t-v)<=r;o.done=E&&S}return o.value=o.done?t:v,o},flipTarget:()=>{h=-h,[e,t]=[t,e],_()}}}Ho.needsInterpolation=(i,e)=>typeof i=="string"||typeof e=="string";const Id=i=>0,Rd=(i,e,t)=>{const s=e-i;return s===0?1:(t-i)/s},Vo=(i,e,t)=>-t*i+t*e+i,Md=(i,e)=>t=>Math.max(Math.min(t,e),i),wi=i=>i%1?Number(i.toFixed(5)):i,Sr=/(-)?([\d]*\.?[\d])+/g,zo=/(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))/gi,x0=/^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))$/i;function Ii(i){return typeof i=="string"}const Tr={test:i=>typeof i=="number",parse:parseFloat,transform:i=>i},Pd=Object.assign(Object.assign({},Tr),{transform:Md(0,1)});Object.assign(Object.assign({},Tr),{default:1});const Ri=(i=>({test:e=>Ii(e)&&e.endsWith(i)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${i}`}))("%");Object.assign(Object.assign({},Ri),{parse:i=>Ri.parse(i)/100,transform:i=>Ri.transform(i*100)});const $o=(i,e)=>t=>!!(Ii(t)&&x0.test(t)&&t.startsWith(i)||e&&Object.prototype.hasOwnProperty.call(t,e)),kd=(i,e,t)=>s=>{if(!Ii(s))return s;const[r,n,o,a]=s.match(Sr);return{[i]:parseFloat(r),[e]:parseFloat(n),[t]:parseFloat(o),alpha:a!==void 0?parseFloat(a):1}},cs={test:$o("hsl","hue"),parse:kd("hue","saturation","lightness"),transform:({hue:i,saturation:e,lightness:t,alpha:s=1})=>"hsla("+Math.round(i)+", "+Ri.transform(wi(e))+", "+Ri.transform(wi(t))+", "+wi(Pd.transform(s))+")"},C0=Md(0,255),jo=Object.assign(Object.assign({},Tr),{transform:i=>Math.round(C0(i))}),qt={test:$o("rgb","red"),parse:kd("red","green","blue"),transform:({red:i,green:e,blue:t,alpha:s=1})=>"rgba("+jo.transform(i)+", "+jo.transform(e)+", "+jo.transform(t)+", "+wi(Pd.transform(s))+")"};function E0(i){let e="",t="",s="",r="";return i.length>5?(e=i.substr(1,2),t=i.substr(3,2),s=i.substr(5,2),r=i.substr(7,2)):(e=i.substr(1,1),t=i.substr(2,1),s=i.substr(3,1),r=i.substr(4,1),e+=e,t+=t,s+=s,r+=r),{red:parseInt(e,16),green:parseInt(t,16),blue:parseInt(s,16),alpha:r?parseInt(r,16)/255:1}}const Xo={test:$o("#"),parse:E0,transform:qt.transform},Ar={test:i=>qt.test(i)||Xo.test(i)||cs.test(i),parse:i=>qt.test(i)?qt.parse(i):cs.test(i)?cs.parse(i):Xo.parse(i),transform:i=>Ii(i)?i:i.hasOwnProperty("red")?qt.transform(i):cs.transform(i)},Od="${c}",Bd="${n}";function S0(i){var e,t,s,r;return isNaN(i)&&Ii(i)&&((t=(e=i.match(Sr))===null||e===void 0?void 0:e.length)!==null&&t!==void 0?t:0)+((r=(s=i.match(zo))===null||s===void 0?void 0:s.length)!==null&&r!==void 0?r:0)>0}function Dd(i){typeof i=="number"&&(i=`${i}`);const e=[];let t=0;const s=i.match(zo);s&&(t=s.length,i=i.replace(zo,Od),e.push(...s.map(Ar.parse)));const r=i.match(Sr);return r&&(i=i.replace(Sr,Bd),e.push(...r.map(Tr.parse))),{values:e,numColors:t,tokenised:i}}function Nd(i){return Dd(i).values}function Ud(i){const{values:e,numColors:t,tokenised:s}=Dd(i),r=e.length;return n=>{let o=s;for(let a=0;a<r;a++)o=o.replace(a<t?Od:Bd,a<t?Ar.transform(n[a]):wi(n[a]));return o}}const T0=i=>typeof i=="number"?0:i;function A0(i){const e=Nd(i);return Ud(i)(e.map(T0))}const Gd={test:S0,parse:Nd,createTransformer:Ud,getAnimatableNone:A0};function Yo(i,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?i+(e-i)*6*t:t<1/2?e:t<2/3?i+(e-i)*(2/3-t)*6:i}function Fd({hue:i,saturation:e,lightness:t,alpha:s}){i/=360,e/=100,t/=100;let r=0,n=0,o=0;if(!e)r=n=o=t;else{const a=t<.5?t*(1+e):t+e-t*e,l=2*t-a;r=Yo(l,a,i+1/3),n=Yo(l,a,i),o=Yo(l,a,i-1/3)}return{red:Math.round(r*255),green:Math.round(n*255),blue:Math.round(o*255),alpha:s}}const w0=(i,e,t)=>{const s=i*i,r=e*e;return Math.sqrt(Math.max(0,t*(r-s)+s))},I0=[Xo,qt,cs],Ld=i=>I0.find(e=>e.test(i)),Wd=(i,e)=>{let t=Ld(i),s=Ld(e),r=t.parse(i),n=s.parse(e);t===cs&&(r=Fd(r),t=qt),s===cs&&(n=Fd(n),s=qt);const o=Object.assign({},r);return a=>{for(const l in o)l!=="alpha"&&(o[l]=w0(r[l],n[l],a));return o.alpha=Vo(r.alpha,n.alpha,a),t.transform(o)}},R0=i=>typeof i=="number",M0=(i,e)=>t=>e(i(t)),Hd=(...i)=>i.reduce(M0);function Vd(i,e){return R0(i)?t=>Vo(i,e,t):Ar.test(i)?Wd(i,e):jd(i,e)}const zd=(i,e)=>{const t=[...i],s=t.length,r=i.map((n,o)=>Vd(n,e[o]));return n=>{for(let o=0;o<s;o++)t[o]=r[o](n);return t}},P0=(i,e)=>{const t=Object.assign(Object.assign({},i),e),s={};for(const r in t)i[r]!==void 0&&e[r]!==void 0&&(s[r]=Vd(i[r],e[r]));return r=>{for(const n in s)t[n]=s[n](r);return t}};function $d(i){const e=Gd.parse(i),t=e.length;let s=0,r=0,n=0;for(let o=0;o<t;o++)s||typeof e[o]=="number"?s++:e[o].hue!==void 0?n++:r++;return{parsed:e,numNumbers:s,numRGB:r,numHSL:n}}const jd=(i,e)=>{const t=Gd.createTransformer(e),s=$d(i),r=$d(e);return s.numHSL===r.numHSL&&s.numRGB===r.numRGB&&s.numNumbers>=r.numNumbers?Hd(zd(s.parsed,r.parsed),t):o=>`${o>0?e:i}`},k0=(i,e)=>t=>Vo(i,e,t);function O0(i){if(typeof i=="number")return k0;if(typeof i=="string")return Ar.test(i)?Wd:jd;if(Array.isArray(i))return zd;if(typeof i=="object")return P0}function B0(i,e,t){const s=[],r=t||O0(i[0]),n=i.length-1;for(let o=0;o<n;o++){let a=r(i[o],i[o+1]);if(e){const l=Array.isArray(e)?e[o]:e;a=Hd(l,a)}s.push(a)}return s}function D0([i,e],[t]){return s=>t(Rd(i,e,s))}function N0(i,e){const t=i.length,s=t-1;return r=>{let n=0,o=!1;if(r<=i[0]?o=!0:r>=i[s]&&(n=s-1,o=!0),!o){let l=1;for(;l<t&&!(i[l]>r||l===s);l++);n=l-1}const a=Rd(i[n],i[n+1],r);return e[n](a)}}function Xd(i,e,{clamp:t=!0,ease:s,mixer:r}={}){const n=i.length;Ad(n===e.length),Ad(!s||!Array.isArray(s)||s.length===n-1),i[0]>i[n-1]&&(i=[].concat(i),e=[].concat(e),i.reverse(),e.reverse());const o=B0(e,s,r),a=n===2?D0(i,o):N0(i,o);return t?l=>a(Fo(i[0],i[n-1],l)):a}const U0=i=>e=>e<=.5?i(2*e)/2:(2-i(2*(1-e)))/2,G0=(i=>e=>Math.pow(e,i))(2),F0=U0(G0);function L0(i,e){return i.map(()=>e||F0).splice(0,i.length-1)}function W0(i){const e=i.length;return i.map((t,s)=>s!==0?s/(e-1):0)}function H0(i,e){return i.map(t=>t*e)}function wr({from:i=0,to:e=1,ease:t,offset:s,duration:r=300}){const n={done:!1,value:i},o=Array.isArray(e)?e:[i,e],a=H0(s&&s.length===o.length?s:W0(o),r);function l(){return Xd(a,o,{ease:Array.isArray(t)?t:L0(o,t)})}let c=l();return{next:h=>(n.value=c(h),n.done=h>=r,n),flipTarget:()=>{o.reverse(),c=l()}}}function V0({velocity:i=0,from:e=0,power:t=.8,timeConstant:s=350,restDelta:r=.5,modifyTarget:n}){const o={done:!1,value:e};let a=t*i;const l=e+a,c=n===void 0?l:n(l);return c!==l&&(a=c-e),{next:h=>{const u=-a*Math.exp(-h/s);return o.done=!(u>r||u<-r),o.value=o.done?c:c+u,o},flipTarget:()=>{}}}const Yd={keyframes:wr,spring:Ho,decay:V0};function z0(i){if(Array.isArray(i.to))return wr;if(Yd[i.type])return Yd[i.type];const e=new Set(Object.keys(i));return e.has("ease")||e.has("duration")&&!e.has("dampingRatio")?wr:e.has("dampingRatio")||e.has("stiffness")||e.has("mass")||e.has("damping")||e.has("restSpeed")||e.has("restDelta")?Ho:wr}const qd=1/60*1e3,$0=typeof performance<"u"?()=>performance.now():()=>Date.now(),Kd=typeof window<"u"?i=>window.requestAnimationFrame(i):i=>setTimeout(()=>i($0()),qd);function j0(i){let e=[],t=[],s=0,r=!1,n=!1;const o=new WeakSet,a={schedule:(l,c=!1,h=!1)=>{const u=h&&r,p=u?e:t;return c&&o.add(l),p.indexOf(l)===-1&&(p.push(l),u&&r&&(s=e.length)),l},cancel:l=>{const c=t.indexOf(l);c!==-1&&t.splice(c,1),o.delete(l)},process:l=>{if(r){n=!0;return}if(r=!0,[e,t]=[t,e],t.length=0,s=e.length,s)for(let c=0;c<s;c++){const h=e[c];h(l),o.has(h)&&(a.schedule(h),i())}r=!1,n&&(n=!1,a.process(l))}};return a}const X0=40;let qo=!0,Mi=!1,Ko=!1;const Pi={delta:0,timestamp:0},ki=["read","update","preRender","render","postRender"],Ir=ki.reduce((i,e)=>(i[e]=j0(()=>Mi=!0),i),{}),Y0=ki.reduce((i,e)=>{const t=Ir[e];return i[e]=(s,r=!1,n=!1)=>(Mi||Z0(),t.schedule(s,r,n)),i},{}),q0=ki.reduce((i,e)=>(i[e]=Ir[e].cancel,i),{});ki.reduce((i,e)=>(i[e]=()=>Ir[e].process(Pi),i),{});const K0=i=>Ir[i].process(Pi),Zd=i=>{Mi=!1,Pi.delta=qo?qd:Math.max(Math.min(i-Pi.timestamp,X0),1),Pi.timestamp=i,Ko=!0,ki.forEach(K0),Ko=!1,Mi&&(qo=!1,Kd(Zd))},Z0=()=>{Mi=!0,qo=!0,Ko||Kd(Zd)};function Jd(i,e,t=0){return i-e-t}function J0(i,e,t=0,s=!0){return s?Jd(e+-i,e,t):e-(i-e)+t}function Q0(i,e,t,s){return s?i>=e+t:i<=-t}const eC=i=>{const e=({delta:t})=>i(t);return{start:()=>Y0.update(e,!0),stop:()=>q0.update(e)}};function tC(i){var e,t,{from:s,autoplay:r=!0,driver:n=eC,elapsed:o=0,repeat:a=0,repeatType:l="loop",repeatDelay:c=0,onPlay:h,onStop:u,onComplete:p,onRepeat:d,onUpdate:g}=i,_=Td(i,["from","autoplay","driver","elapsed","repeat","repeatType","repeatDelay","onPlay","onStop","onComplete","onRepeat","onUpdate"]);let{to:b}=_,v,C=0,E=_.duration,S,w=!1,R=!0,M;const D=z0(_);!((t=(e=D).needsInterpolation)===null||t===void 0)&&t.call(e,s,b)&&(M=Xd([0,100],[s,b],{clamp:!1}),s=0,b=100);const G=D(Object.assign(Object.assign({},_),{from:s,to:b}));function k(){C++,l==="reverse"?(R=C%2===0,o=J0(o,E,c,R)):(o=Jd(o,E,c),l==="mirror"&&G.flipTarget()),w=!1,d&&d()}function O(){v.stop(),p&&p()}function V(z){if(R||(z=-z),o+=z,!w){const de=G.next(Math.max(0,o));S=de.value,M&&(S=M(S)),w=R?de.done:o<=0}g==null||g(S),w&&(C===0&&(E??(E=o)),C<a?Q0(o,E,c,R)&&k():O())}function X(){h==null||h(),v=n(V),v.start()}return r&&X(),{stop:()=>{u==null||u(),v.stop()}}}const sC={snappy:{stiffness:300,damping:28,mass:.8},gentle:{stiffness:170,damping:26,mass:1},bouncy:{stiffness:400,damping:20,mass:.6},smooth:{stiffness:200,damping:30,mass:1}};function Kt(i){const e=i.preset?sC[i.preset]:void 0,t=tC({from:i.from,to:i.to,type:"spring",stiffness:i.stiffness??(e==null?void 0:e.stiffness)??170,damping:i.damping??(e==null?void 0:e.damping)??26,mass:i.mass??(e==null?void 0:e.mass)??1,onUpdate:i.onUpdate,onComplete:i.onComplete});return{stop:()=>t.stop()}}function iC(i,e,t,s="smooth",r){return Kt({from:e,to:t,preset:s,onUpdate:n=>{i.style.opacity=String(n)},onComplete:r})}function rt(i,e={}){const{from:t={},preset:s="snappy",onComplete:r}=e,n=t.opacity??0,o=t.scale??.92,a=t.y??8;i.style.opacity=String(n),i.style.transform=`scale(${o}) translateY(${a}px)`;const l=[];let c=0;const h=3,u=()=>{++c>=h&&(r==null||r())};return l.push(Kt({from:n,to:1,preset:s,onUpdate:p=>{i.style.opacity=String(p)},onComplete:u})),l.push(Kt({from:o,to:1,preset:s,onUpdate:p=>{var g;const d=parseFloat(((g=i.style.transform.match(/translateY\(([^)]+)\)/))==null?void 0:g[1])??"0");i.style.transform=`scale(${p}) translateY(${d}px)`},onComplete:u})),l.push(Kt({from:a,to:0,preset:s,onUpdate:p=>{var g;const d=parseFloat(((g=i.style.transform.match(/scale\(([^)]+)\)/))==null?void 0:g[1])??"1");i.style.transform=`scale(${d}) translateY(${p}px)`},onComplete:u})),{stop:()=>l.forEach(p=>p.stop())}}function Ot(i,e={}){const{to:t={},preset:s="smooth",remove:r=!0,onComplete:n}=e,o=t.opacity??0,a=t.scale??.92,l=t.y??8,c=[];let h=0;const u=3,p=()=>{++h>=u&&(r&&i.remove(),n==null||n())};return c.push(Kt({from:parseFloat(i.style.opacity||"1"),to:o,preset:s,onUpdate:d=>{i.style.opacity=String(d)},onComplete:p})),c.push(Kt({from:1,to:a,preset:s,onUpdate:d=>{var _;const g=parseFloat(((_=i.style.transform.match(/translateY\(([^)]+)\)/))==null?void 0:_[1])??"0");i.style.transform=`scale(${d}) translateY(${g}px)`},onComplete:p})),c.push(Kt({from:0,to:l,preset:s,onUpdate:d=>{var _;const g=parseFloat(((_=i.style.transform.match(/scale\(([^)]+)\)/))==null?void 0:_[1])??"1");i.style.transform=`scale(${g}) translateY(${d}px)`},onComplete:p})),{stop:()=>c.forEach(d=>d.stop())}}const Qd="holostaff-liquid-tokens",W={glassBlur:"20px",glassSaturate:"180%",dark:{glassBg:"rgba(255, 255, 255, 0.10)",glassBgElevated:"rgba(255, 255, 255, 0.16)",glassBgSolid:"rgba(30, 30, 40, 0.85)",glassBorder:"rgba(255, 255, 255, 0.14)",glassBorderHover:"rgba(255, 255, 255, 0.28)",glassShadow:"0 8px 32px rgba(0, 0, 0, 0.24)",glassShadowElevated:"0 12px 48px rgba(0, 0, 0, 0.32)",textPrimary:"rgba(255, 255, 255, 0.92)",textSecondary:"rgba(255, 255, 255, 0.56)",textTertiary:"rgba(255, 255, 255, 0.32)",divider:"rgba(255, 255, 255, 0.08)"},light:{glassBg:"rgba(255, 255, 255, 0.55)",glassBgElevated:"rgba(255, 255, 255, 0.72)",glassBgSolid:"rgba(255, 255, 255, 0.92)",glassBorder:"rgba(0, 0, 0, 0.06)",glassBorderHover:"rgba(0, 0, 0, 0.12)",glassShadow:"0 8px 32px rgba(0, 0, 0, 0.08)",glassShadowElevated:"0 12px 48px rgba(0, 0, 0, 0.12)",textPrimary:"rgba(0, 0, 0, 0.85)",textSecondary:"rgba(0, 0, 0, 0.50)",textTertiary:"rgba(0, 0, 0, 0.28)",divider:"rgba(0, 0, 0, 0.06)"},radiusSm:"10px",radiusMd:"16px",radiusLg:"24px",radiusPill:"9999px",font:"-apple-system, 'Inter', 'Segoe UI', system-ui, sans-serif",textXs:"11px",textSm:"12px",textBase:"14px",textLg:"16px",textXl:"20px",weightNormal:"400",weightMedium:"500",weightSemibold:"600",lineHeight:"1.45",springDuration:"500ms",springEasing:"cubic-bezier(0.34, 1.56, 0.64, 1)",easeFast:"cubic-bezier(0.25, 0.1, 0.25, 1)",fadeDuration:"200ms",accent:"#7C5CFF",accentGlow:"rgba(124, 92, 255, 0.35)",accentText:"#ffffff",space1:"4px",space2:"8px",space3:"12px",space4:"16px",space5:"20px",space6:"24px",space8:"32px",zOverlay:"2147483644",zControls:"2147483646",zTop:"2147483647"};function xt(){if(document.getElementById(Qd))return;const i=document.createElement("style");i.id=Qd,i.textContent=`
|
|
961
961
|
/* Holostaff Liquid Glass Design Tokens */
|
|
962
962
|
:root {
|
|
963
963
|
--hs-glass-blur: ${W.glassBlur};
|
|
@@ -1034,20 +1034,20 @@ or you can use record.mirror to access the mirror instance during recording.`;le
|
|
|
1034
1034
|
--hs-fade-duration: 0ms;
|
|
1035
1035
|
}
|
|
1036
1036
|
}
|
|
1037
|
-
`,document.head.appendChild(i)}const
|
|
1037
|
+
`,document.head.appendChild(i)}const rC=15e3;class nC{constructor(e){this.currentIntervention=null,this.autoDismissTimer=null,this._active=!1,this.cardOverlay=null,this.cardOverlayAnim=null,this.onAccept=null,this.wsClient=e.wsClient,this.getWidgetState=e.getWidgetState,this.getHomeVisible=e.getHomeVisible,this.inlineTarget=e.inlineTarget??null,this.pill=e.pill??null,this.wsClient.onIntervention=t=>this.handleIntervention(t)}get isActive(){return this._active}destroy(){this.cleanup(),this.wsClient.onIntervention=null}handleIntervention(e){const t=this.getWidgetState();if(t==="active"||t==="connecting"){this.wsClient.sendActionComplete(e.actionId,"ignored");return}if(this._active)return;console.log(`[ActionExecutor] Showing suggestion: "${e.message}"`),this.currentIntervention=e,this._active=!0;const s=this.getHomeVisible();this.inlineTarget&&s?this.showCardOverlay(e.message):this.pill&&this.showInPill(e.message),this.autoDismissTimer=setTimeout(()=>this.handleIgnore(),rC)}showCardOverlay(e){var r;if(!this.inlineTarget)return;xt(),(r=this.inlineTarget.querySelector(".hs-suggestion-overlay"))==null||r.remove(),this.cardOverlay=Yt({radius:"lg",elevation:"solid",className:"hs-suggestion-overlay"}),Object.assign(this.cardOverlay.style,{position:"absolute",inset:"0",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:W.space4,boxSizing:"border-box",zIndex:"10",textAlign:"center",opacity:"0"}),this.cardOverlay.setAttribute("data-hs-theme","dark");const t=document.createElement("p");bt(t,"primary","base","normal"),Object.assign(t.style,{margin:`0 0 ${W.space4} 0`,maxWidth:"260px"}),t.textContent=e,this.cardOverlay.appendChild(t);const s=document.createElement("div");Object.assign(s.style,{display:"flex",gap:W.space3}),s.appendChild(vt({label:"Let's talk",variant:"accent",size:"md",onClick:()=>this.handleAccept()})),s.appendChild(vt({label:"Not now",variant:"ghost",size:"sm",onClick:()=>this.handleDecline()})),this.cardOverlay.appendChild(s),this.inlineTarget.style.position="relative",this.inlineTarget.appendChild(this.cardOverlay),this.cardOverlayAnim=rt(this.cardOverlay,{preset:"snappy",from:{opacity:0,scale:.96,y:8}})}hideCardOverlay(){var e;if((e=this.cardOverlayAnim)==null||e.stop(),this.cardOverlay){const t=this.cardOverlay;this.cardOverlay=null,this.cardOverlayAnim=Ot(t,{remove:!0,preset:"smooth"})}}showInPill(e){this.pill&&(this.pill.showSuggestion(e),this.pill.onSuggestionAccept=()=>this.handleAccept(),this.pill.onSuggestionDismiss=()=>this.handleDecline())}clearPillSuggestion(){this.pill&&(this.pill.clearSuggestion(),this.pill.onSuggestionAccept=null,this.pill.onSuggestionDismiss=null)}handleAccept(){var r;if(!this._active||!this.currentIntervention)return;console.log("[ActionExecutor] User accepted suggestion");const e=this.currentIntervention,t=`${e.context}
|
|
1038
1038
|
|
|
1039
1039
|
The user accepted your suggestion: "${e.message}"
|
|
1040
|
-
Continue the conversation naturally from this context.`,s=e.actionId;this.cleanup(),this.wsClient.sendActionComplete(s,"accepted"),(r=this.onAccept)==null||r.call(this,t)}handleDecline(){if(!this._active||!this.currentIntervention)return;console.log("[ActionExecutor] User declined suggestion");const e=this.currentIntervention.actionId;this.cleanup(),this.wsClient.sendActionComplete(e,"declined")}handleIgnore(){if(!this._active||!this.currentIntervention)return;console.log("[ActionExecutor] Suggestion auto-dismissed (ignored)");const e=this.currentIntervention.actionId;this.cleanup(),this.wsClient.sendActionComplete(e,"ignored")}cleanup(){this._active=!1,this.autoDismissTimer&&(clearTimeout(this.autoDismissTimer),this.autoDismissTimer=null),this.hideCardOverlay(),this.clearPillSuggestion(),this.currentIntervention=null}}function
|
|
1040
|
+
Continue the conversation naturally from this context.`,s=e.actionId;this.cleanup(),this.wsClient.sendActionComplete(s,"accepted"),(r=this.onAccept)==null||r.call(this,t)}handleDecline(){if(!this._active||!this.currentIntervention)return;console.log("[ActionExecutor] User declined suggestion");const e=this.currentIntervention.actionId;this.cleanup(),this.wsClient.sendActionComplete(e,"declined")}handleIgnore(){if(!this._active||!this.currentIntervention)return;console.log("[ActionExecutor] Suggestion auto-dismissed (ignored)");const e=this.currentIntervention.actionId;this.cleanup(),this.wsClient.sendActionComplete(e,"ignored")}cleanup(){this._active=!1,this.autoDismissTimer&&(clearTimeout(this.autoDismissTimer),this.autoDismissTimer=null),this.hideCardOverlay(),this.clearPillSuggestion(),this.currentIntervention=null}}function oC(i){try{const e=i.left+i.width/2,t=i.top+i.height/2,s=document.elementFromPoint(e,t);if(!s)return"dark";const r=aC(s);return cC(r)>.5?"light":"dark"}catch{return"dark"}}function aC(i){let e=i;for(;e;){const s=getComputedStyle(e).backgroundColor;if(s&&s!=="transparent"&&s!=="rgba(0, 0, 0, 0)")return lC(s);e=e.parentElement}return[255,255,255]}function lC(i){const e=i.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);return e?[parseInt(e[1]),parseInt(e[2]),parseInt(e[3])]:[255,255,255]}function cC([i,e,t]){const[s,r,n]=[i/255,e/255,t/255].map(o=>o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4));return .2126*s+.7152*r+.0722*n}function hC(i,e){i.setAttribute("data-hs-theme",e)}function Hs(i,e){const t=i.getBoundingClientRect(),s=oC(t);return hC(i,s),s}const ef={idle:"var(--hs-text-tertiary)",listening:"#34C759",thinking:"#FF9F0A",speaking:"var(--hs-accent)",connecting:"var(--hs-text-tertiary)"},uC={idle:"",listening:"Listening",thinking:"Thinking",speaking:"Speaking",connecting:"Connecting"};class dC{constructor(){this.pulseAnim=null,this.currentStatus="idle",this.theme="dark",xt(),this.el=Yt({radius:"lg",elevation:"base",className:"hs-avatar-frame"}),Object.assign(this.el.style,{position:"relative",overflow:"hidden",display:"flex",flexDirection:"column"}),this.glowRing=document.createElement("div"),Object.assign(this.glowRing.style,{position:"absolute",inset:"-1px",borderRadius:"inherit",border:"2px solid transparent",pointerEvents:"none",transition:"border-color 0.3s ease, box-shadow 0.3s ease",zIndex:"2"}),this.el.appendChild(this.glowRing),this.statusBar=document.createElement("div"),Object.assign(this.statusBar.style,{position:"absolute",bottom:"0",left:"0",right:"0",display:"flex",alignItems:"center",justifyContent:"center",gap:"var(--hs-space-2)",padding:"var(--hs-space-2) var(--hs-space-3)",background:"linear-gradient(transparent, rgba(0,0,0,0.3))",zIndex:"3",opacity:"0",transition:"opacity 0.2s ease",pointerEvents:"none"}),this.statusDot=document.createElement("div"),Object.assign(this.statusDot.style,{width:"6px",height:"6px",borderRadius:"50%",background:ef.idle,transition:"background 0.3s ease, box-shadow 0.3s ease",flexShrink:"0"}),this.statusLabel=document.createElement("span"),Object.assign(this.statusLabel.style,{fontSize:"var(--hs-text-xs)",fontFamily:"var(--hs-font)",fontWeight:"var(--hs-weight-medium)",color:"rgba(255,255,255,0.8)",letterSpacing:"0.02em"}),this.statusBar.appendChild(this.statusDot),this.statusBar.appendChild(this.statusLabel),this.el.appendChild(this.statusBar)}setSize(e,t){this.el.style.width=`${e}px`,this.el.style.height=`${t}px`}appendContent(e){this.el.insertBefore(e,this.glowRing)}setStatus(e){if(e===this.currentStatus)return;this.currentStatus=e;const t=ef[e],s=uC[e];this.statusDot.style.background=t,this.statusDot.style.boxShadow=e!=="idle"?`0 0 6px ${t}`:"none",this.statusLabel.textContent=s,this.statusBar.style.opacity=e==="idle"?"0":"1",e==="speaking"||e==="listening"?(this.glowRing.style.borderColor=t,this.glowRing.style.boxShadow=`0 0 16px ${t}40, inset 0 0 16px ${t}10`,this.startPulse(t)):(this.glowRing.style.borderColor="transparent",this.glowRing.style.boxShadow="none",this.stopPulse())}detectTheme(){return this.theme=Hs(this.el),this.theme}setTheme(e){this.theme=e,this.el.setAttribute("data-hs-theme",e)}show(){return this.el.style.display="flex",rt(this.el,{preset:"gentle"})}hide(e=!1){return Ot(this.el,{remove:e,preset:"smooth"})}startPulse(e){this.stopPulse(),this.pulseAnim=Kt({from:0,to:1,preset:"gentle",onUpdate:t=>{const s=.15+t*.25;this.glowRing.style.boxShadow=`0 0 ${16+t*8}px ${e}${Math.round(s*255).toString(16).padStart(2,"0")}, inset 0 0 ${16+t*4}px ${e}10`},onComplete:()=>{(this.currentStatus==="speaking"||this.currentStatus==="listening")&&this.startPulse(e)}})}stopPulse(){var e;(e=this.pulseAnim)==null||e.stop(),this.pulseAnim=null}destroy(){this.stopPulse(),this.el.remove()}}const Rr=30,fC=3e3,pC=500;class mC{constructor(e){this.prompts=[],this.promptIndex=0,this.typeTimer=null,this.holdTimer=null,this.cycling=!1,this.currentAnim=null,this.onClick=null,this.onAccept=null,this.onDismiss=null,xt(),this.prompts=e??["Need help finding something?","I can walk you through this page.","Questions? I'm here to help."],this.el=Yt({radius:"md",elevation:"elevated",className:"hs-speech-bubble"}),Object.assign(this.el.style,{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"12px",padding:"var(--hs-space-3) var(--hs-space-4)",maxWidth:"280px",minWidth:"120px",pointerEvents:"auto",cursor:"pointer",opacity:"0",display:"none",zIndex:"4"}),this.textEl=document.createElement("span"),bt(this.textEl,"primary","base","normal"),this.textEl.style.display="block",this.el.appendChild(this.textEl),this.actionsEl=document.createElement("div"),Object.assign(this.actionsEl.style,{display:"none",gap:"var(--hs-space-2)",marginTop:"var(--hs-space-3)",justifyContent:"flex-end"}),this.el.appendChild(this.actionsEl),this.tailEl=document.createElement("div"),Object.assign(this.tailEl.style,{position:"absolute",bottom:"-6px",left:"50%",transform:"translateX(-50%) rotate(45deg)",width:"12px",height:"12px",background:"var(--hs-glass-bg-elevated)",backdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",WebkitBackdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",borderRight:"1px solid var(--hs-glass-border)",borderBottom:"1px solid var(--hs-glass-border)",zIndex:"-1"}),this.el.appendChild(this.tailEl),this.el.addEventListener("click",t=>{var s;t.stopPropagation(),(s=this.onClick)==null||s.call(this)})}start(){this.cycling||(this.cycling=!0,this.promptIndex=0,this.showNextPrompt())}stop(){this.cycling=!1,this.clearTimers(),this.hide()}showNextPrompt(){if(!this.cycling)return;const e=this.prompts[this.promptIndex%this.prompts.length];this.promptIndex++,this.actionsEl.style.display="none",this.typewrite(e,()=>{this.holdTimer=setTimeout(()=>{this.fadeOutAndNext()},fC)})}fadeOutAndNext(){this.currentAnim=Ot(this.el,{remove:!1,preset:"smooth",onComplete:()=>{this.el.style.display="none",setTimeout(()=>{this.cycling&&this.showNextPrompt()},pC)}})}typewrite(e,t){this.clearTimers(),this.textEl.textContent="",this.el.style.display="block",this.currentAnim=rt(this.el,{preset:"snappy"});let s=0;const r=()=>{s<e.length?(this.textEl.textContent=e.slice(0,++s),this.typeTimer=setTimeout(r,Rr)):t==null||t()};this.typeTimer=setTimeout(r,Rr)}showStatic(e){this.clearTimers(),this.cycling=!1,this.actionsEl.style.display="none",this.textEl.textContent=e,this.el.style.display="block",this.currentAnim=rt(this.el,{preset:"snappy"})}hideStatic(){this.hide()}showSuggestion(e){this.clearTimers(),this.cycling=!1,this.textEl.textContent="",this.actionsEl.innerHTML="";const t=vt({label:"Sure",variant:"accent",size:"sm",icon:"✓",onClick:()=>{var o;(o=this.onAccept)==null||o.call(this),this.hide()}}),s=vt({label:"Not now",variant:"ghost",size:"sm",icon:"✕",onClick:()=>{var o;(o=this.onDismiss)==null||o.call(this),this.hide()}});this.actionsEl.appendChild(t),this.actionsEl.appendChild(s),this.actionsEl.style.display="flex",this.el.style.display="block",this.currentAnim=rt(this.el,{preset:"snappy"});let r=0;const n=()=>{r<e.length&&(this.textEl.textContent=e.slice(0,++r),this.typeTimer=setTimeout(n,Rr))};this.typeTimer=setTimeout(n,Rr)}hide(){var e;(e=this.currentAnim)==null||e.stop(),this.el.style.display!=="none"&&(this.currentAnim=Ot(this.el,{remove:!1,preset:"smooth",onComplete:()=>{this.el.style.display="none"}}))}clearTimers(){this.typeTimer&&(clearTimeout(this.typeTimer),this.typeTimer=null),this.holdTimer&&(clearTimeout(this.holdTimer),this.holdTimer=null)}destroy(){var e;(e=this.currentAnim)==null||e.stop(),this.clearTimers(),this.el.remove()}}const gC=`
|
|
1041
1041
|
@keyframes hs-pill-pulse {
|
|
1042
1042
|
0%, 100% { box-shadow: 0 0 0 0 var(--hs-accent-glow); }
|
|
1043
1043
|
50% { box-shadow: 0 0 14px 5px var(--hs-accent-glow); }
|
|
1044
1044
|
}
|
|
1045
|
-
`;class tf{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,s){if(this.el)return;if(xt(),this.avatarUrl=e,this.videoUrl=t,this.staffName=s,this.el=Yt({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"}),Hs(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=s,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=s.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"),bt(this.nameEl,"primary","base","medium"),this.nameEl.textContent=s,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"),bt(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=vt({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 s;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&&((s=this.currentAnim)==null||s.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=Ot(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=mC,document.head.appendChild(e)}}const gC=15e3,_C=320;class yC{constructor(){this.cards=[],this.anchor=null}setAnchor(e){this.anchor=e}showTextCard(e,t){const s=this.createCard(),r=document.createElement("div");bt(r,"primary","base","semibold"),r.textContent=e,r.style.marginBottom="var(--hs-space-2)",s.el.appendChild(r);const n=document.createElement("div");bt(n,"secondary","sm","normal"),n.textContent=t,n.style.whiteSpace="pre-wrap",s.el.appendChild(n),this.mountCard(s)}showImageCard(e,t){const s=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"}),s.el.appendChild(r),t){const n=document.createElement("div");bt(n,"secondary","sm","normal"),n.textContent=t,s.el.appendChild(n)}this.mountCard(s)}showBulletList(e,t){const s=this.createCard(),r=document.createElement("div");bt(r,"primary","base","semibold"),r.textContent=e,r.style.marginBottom="var(--hs-space-2)",s.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");bt(c,"secondary","sm","normal"),c.textContent=o,a.appendChild(c),n.appendChild(a)}),s.el.appendChild(n),this.mountCard(s)}dismissAll(){this.cards.forEach(e=>this.removeCard(e)),this.cards=[]}createCard(){xt();const e=Yt({radius:"md",elevation:"elevated",className:"hs-overlay-card"});Object.assign(e.style,{position:"fixed",maxWidth:`${Math.min(_C,window.innerWidth-32)}px`,padding:"var(--hs-space-4)",zIndex:W.zOverlay,opacity:"0",pointerEvents:"auto"});const t=vt({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 s=setTimeout(()=>this.dismiss(r),gC),r={el:e,timer:s,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 s=500+t*10,r=e.offsetHeight||80;Object.assign(e.style,{bottom:`${s+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=Ot(e.el,{remove:!0,preset:"smooth"})}}class bC{constructor(){this.el=null,this.currentAnim=null,this.minimized=!1,this.onMinimize=null,this.onRestore=null,this.onClose=null}show(){xt(),this.hide(),this.el=Yt({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"}),Hs(this.el);const e=vt({label:this.minimized?"▲":"—",variant:"ghost",size:"sm",onClick:()=>{var s,r;this.minimized?(this.minimized=!1,e.textContent="—",(s=this.onRestore)==null||s.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=vt({label:"✕",variant:"ghost",size:"sm",onClick:()=>{var s;return(s=this.onClose)==null?void 0:s.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=Ot(e,{remove:!0,preset:"smooth"})}}const vC=1e4;class xC{constructor(){this.el=null,this.currentAnim=null,this.autoTimer=null,this.resolver=null}ask(e){return xt(),this.dismiss(),new Promise(t=>{this.resolver=t,this.el=Yt({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"),Hs(this.el);const s=document.createElement("p");bt(s,"primary","base","normal"),s.textContent=e,s.style.marginBottom="var(--hs-space-4)",this.el.appendChild(s);const r=document.createElement("div");Object.assign(r.style,{display:"flex",gap:"var(--hs-space-3)",justifyContent:"center"}),r.appendChild(vt({label:"Yes",variant:"accent",size:"md",onClick:()=>this.resolve(!0)})),r.appendChild(vt({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),vC)})}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=Ot(t,{remove:!0,preset:"smooth"})}}}const CC=520,EC=340,Zo=12;class SC{constructor(){this.currentAnim=null,xt(),this.el=Yt({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:`${CC}px`,height:`${EC}px`,zIndex:W.zOverlay,overflow:"hidden",display:"flex",flexDirection:"column",opacity:"0",padding:`${Zo}px ${Zo}px 0 ${Zo}px`,borderRadius:"var(--hs-radius-lg) var(--hs-radius-lg) 0 0",borderBottom:"none"}),Hs(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=Ot(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 TC=`
|
|
1045
|
+
`;class tf{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,s){if(this.el)return;if(xt(),this.avatarUrl=e,this.videoUrl=t,this.staffName=s,this.el=Yt({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"}),Hs(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=s,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=s.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"),bt(this.nameEl,"primary","base","medium"),this.nameEl.textContent=s,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"),bt(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=vt({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 s;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&&((s=this.currentAnim)==null||s.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=Ot(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=gC,document.head.appendChild(e)}}const _C=15e3,yC=320;class bC{constructor(){this.cards=[],this.anchor=null}setAnchor(e){this.anchor=e}showTextCard(e,t){const s=this.createCard(),r=document.createElement("div");bt(r,"primary","base","semibold"),r.textContent=e,r.style.marginBottom="var(--hs-space-2)",s.el.appendChild(r);const n=document.createElement("div");bt(n,"secondary","sm","normal"),n.textContent=t,n.style.whiteSpace="pre-wrap",s.el.appendChild(n),this.mountCard(s)}showImageCard(e,t){const s=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"}),s.el.appendChild(r),t){const n=document.createElement("div");bt(n,"secondary","sm","normal"),n.textContent=t,s.el.appendChild(n)}this.mountCard(s)}showBulletList(e,t){const s=this.createCard(),r=document.createElement("div");bt(r,"primary","base","semibold"),r.textContent=e,r.style.marginBottom="var(--hs-space-2)",s.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");bt(c,"secondary","sm","normal"),c.textContent=o,a.appendChild(c),n.appendChild(a)}),s.el.appendChild(n),this.mountCard(s)}dismissAll(){this.cards.forEach(e=>this.removeCard(e)),this.cards=[]}createCard(){xt();const e=Yt({radius:"md",elevation:"elevated",className:"hs-overlay-card"});Object.assign(e.style,{position:"fixed",maxWidth:`${Math.min(yC,window.innerWidth-32)}px`,padding:"var(--hs-space-4)",zIndex:W.zOverlay,opacity:"0",pointerEvents:"auto"});const t=vt({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 s=setTimeout(()=>this.dismiss(r),_C),r={el:e,timer:s,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 s=500+t*10,r=e.offsetHeight||80;Object.assign(e.style,{bottom:`${s+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=Ot(e.el,{remove:!0,preset:"smooth"})}}class vC{constructor(){this.el=null,this.currentAnim=null,this.minimized=!1,this.onMinimize=null,this.onRestore=null,this.onClose=null}show(){xt(),this.hide(),this.el=Yt({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"}),Hs(this.el);const e=vt({label:this.minimized?"▲":"—",variant:"ghost",size:"sm",onClick:()=>{var s,r;this.minimized?(this.minimized=!1,e.textContent="—",(s=this.onRestore)==null||s.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=vt({label:"✕",variant:"ghost",size:"sm",onClick:()=>{var s;return(s=this.onClose)==null?void 0:s.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=Ot(e,{remove:!0,preset:"smooth"})}}const xC=1e4;class CC{constructor(){this.el=null,this.currentAnim=null,this.autoTimer=null,this.resolver=null}ask(e){return xt(),this.dismiss(),new Promise(t=>{this.resolver=t,this.el=Yt({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"),Hs(this.el);const s=document.createElement("p");bt(s,"primary","base","normal"),s.textContent=e,s.style.marginBottom="var(--hs-space-4)",this.el.appendChild(s);const r=document.createElement("div");Object.assign(r.style,{display:"flex",gap:"var(--hs-space-3)",justifyContent:"center"}),r.appendChild(vt({label:"Yes",variant:"accent",size:"md",onClick:()=>this.resolve(!0)})),r.appendChild(vt({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),xC)})}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=Ot(t,{remove:!0,preset:"smooth"})}}}const EC=520,SC=340,Zo=12;class TC{constructor(){this.currentAnim=null,xt(),this.el=Yt({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:`${EC}px`,height:`${SC}px`,zIndex:W.zOverlay,overflow:"hidden",display:"flex",flexDirection:"column",opacity:"0",padding:`${Zo}px ${Zo}px 0 ${Zo}px`,borderRadius:"var(--hs-radius-lg) var(--hs-radius-lg) 0 0",borderBottom:"none"}),Hs(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=Ot(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 AC=`
|
|
1046
1046
|
@keyframes hs-highlight-glow {
|
|
1047
1047
|
0%, 100% { box-shadow: 0 0 8px var(--hs-accent-glow), inset 0 0 4px var(--hs-accent-glow); }
|
|
1048
1048
|
50% { box-shadow: 0 0 20px var(--hs-accent-glow), inset 0 0 8px var(--hs-accent-glow); }
|
|
1049
1049
|
}
|
|
1050
|
-
`;let sf=!1;class AC{constructor(){this.highlights=[]}highlight(e,t=3e3){xt(),this.injectPulseStyle();const s=document.createElement("div");s.className="hs-highlight-overlay",s.setAttribute("data-hs-theme","dark");const r=()=>{const l=e.getBoundingClientRect();Object.assign(s.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(s);const n=()=>r();window.addEventListener("scroll",n,{passive:!0});const o=setTimeout(()=>this.removeHighlight(a),t),a={overlay:s,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=sC(e.overlay,1,0,"smooth",()=>{e.overlay.remove()});const t=this.highlights.indexOf(e);t>=0&&this.highlights.splice(t,1)}injectPulseStyle(){if(sf)return;sf=!0;const e=document.createElement("style");e.textContent=TC,document.head.appendChild(e)}}const wC=800,IC=600*1e3,RC=540*1e3,rf=60*1e3,MC=90*1e3,PC=[{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 nf{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(){xt(),this.stage=new Vb,await this.stage.init(this.config.mode,this.config.container),this.avatar=new $b(this.stage.stageWidth,this.stage.stageHeight),this.stage.app.stage.addChild(this.avatar.container),await this.loadIdleAsset(),this.avatarFrame=new uC,this.stage.rootElement&&Hs(this.stage.rootElement),this.bubble=new pC(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 tf,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 s=document.createElement("div");Object.assign(s.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"}),s.appendChild(r),t.appendChild(s);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,s=t>0?e/t:0;s>=this.config.scrollThreshold&&this.state==="idle"?this.showTeaser():s<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()},wC))}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,s,r,n,o,a,l,c,h,u,p;if(!(this.state!=="teasing"&&this.state!=="idle")){if(this.state="connecting",(e=this.bubble)==null||e.stop(),(t=this.bubble)==null||t.hideStatic(),(s=this.actionExecutor)==null||s.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 Mf(this.config.staffId,this.config.backendUrl),console.log("[HolostaffWidget] Session tokens received"),this.logger=new Vv({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),(p=this.bubble)==null||p.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(s=>{s instanceof HTMLVideoElement&&s.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 SC,this.stageEl=this.stageBackdrop.el,this.stageBackdrop.show(),console.log("[HolostaffWidget] Moved to glass stage (bottom-center)")}returnToHome(){var t,s,r;if((t=this.stageBackdrop)==null||t.destroy(),this.stageBackdrop=null,this.stageEl=null,(s=this.homePlaceholder)==null||s.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 s;this.stopHomeObserver();const e=(s=this.stage)==null?void 0:s.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 kv({sessionToken:this.sessionResponse.anamSessionToken,inlineMode:this.isInline&&!!this.stageBackdrop}),this.anamSession.onConnected=()=>{console.log("[HolostaffWidget] Anam connected")},this.anamSession.onVideoReady=e=>{var t,s,r;console.log("[HolostaffWidget] Anam avatar video ready"),(t=this.bubble)==null||t.hideStatic(),(s=this.chatPill)==null||s.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,s=((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??"")+`
|
|
1050
|
+
`;let sf=!1;class wC{constructor(){this.highlights=[]}highlight(e,t=3e3){xt(),this.injectPulseStyle();const s=document.createElement("div");s.className="hs-highlight-overlay",s.setAttribute("data-hs-theme","dark");const r=()=>{const l=e.getBoundingClientRect();Object.assign(s.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(s);const n=()=>r();window.addEventListener("scroll",n,{passive:!0});const o=setTimeout(()=>this.removeHighlight(a),t),a={overlay:s,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=iC(e.overlay,1,0,"smooth",()=>{e.overlay.remove()});const t=this.highlights.indexOf(e);t>=0&&this.highlights.splice(t,1)}injectPulseStyle(){if(sf)return;sf=!0;const e=document.createElement("style");e.textContent=AC,document.head.appendChild(e)}}const IC=800,RC=600*1e3,MC=540*1e3,rf=60*1e3,PC=90*1e3,kC=[{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 nf{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(){xt(),this.stage=new zb,await this.stage.init(this.config.mode,this.config.container),this.avatar=new jb(this.stage.stageWidth,this.stage.stageHeight),this.stage.app.stage.addChild(this.avatar.container),await this.loadIdleAsset(),this.avatarFrame=new dC,this.stage.rootElement&&Hs(this.stage.rootElement),this.bubble=new mC(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 tf,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 s=document.createElement("div");Object.assign(s.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"}),s.appendChild(r),t.appendChild(s);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,s=t>0?e/t:0;s>=this.config.scrollThreshold&&this.state==="idle"?this.showTeaser():s<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()},IC))}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,s,r,n,o,a,l,c,h,u,p;if(!(this.state!=="teasing"&&this.state!=="idle")){if(this.state="connecting",(e=this.bubble)==null||e.stop(),(t=this.bubble)==null||t.hideStatic(),(s=this.actionExecutor)==null||s.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 Mf(this.config.staffId,this.config.backendUrl),console.log("[HolostaffWidget] Session tokens received"),this.logger=new zv({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),(p=this.bubble)==null||p.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(s=>{s instanceof HTMLVideoElement&&s.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 TC,this.stageEl=this.stageBackdrop.el,this.stageBackdrop.show(),console.log("[HolostaffWidget] Moved to glass stage (bottom-center)")}returnToHome(){var t,s,r;if((t=this.stageBackdrop)==null||t.destroy(),this.stageBackdrop=null,this.stageEl=null,(s=this.homePlaceholder)==null||s.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 s;this.stopHomeObserver();const e=(s=this.stage)==null?void 0:s.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 Ov({sessionToken:this.sessionResponse.anamSessionToken,inlineMode:this.isInline&&!!this.stageBackdrop}),this.anamSession.onConnected=()=>{console.log("[HolostaffWidget] Anam connected")},this.anamSession.onVideoReady=e=>{var t,s,r;console.log("[HolostaffWidget] Anam avatar video ready"),(t=this.bubble)==null||t.hideStatic(),(s=this.chatPill)==null||s.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,s=((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??"")+`
|
|
1051
1051
|
|
|
1052
1052
|
## Current Page
|
|
1053
1053
|
Title: ${e}
|
|
@@ -1062,5 +1062,5 @@ Then you can scroll to elements, highlight them, click links/buttons, or fill fo
|
|
|
1062
1062
|
All actions except form filling require the visitor to confirm before executing.`;this.visionContext&&(n+=`
|
|
1063
1063
|
|
|
1064
1064
|
## Context from observing the user's session
|
|
1065
|
-
`+this.visionContext,this.visionContext=null),this.realtimeSession=new qb({ephemeralKey:this.sessionResponse.realtimeEphemeralKey,webrtcUrl:this.sessionResponse.realtimeWebrtcUrl,voice:this.sessionResponse.staff.voiceId,instructions:n,tools:PC}),this.domAnalyzer=new Uv,this.highlightRenderer=new AC,this.confirmationPrompt=new xC,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 Qb,this.audioForwarder.onAudioChunk=l=>{var c;(c=this.anamSession)==null||c.sendAudioChunk(l)},await this.audioForwarder.start(a)},this.overlayRenderer=new yC,this.toolHandler=new Fv({realtimeSession:this.realtimeSession,domAnalyzer:this.domAnalyzer,pageActions:new Lv(this.domAnalyzer,this.highlightRenderer),overlayActions:new Wv(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 s,r,n,o,a,l,c,h;if((s=this.toolHandler)!=null&&s.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 s of t.content)s.transcript?this.logger.addStaffMessage(s.transcript):s.text&&this.logger.addStaffMessage(s.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 bC,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"})},RC),this.maxDurationTimer=setTimeout(()=>{console.log("[HolostaffWidget] Max session duration reached"),this.endConversation()},IC),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())},MC-rf))},rf)}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,s,r,n,o,a,l,c,h,u,p,d,g;(t=this.logger)==null||t.flush(),this.logger=null,this.clearSessionTimers(),(s=this.controls)==null||s.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,(p=this.chatPill)==null||p.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 tf,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 Cd,this.visionWs=new Sd(e,{staffId:this.config.staffId,visitorId:this.visitorId,pageUrl:location.href,pageTitle:document.title}),this.rrwebRecorder.onEvent=t=>{var s;(s=this.visionWs)==null||s.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 rC({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,s;(e=this.actionExecutor)==null||e.destroy(),this.actionExecutor=null,this.externalObserver||((t=this.rrwebRecorder)==null||t.stop(),this.rrwebRecorder=null,(s=this.visionWs)==null||s.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 s=`v_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`;return document.cookie=`${e}=${s}; max-age=${365*24*60*60}; path=/; SameSite=Lax`,s}pause(){var e,t,s;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(),(s=this.actionExecutor)==null||s.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,s;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(),(s=this.stage)==null||s.destroy(),this.bubble=null,this.avatar=null,this.stage=null}}function kC(i){return!i||i.length===0?[{pattern:"*"}]:i.map(e=>typeof e=="string"?{pattern:e}:e)}function OC(i,e){if(e==="*")return!0;if(!e.endsWith("/*")){const n=i.replace(/\/+$/,"")||"/",o=e.replace(/\/+$/,"")||"/";return n===o}const t=e.slice(0,-2),s=i.replace(/\/+$/,"")||"/",r=t.replace(/\/+$/,"")||"/";return s===r||s.startsWith(r+"/")}function of(i,e){for(const t of e)if(OC(i,t.pattern))return t;return null}class BC{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 DC(){var s;const i="hs_visitor_id",e=(s=document.cookie.split("; ").find(r=>r.startsWith(`${i}=`)))==null?void 0:s.split("=")[1];if(e)return e;const t=`v_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`;return document.cookie=`${i}=${t}; max-age=${365*24*60*60}; path=/; SameSite=Lax`,t}function NC(){const i=document.currentScript??document.querySelector("script[data-staff-id]");if(!i){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 nf(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=Tf(i);async function s(){let r=t,n=null,o=null;try{o=await Pf(t.staffId,t.backendUrl),r=Rf(t,i,o),n=o.widgetPrompts}catch(g){console.warn("[HolostaffWidget] Failed to fetch server config, using embed defaults:",g)}const a=kC(o==null?void 0:o.pagePatterns),l=DC();let c=null,h=null;r.visionWsUrl&&(c=new Cd,h=new Sd(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=of(location.pathname,a),p=null;if(u){let g=r;u.container&&(g={...r,mode:"inline",container:u.container}),p=e(g,o,n,c,h),window.holostaffWidget=p,p.init()}else console.log("[HolostaffWidget] No matching page pattern for",location.pathname,"— presenter not loaded (observer active)");const d=new BC(g=>{h==null||h.sendPageChanged(location.href,g,document.title);const _=of(g,a);if(_&&!p){console.log("[HolostaffWidget] SPA navigated to matching page:",g);let b=r;_.container&&(b={...r,mode:"inline",container:_.container}),p=e(b,o,n,c,h),window.holostaffWidget=p,p.init()}else if(_&&p){const b=_.container??null;b!==p.activeContainer&&p.updateContainer(b),p.resume()}else!_&&p&&p.pause()});window.__holostaffSPARouter=d}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>s()):s()}catch(e){console.error("[HolostaffWidget]",e)}}NC(),Q.add(Vp),Q.mixin(Ve,zp),Q.add(Lc),Q.add(Wc),Q.mixin(Ve,g_),Q.add($c),Q.add(Vc);const UC=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),GC=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));ds.HolostaffWidget=nf,Object.defineProperty(ds,Symbol.toStringTag,{value:"Module"})}));
|
|
1065
|
+
`+this.visionContext,this.visionContext=null),this.realtimeSession=new Kb({ephemeralKey:this.sessionResponse.realtimeEphemeralKey,webrtcUrl:this.sessionResponse.realtimeWebrtcUrl,voice:this.sessionResponse.staff.voiceId,instructions:n,tools:kC}),this.domAnalyzer=new Gv,this.highlightRenderer=new wC,this.confirmationPrompt=new CC,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 ev,this.audioForwarder.onAudioChunk=l=>{var c;(c=this.anamSession)==null||c.sendAudioChunk(l)},await this.audioForwarder.start(a)},this.overlayRenderer=new bC,this.toolHandler=new Lv({realtimeSession:this.realtimeSession,domAnalyzer:this.domAnalyzer,pageActions:new Wv(this.domAnalyzer,this.highlightRenderer),overlayActions:new Hv(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 s,r,n,o,a,l,c,h;if((s=this.toolHandler)!=null&&s.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 s of t.content)s.transcript?this.logger.addStaffMessage(s.transcript):s.text&&this.logger.addStaffMessage(s.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 vC,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"})},MC),this.maxDurationTimer=setTimeout(()=>{console.log("[HolostaffWidget] Max session duration reached"),this.endConversation()},RC),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())},PC-rf))},rf)}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,s,r,n,o,a,l,c,h,u,p,d,g;(t=this.logger)==null||t.flush(),this.logger=null,this.clearSessionTimers(),(s=this.controls)==null||s.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,(p=this.chatPill)==null||p.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 tf,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 Cd,this.visionWs=new Sd(e,{staffId:this.config.staffId,visitorId:this.visitorId,pageUrl:location.href,pageTitle:document.title}),this.rrwebRecorder.onEvent=t=>{var s;(s=this.visionWs)==null||s.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 nC({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,s;(e=this.actionExecutor)==null||e.destroy(),this.actionExecutor=null,this.externalObserver||((t=this.rrwebRecorder)==null||t.stop(),this.rrwebRecorder=null,(s=this.visionWs)==null||s.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 s=`v_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`;return document.cookie=`${e}=${s}; max-age=${365*24*60*60}; path=/; SameSite=Lax`,s}pause(){var e,t,s;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(),(s=this.actionExecutor)==null||s.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,s;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(),(s=this.stage)==null||s.destroy(),this.bubble=null,this.avatar=null,this.stage=null}}function OC(i){return!i||i.length===0?[{pattern:"*"}]:i.map(e=>typeof e=="string"?{pattern:e}:e)}function BC(i,e){if(e==="*")return!0;if(!e.endsWith("/*")){const n=i.replace(/\/+$/,"")||"/",o=e.replace(/\/+$/,"")||"/";return n===o}const t=e.slice(0,-2),s=i.replace(/\/+$/,"")||"/",r=t.replace(/\/+$/,"")||"/";return s===r||s.startsWith(r+"/")}function of(i,e){for(const t of e)if(BC(i,t.pattern))return t;return null}class DC{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 NC(){var s;const i="hs_visitor_id",e=(s=document.cookie.split("; ").find(r=>r.startsWith(`${i}=`)))==null?void 0:s.split("=")[1];if(e)return e;const t=`v_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`;return document.cookie=`${i}=${t}; max-age=${365*24*60*60}; path=/; SameSite=Lax`,t}function UC(){const i=document.currentScript??document.querySelector("script[data-staff-id]");if(!i){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 nf(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=Tf(i);async function s(){let r=t,n=null,o=null;try{o=await kf(t.staffId,t.backendUrl),r=Rf(t,i,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=OC(o==null?void 0:o.pagePatterns),l=NC();let c=null,h=null;r.visionWsUrl&&(c=new Cd,h=new Sd(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=of(location.pathname,a),p=null;if(u){let g=r;u.container&&(g={...r,mode:"inline",container:u.container}),p=e(g,o,n,c,h),window.holostaffWidget=p,p.init()}else console.log("[HolostaffWidget] No matching page pattern for",location.pathname,"— presenter not loaded (observer active)");const d=new DC(g=>{h==null||h.sendPageChanged(location.href,g,document.title);const _=of(g,a);if(_&&!p){console.log("[HolostaffWidget] SPA navigated to matching page:",g);let b=r;_.container&&(b={...r,mode:"inline",container:_.container}),p=e(b,o,n,c,h),window.holostaffWidget=p,p.init()}else if(_&&p){const b=_.container??null;b!==p.activeContainer&&p.updateContainer(b),p.resume()}else!_&&p&&p.pause()});window.__holostaffSPARouter=d}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>s()):s()}catch(e){console.error("[HolostaffWidget]",e)}}UC(),Q.add(zp),Q.mixin(Ve,$p),Q.add(Lc),Q.add(Wc),Q.mixin(Ve,__),Q.add($c),Q.add(Vc);const GC=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),FC=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));ds.HolostaffWidget=nf,Object.defineProperty(ds,Symbol.toStringTag,{value:"Module"})}));
|
|
1066
1066
|
//# sourceMappingURL=hs-widget.umd.js.map
|