@cyberart-io/engine 0.0.5 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/headless.js CHANGED
@@ -5,4 +5,4 @@
5
5
  * Not an OSI open-source license.
6
6
  */
7
7
 
8
- var Nn=(e,t)=>()=>(e&&(t=e(e=0)),t);var dr={};function cr(e,t){let n=e.indexOf(nn);if(n===-1)return null;let r=n+nn.length,s=`const __cyberSkip=new Set(${JSON.stringify(t)});const __cyberOrig=registerProcessor;registerProcessor=(n,p)=>__cyberSkip.has(n)?undefined:__cyberOrig(n,p);`;return e.slice(0,r)+s+e.slice(r)}var mt,ze,ur,De,nn,rn=Nn(()=>{"use strict";mt=/AudioWorkletProcessor with name:\s*["'`][^"'`]+["'`]\s+is already registered/i,ze="__cyberartWorkletPatchApplied";typeof window<"u"&&!window[ze]&&(window.addEventListener("error",e=>{let t=e?.message??"";mt.test(t)&&(e.preventDefault(),e.stopImmediatePropagation())},!0),window.addEventListener("unhandledrejection",e=>{let t=e?.reason,n=typeof t=="string"?t:t?.message??"";mt.test(n)&&e.preventDefault()}),window[ze]=!0);ur=!1,De=(...e)=>{ur&&console.log("[workletPatch]",...e)},nn="((AudioWorkletProcessor,registerProcessor)=>{";if(typeof AudioWorklet<"u"&&!AudioWorklet.prototype[ze]){let e=new WeakMap,t=/registerProcessor\s*\(\s*['"`]([^'"`]+)['"`]/g,n=AudioWorklet.prototype.addModule,r=0;AudioWorklet.prototype.addModule=async function(s,a){let c=++r,h=e.get(this);h||(h=new Set,e.set(this,h)),De(`#${c} addModule`,{url:s.slice(0,64),isBlob:s.startsWith("blob:"),knownBefore:[...h]});let g=s,b=null;if(s.startsWith("blob:")){let m=null;try{m=await(await fetch(s)).text()}catch(E){De(`#${c} blob fetch failed`,E)}if(m!==null){let E=new Set;for(let H of m.matchAll(t))E.add(H[1]);if(E.size>0){let H=[...E].filter(O=>h.has(O)),C=[...E].filter(O=>!h.has(O));if(H.length>0&&C.length===0){De(`#${c} short-circuit \u2014 all processors already registered`,H);return}if(H.length>0&&C.length>0){let O=cr(m,H);if(O!==null){let R=new Blob([O],{type:"application/javascript"});b=URL.createObjectURL(R),g=b,De(`#${c} rewrote blob; skipping`,H,"allowing",C)}else De(`#${c} blob rewrite failed; passing original through`)}C.forEach(O=>h.add(O))}}}return n.call(this,g,a).then(()=>{b&&URL.revokeObjectURL(b)},m=>{b&&URL.revokeObjectURL(b);let E=(m&&m.message)??"";if(!(mt.test(E)||/already registered/i.test(E)))throw m})},AudioWorklet.prototype[ze]=!0}});var j=class extends Error{constructor(n,r){super(r?`Headless Canvas2D does not support ${n}: ${r}`:`Headless Canvas2D does not support ${n}`);this.name="HeadlessUnsupportedOperationError";this.operation=n}},ge=class{constructor(t,n,r,i,s,a=0,c=0){this.stops=[];this.kind=t,this.x0=n,this.y0=r,this.x1=i,this.y1=s,this.r0=a,this.r1=c}addColorStop(t,n){if(!Number.isFinite(t)||t<0||t>1)throw new j("addColorStop","offset must be in [0, 1]");this.stops.push({offset:t,color:Ke(n)}),this.stops.sort((r,i)=>r.offset-i.offset)}colorAt(t){let n=t<0?0:t>1?1:t;if(this.stops.length===0)return{r:0,g:0,b:0,a:0};if(this.stops.length===1||n<=this.stops[0].offset)return this.stops[0].color;let r=this.stops[this.stops.length-1];if(n>=r.offset)return r.color;for(let i=1;i<this.stops.length;i++){let s=this.stops[i],a=this.stops[i-1];if(n<=s.offset){let c=s.offset-a.offset,h=c===0?0:(n-a.offset)/c;return jn(a.color,s.color,h)}}return r.color}},tt={a:1,b:0,c:0,d:1,e:0,f:0},Gn={black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",blue:"#0000ff",cyan:"#00ffff",magenta:"#ff00ff",yellow:"#ffff00",gold:"#ffd700",orange:"#ffa500",navy:"#000080",gray:"#808080",grey:"#808080",transparent:"#00000000"},we=new WeakMap,Ft,Pt=!1,at=class{constructor(t,n,r,i){this.context=null;this.onDeviceReset=null;this.canvas=t,this.width=Math.max(0,n|0),this.height=Math.max(0,r|0),this.alpha=i.alpha!==!1,this.pixels=new Uint8ClampedArray(this.width*this.height*4),this.glyphAtlas=i.glyphAtlas??Ft??Ut(),this.alpha||this.fillOpaqueBlack()}resize(t,n,r=!1){let i=Math.max(0,t|0),s=Math.max(0,n|0);i!==this.width||s!==this.height?(this.width=i,this.height=s,this.pixels=new Uint8ClampedArray(i*s*4)):r&&this.pixels.fill(0),this.alpha||this.fillOpaqueBlack()}fillOpaqueBlack(){let t=this.pixels;for(let n=3;n<t.length;n+=4)t[n]=255}};function Kn(e,t,n){let r=n??new Uint8ClampedArray(e*t*4);if(r.length!==e*t*4)throw new j("createImageFixture","data length must be width*height*4");return{__headlessImage:!0,width:e,height:t,data:r}}function ot(e){Ft=e}function Vn(e){return we.get(e)}function ut(e,t={}){let n=we.get(e);if(n?.context)return n.context;let r=Math.max(0,Number(e.width)||0),i=Math.max(0,Number(e.height)||0),s=new at(e,r,i,t);we.set(e,s);let a=Wn(s);return s.context=a,a}function Ot(e){let t=we.get(e);if(t)return t.resize(e.width,e.height,!1),Ee(t.width,t.height,t.pixels)}function Wn(e){let t={...tt},n=[],r="#000000",i="#000000",s={r:0,g:0,b:0,a:255},a={r:0,g:0,b:0,a:255},c=1,h="source-over",g=1,b="butt",m="10px sans-serif",E="start",H="alphabetic",C=null,O=!0,R=[],G=null,K=(o,p)=>{G={points:[T(o,p)],closed:!1},R.push(G)},z=(o,p)=>{if(!G){K(o,p);return}G.points.push(T(o,p))},v=()=>{if(!G||G.points.length===0)return;G.closed=!0;let o=G.points[0];G.points.push({x:o.x,y:o.y})},T=(o,p)=>({x:t.a*o+t.c*p+t.e,y:t.b*o+t.d*p+t.f}),l=()=>{if(h!=="source-over"&&h!=="copy")throw new j("globalCompositeOperation",h)},x=()=>{e.resize(e.canvas.width,e.canvas.height,!1)},U=()=>{t={...tt},n.length=0,R.length=0,G=null,C=null,r="#000000",i="#000000",s={r:0,g:0,b:0,a:255},a={r:0,g:0,b:0,a:255},c=1,h="source-over",g=1,b="butt",m="10px sans-serif",E="start",H="alphabetic",O=!0};e.onDeviceReset=U;let V=(o,p,f,A=h)=>{if(o<0||p<0||o>=e.width||p>=e.height||C&&C[p*e.width+o]===0)return;let w=(p*e.width+o)*4,S=e.pixels;if(A==="copy"){S[w]=f.r,S[w+1]=f.g,S[w+2]=f.b,S[w+3]=e.alpha?f.a:255;return}let I=Math.round(f.a/255*c*255);if(I<=0)return;if(I>=255){S[w]=f.r,S[w+1]=f.g,S[w+2]=f.b,S[w+3]=255;return}let M=I/255,_=S[w+3]/255,B=M+_*(1-M);if(B<=0){S[w]=0,S[w+1]=0,S[w+2]=0,S[w+3]=e.alpha?0:255;return}S[w]=Math.round((f.r*M+S[w]*_*(1-M))/B),S[w+1]=Math.round((f.g*M+S[w+1]*_*(1-M))/B),S[w+2]=Math.round((f.b*M+S[w+2]*_*(1-M))/B),S[w+3]=e.alpha?Math.round(B*255):255},W=(o,p,f,A)=>{if(!(o instanceof ge))return p;let w=Ge(t,f+.5,A+.5);return Bn(o,w.x,w.y)},Q=(o,p,f,A,w)=>{l(),x();let S=rt(o,e.width,e.height);if(S)for(let I=S.minY;I<=S.maxY;I++)for(let M=S.minX;M<=S.maxX;M++){let _=M+.5,B=I+.5;Dt(o,_,B,A)&&V(M,I,W(p,f,M,I),w)}},ee=o=>{l(),x();let p=Math.sqrt(Math.abs(t.a*t.d-t.b*t.c)),f=g*(p===0?1:p)/2,A=rt(o,e.width,e.height,f+1);if(A)for(let w=A.minY;w<=A.maxY;w++)for(let S=A.minX;S<=A.maxX;S++)qn(o,S+.5,w+.5,f,b)&&V(S,w,W(i,a,S,w))},d=(o,p)=>{if(o instanceof ge){p==="fillStyle"?(r=o,s={r:0,g:0,b:0,a:255}):(i=o,a={r:0,g:0,b:0,a:255});return}if(typeof o!="string")throw new j(p,String(o));let f=Ke(o);p==="fillStyle"?(r=o,s=f):(i=o,a=f)},F={get canvas(){return e.canvas},get fillStyle(){return r},set fillStyle(o){d(o,"fillStyle")},get strokeStyle(){return i},set strokeStyle(o){d(o,"strokeStyle")},get globalAlpha(){return c},set globalAlpha(o){c=Lt(o)},get globalCompositeOperation(){return h},set globalCompositeOperation(o){if(o!=="source-over"&&o!=="copy")throw new j("globalCompositeOperation",o);h=o},get lineWidth(){return g},set lineWidth(o){g=Number.isFinite(o)&&o>0?o:1},get lineCap(){return b},set lineCap(o){if(o!=="butt"&&o!=="round"&&o!=="square")throw new j("lineCap",String(o));b=o},get font(){return m},set font(o){m=o},get textAlign(){return E},set textAlign(o){if(o!=="start"&&o!=="left"&&o!=="center"&&o!=="right"&&o!=="end")throw new j("textAlign",String(o));E=o},get textBaseline(){return H},set textBaseline(o){H=o},get imageSmoothingEnabled(){return O},set imageSmoothingEnabled(o){O=!!o},imageSmoothingQuality:"low",lineJoin:"miter",miterLimit:10,lineDashOffset:0,shadowBlur:0,shadowColor:"rgba(0, 0, 0, 0)",shadowOffsetX:0,shadowOffsetY:0,setGlyphAtlas(o){e.glyphAtlas=o},save(){n.push({transform:{...t},fillStyle:r,strokeStyle:i,fillStyleRaw:r,strokeStyleRaw:i,globalAlpha:c,globalCompositeOperation:h,lineWidth:g,lineCap:b,font:m,textAlign:E,textBaseline:H,clip:C?C.slice():null,imageSmoothingEnabled:O})},restore(){let o=n.pop();o&&(t=o.transform,r=o.fillStyleRaw,i=o.strokeStyleRaw,r instanceof ge?s={r:0,g:0,b:0,a:255}:s=Ke(r),i instanceof ge?a={r:0,g:0,b:0,a:255}:a=Ke(i),c=o.globalAlpha,h=o.globalCompositeOperation,g=o.lineWidth,b=o.lineCap,m=o.font,E=o.textAlign,H=o.textBaseline,C=o.clip,O=o.imageSmoothingEnabled)},beginPath(){R.length=0,G=null},closePath:v,moveTo:K,lineTo:z,rect(o,p,f,A){K(o,p),z(o+f,p),z(o+f,p+A),z(o,p+A),v()},quadraticCurveTo(o,p,f,A){let w=G?.points[G.points.length-1];if(!w){K(f,A);return}let S=Ge(t,w.x,w.y);Xn(S.x,S.y,o,p,f,A,16,(I,M)=>{G.points.push(T(I,M))})},bezierCurveTo(o,p,f,A,w,S){let I=G?.points[G.points.length-1];if(!I){K(w,S);return}let M=Ge(t,I.x,I.y);Jn(M.x,M.y,o,p,f,A,w,S,24,(_,B)=>{G.points.push(T(_,B))})},arc(o,p,f,A,w,S=!1){if(f<0)throw new j("arc","negative radius");let I=Mt(o,p,f,A,w,S);if(I.length===0)return;let M=I[0];G?G.points.push(T(M.x,M.y)):K(M.x,M.y);for(let _=1;_<I.length;_++)G.points.push(T(I[_].x,I[_].y))},ellipse(o,p,f,A,w,S,I,M=!1){if(f<0||A<0)throw new j("ellipse","negative radius");let _=Mt(0,0,1,S,I,M),B=Math.cos(w),X=Math.sin(w);for(let q=0;q<_.length;q++){let re=_[q].x*f,J=_[q].y*A,ae=o+re*B-J*X,ie=p+re*X+J*B;q===0&&!G?K(ae,ie):z(ae,ie)}},fill(o="nonzero"){Q(nt(R),r,s,o)},stroke(){ee(nt(R))},clip(o="nonzero"){let p=new Uint8Array(e.width*e.height),f=nt(R),A=rt(f,e.width,e.height);if(A)for(let w=A.minY;w<=A.maxY;w++)for(let S=A.minX;S<=A.maxX;S++)Dt(f,S+.5,w+.5,o)&&(p[w*e.width+S]=1);if(!C){C=p;return}for(let w=0;w<C.length;w++)C[w]=C[w]&&p[w]?1:0},fillRect(o,p,f,A){Q(L(o,p,f,A),r,s,"nonzero")},strokeRect(o,p,f,A){ee(L(o,p,f,A))},clearRect(o,p,f,A){let w=e.alpha?{r:0,g:0,b:0,a:0}:{r:0,g:0,b:0,a:255};Q(L(o,p,f,A),"#000000",w,"nonzero","copy")},fillText(o,p,f){$(String(o),p,f,r,s,!0)},strokeText(o,p,f){$(String(o),p,f,i,a,!1)},measureText(o){return{width:Ht(String(o),m,e.glyphAtlas)}},translate(o,p){t=Ne(t,{a:1,b:0,c:0,d:1,e:o,f:p})},rotate(o){let p=Math.cos(o),f=Math.sin(o);t=Ne(t,{a:p,b:f,c:-f,d:p,e:0,f:0})},scale(o,p){t=Ne(t,{a:o,b:0,c:0,d:p,e:0,f:0})},transform(o,p,f,A,w,S){t=Ne(t,{a:o,b:p,c:f,d:A,e:w,f:S})},setTransform(o,p,f,A,w,S){if(o&&typeof o=="object"){t={a:o.a,b:o.b,c:o.c,d:o.d,e:o.e,f:o.f};return}t={a:Number(o)||0,b:Number(p)||0,c:Number(f)||0,d:Number(A)||0,e:Number(w)||0,f:Number(S)||0}},resetTransform(){t={...tt}},getTransform(){return{...t}},createLinearGradient(o,p,f,A){return new ge("linear",o,p,f,A)},createRadialGradient(o,p,f,A,w,S){if(f<0||S<0)throw new j("createRadialGradient","negative radius");return new ge("radial",o,p,A,w,f,S)},createImageData(o,p){return typeof o=="object"?he(new Uint8ClampedArray(o.width*o.height*4),o.width,o.height):he(new Uint8ClampedArray(o*(p??0)*4),o,p??0)},getImageData(o,p,f,A){x();let w=o|0,S=p|0,I=f|0,M=A|0,_=new Uint8ClampedArray(I*M*4);for(let B=0;B<M;B++)for(let X=0;X<I;X++){let q=w+X,re=S+B,J=(B*I+X)*4;if(q<0||re<0||q>=e.width||re>=e.height)continue;let ae=(re*e.width+q)*4;_[J]=e.pixels[ae],_[J+1]=e.pixels[ae+1],_[J+2]=e.pixels[ae+2],_[J+3]=e.pixels[ae+3]}return he(_,I,M)},putImageData(o,p,f){x();let A=p|0,w=f|0,S=o.data;for(let I=0;I<o.height;I++)for(let M=0;M<o.width;M++){let _=A+M,B=w+I;if(_<0||B<0||_>=e.width||B>=e.height)continue;let X=(I*o.width+M)*4,q=(B*e.width+_)*4;e.pixels[q]=S[X],e.pixels[q+1]=S[X+1],e.pixels[q+2]=S[X+2],e.pixels[q+3]=e.alpha?S[X+3]:255}},drawImage(o,...p){let f=$n(o),A=0,w=0,S=f.width,I=f.height,M,_,B,X;if(p.length===2)M=p[0],_=p[1],B=S,X=I;else if(p.length===4)M=p[0],_=p[1],B=p[2],X=p[3];else if(p.length===8)A=p[0],w=p[1],S=p[2],I=p[3],M=p[4],_=p[5],B=p[6],X=p[7];else throw new j("drawImage","invalid argument count");l(),x();let q=[T(M,_),T(M+B,_),T(M+B,_+X),T(M,_+X)],re=Math.max(0,Math.floor(Math.min(...q.map(Y=>Y.x)))),J=Math.min(e.width-1,Math.ceil(Math.max(...q.map(Y=>Y.x)))),ae=Math.max(0,Math.floor(Math.min(...q.map(Y=>Y.y)))),ie=Math.min(e.height-1,Math.ceil(Math.max(...q.map(Y=>Y.y))));for(let Y=ae;Y<=ie;Y++)for(let te=re;te<=J;te++){let ve=Ge(t,te+.5,Y+.5),ye=(ve.x-M)/B,me=(ve.y-_)/X;if(ye<0||me<0||ye>=1||me>=1)continue;let u=Math.floor(A+ye*S),y=Math.floor(w+me*I);if(u<0||y<0||u>=f.width||y>=f.height)continue;let k=(y*f.width+u)*4;V(te,Y,{r:f.data[k],g:f.data[k+1],b:f.data[k+2],a:f.data[k+3]})}},setLineDash(o){if(o.length>0)throw new j("setLineDash","non-empty dash")},getLineDash(){return[]},createPattern(){throw new j("createPattern")}};function L(o,p,f,A){let w=T(o,p),S=T(o+f,p),I=T(o+f,p+A),M=T(o,p+A);return[{closed:!0,points:[w,S,I,M,w]}]}function $(o,p,f,A,w,S){l();let I=e.glyphAtlas,M=_t(m),_=M/I.cellHeight,B=Ht(o,m,I),X=p;E==="center"?X=p-B/2:(E==="right"||E==="end")&&(X=p-B);let q=f;H==="top"||H==="hanging"?q=f:H==="middle"?q=f-M/2:q=f-M;let re=X,J=(I.cellWidth+1)*_;for(let ae of o){let ie=I.glyphs[ae]??I.glyphs[ae.toUpperCase()];if(!ie){re+=J;continue}for(let Y=0;Y<I.cellHeight;Y++)for(let te=0;te<I.cellWidth;te++){if(ie[Y*I.cellWidth+te]===0)continue;if(!S){let ne=te===0||ie[Y*I.cellWidth+te-1]===0,ce=te===I.cellWidth-1||ie[Y*I.cellWidth+te+1]===0,fe=Y===0||ie[(Y-1)*I.cellWidth+te]===0,Ue=Y===I.cellHeight-1||ie[(Y+1)*I.cellWidth+te]===0;if(!ne&&!ce&&!fe&&!Ue)continue}let ve=re+te*_,ye=q+Y*_,me=re+(te+1)*_,u=q+(Y+1)*_,y=T(ve,ye),k=T(me,u),P=Math.max(0,Math.floor(Math.min(y.x,k.x))),D=Math.min(e.width-1,Math.ceil(Math.max(y.x,k.x))-1),N=Math.max(0,Math.floor(Math.min(y.y,k.y))),oe=Math.min(e.height-1,Math.ceil(Math.max(y.y,k.y))-1);for(let ne=N;ne<=oe;ne++)for(let ce=P;ce<=D;ce++)V(ce,ne,W(A,w,ce,ne))}re+=J}}return new Proxy(F,{get(o,p,f){if(Reflect.has(o,p))return Reflect.get(o,p,f);if(typeof p=="symbol")return;let A=String(p);if(!(A==="then"||A==="toJSON"))return(...w)=>{throw new j(A)}},set(o,p,f,A){if(p==="shadowBlur"&&f)throw new j("shadowBlur");if((p==="shadowOffsetX"||p==="shadowOffsetY")&&f)throw new j(String(p));if(p==="filter"&&f&&f!=="none")throw new j("filter",String(f));if(Reflect.has(o,p))return Reflect.set(o,p,f,A);throw new j(String(p))}})}function $n(e){if(e&&typeof e=="object"&&"__headlessImage"in e){let t=e;return{width:t.width,height:t.height,data:t.data}}if(e&&typeof e=="object"&&"data"in e&&"width"in e&&"height"in e){let t=e;if(t.data instanceof Uint8ClampedArray)return{width:t.width,height:t.height,data:t.data}}if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement){let t=we.get(e);if(!t)throw new j("drawImage","source canvas has no headless surface");return{width:t.width,height:t.height,data:t.pixels}}throw new j("drawImage","source must be ImageData, a headless canvas, or createImageFixture()")}function Bn(e,t,n){if(e.kind==="linear"){let a=e.x1-e.x0,c=e.y1-e.y0,h=a*a+c*c,g=h===0?0:((t-e.x0)*a+(n-e.y0)*c)/h;return e.colorAt(g)}let r=Math.hypot(t-e.x1,n-e.y1),i=e.r1-e.r0,s=i===0?0:(r-e.r0)/i;return e.colorAt(s)}function jn(e,t,n){return{r:Math.round(e.r+(t.r-e.r)*n),g:Math.round(e.g+(t.g-e.g)*n),b:Math.round(e.b+(t.b-e.b)*n),a:Math.round(e.a+(t.a-e.a)*n)}}function Ne(e,t){return{a:e.a*t.a+e.c*t.b,b:e.b*t.a+e.d*t.b,c:e.a*t.c+e.c*t.d,d:e.b*t.c+e.d*t.d,e:e.a*t.e+e.c*t.f+e.e,f:e.b*t.e+e.d*t.f+e.f}}function Ge(e,t,n){let r=e.a*e.d-e.b*e.c;if(r===0)return{x:t,y:n};let i=e.d/r,s=-e.b/r,a=-e.c/r,c=e.a/r,h=(e.c*e.f-e.d*e.e)/r,g=(e.b*e.e-e.a*e.f)/r;return{x:i*t+a*n+h,y:s*t+c*n+g}}function nt(e){return e.map(t=>({closed:t.closed,points:t.points.map(n=>({x:n.x,y:n.y}))}))}function rt(e,t,n,r=0){let i=1/0,s=1/0,a=-1/0,c=-1/0;for(let h of e)for(let g of h.points)i=Math.min(i,g.x),s=Math.min(s,g.y),a=Math.max(a,g.x),c=Math.max(c,g.y);return Number.isFinite(i)?{minX:Math.max(0,Math.floor(i-r)),minY:Math.max(0,Math.floor(s-r)),maxX:Math.min(t-1,Math.ceil(a+r)),maxY:Math.min(n-1,Math.ceil(c+r))}:null}function Dt(e,t,n,r){let i=0,s=0;for(let a of e){let c=a.points;if(!(c.length<2))for(let h=1;h<c.length;h++){let g=c[h-1],b=c[h],m=zn(g.x,g.y,b.x,b.y,t,n);i+=m,m!==0&&(s+=1)}}return r==="evenodd"?s%2===1:i!==0}function zn(e,t,n,r,i,s){if(t<=s==r<=s)return 0;let a=e+(s-t)/(r-t)*(n-e);return i<a?r>t?1:-1:0}function qn(e,t,n,r,i){for(let s of e){let a=s.points;for(let c=1;c<a.length;c++){let h=a[c-1],g=a[c];if(i==="round"){if(Yn(t,n,h.x,h.y,g.x,g.y)<=r)return!0;continue}let b=g.x-h.x,m=g.y-h.y,E=Math.hypot(b,m);if(E===0){if(Math.hypot(t-h.x,n-h.y)<=r)return!0;continue}let H=b/E,C=m/E,O=h.x,R=h.y,G=g.x,K=g.y;i==="square"&&(O-=H*r,R-=C*r,G+=H*r,K+=C*r);let z=G-O,v=K-R,T=z*z+v*v,l=((t-O)*z+(n-R)*v)/T;if(l<0||l>1)continue;let x=O+l*z,U=R+l*v;if(Math.hypot(t-x,n-U)<=r)return!0}}return!1}function Yn(e,t,n,r,i,s){let a=i-n,c=s-r,h=a*a+c*c;if(h===0)return Math.hypot(e-n,t-r);let g=((e-n)*a+(t-r)*c)/h;return g=g<0?0:g>1?1:g,Math.hypot(e-(n+g*a),t-(r+g*c))}function Xn(e,t,n,r,i,s,a,c){for(let h=1;h<=a;h++){let g=h/a,b=1-g;c(b*b*e+2*b*g*n+g*g*i,b*b*t+2*b*g*r+g*g*s)}}function Jn(e,t,n,r,i,s,a,c,h,g){for(let b=1;b<=h;b++){let m=b/h,E=1-m,H=E*E,C=m*m;g(H*E*e+3*H*m*n+3*E*C*i+C*m*a,H*E*t+3*H*m*r+3*E*C*s+C*m*c)}}function Mt(e,t,n,r,i,s){let a=r,c=i;!s&&c<a&&(c+=Math.PI*2),s&&a<c&&(a+=Math.PI*2);let h=c-a,g=Math.max(8,Math.min(360,Math.ceil(Math.abs(h)*Math.max(n,1)))),b=[];for(let m=0;m<=g;m++){let E=a+h*m/g;b.push({x:e+Math.cos(E)*n,y:t+Math.sin(E)*n})}return b}function Lt(e){return Number.isFinite(e)?e<0?0:e>1?1:e:1}function Ke(e){let t=e.trim().toLowerCase(),r=Gn[t]??t;if(r==="transparent")return{r:0,g:0,b:0,a:0};if(r[0]==="#"){let s=r.slice(1);if(s.length===3)return{r:parseInt(s[0]+s[0],16),g:parseInt(s[1]+s[1],16),b:parseInt(s[2]+s[2],16),a:255};if(s.length===6)return{r:parseInt(s.slice(0,2),16),g:parseInt(s.slice(2,4),16),b:parseInt(s.slice(4,6),16),a:255};if(s.length===8)return{r:parseInt(s.slice(0,2),16),g:parseInt(s.slice(2,4),16),b:parseInt(s.slice(4,6),16),a:parseInt(s.slice(6,8),16)}}let i=r.match(/^rgba?\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)(?:\s*,\s*([0-9.]+))?\s*\)$/);if(i)return{r:it(Number(i[1])),g:it(Number(i[2])),b:it(Number(i[3])),a:i[4]===void 0?255:Math.round(Lt(Number(i[4]))*255)};throw new j("fillStyle",e)}function it(e){return Number.isFinite(e)?e<0?0:e>255?255:Math.round(e):0}function _t(e){let t=e.match(/([0-9]+(?:\.[0-9]+)?)px/);return t?Number(t[1]):10}function Ht(e,t,n){let r=_t(t)/n.cellHeight;return e.length*(n.cellWidth+1)*r}function he(e,t,n){if(typeof ImageData=="function")try{return new ImageData(e,t,n)}catch{try{let r=new ImageData(t,n);return r.data.set(e),r}catch{}}return{data:e,width:t,height:n,colorSpace:"srgb"}}function Ut(){let n={" ":new Uint8Array(35)},r={0:[14,17,19,21,25,17,14],1:[4,12,4,4,4,4,14],2:[14,17,1,2,4,8,31],3:[14,17,1,6,1,17,14],4:[2,6,10,18,31,2,2],5:[31,16,30,1,1,17,14],6:[14,16,30,17,17,17,14],7:[31,1,2,4,8,8,8],8:[14,17,17,14,17,17,14],9:[14,17,17,15,1,1,14],A:[14,17,17,31,17,17,17],B:[30,17,17,30,17,17,30],C:[14,17,16,16,16,17,14],D:[30,17,17,17,17,17,30],E:[31,16,16,30,16,16,31],F:[31,16,16,30,16,16,16],G:[14,17,16,23,17,17,14],H:[17,17,17,31,17,17,17],I:[14,4,4,4,4,4,14],K:[17,18,20,24,20,18,17],L:[16,16,16,16,16,16,31],M:[17,27,21,21,17,17,17],N:[17,25,21,19,17,17,17],O:[14,17,17,17,17,17,14],P:[30,17,17,30,16,16,16],R:[30,17,17,30,20,18,17],S:[15,16,16,14,1,1,30],T:[31,4,4,4,4,4,4],U:[17,17,17,17,17,17,14],V:[17,17,17,17,17,10,4],W:[17,17,17,21,21,21,10],Y:[17,17,10,4,4,4,4],Z:[31,1,2,4,8,16,31],".":[0,0,0,0,0,0,4],"-":[0,0,0,31,0,0,0],"+":[0,4,4,31,4,4,0],"*":[0,21,14,31,14,21,0],"!":[4,4,4,4,4,0,4],"?":[14,17,1,2,4,0,4],"/":[1,2,2,4,8,8,16],":":[0,4,0,0,0,4,0],"\u2713":[1,1,2,2,20,8,0]};for(let[i,s]of Object.entries(r)){let a=new Uint8Array(35);for(let c=0;c<7;c++)for(let h=0;h<5;h++)a[c*5+h]=s[c]&1<<4-h?1:0;n[i]=a,n[i.toLowerCase()]=a}return{cellWidth:5,cellHeight:7,glyphs:n}}var Nt=new Uint32Array(256);for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;Nt[e]=t>>>0}function Qn(e){let t=4294967295;for(let n=0;n<e.length;n++)t=Nt[(t^e[n])&255]^t>>>8;return(t^4294967295)>>>0}function Zn(e){let t=1,n=0;for(let r=0;r<e.length;r++)t=(t+e[r])%65521,n=(n+t)%65521;return(n<<16|t)>>>0}function Ie(e){return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,e&255])}function st(e,t){let n=new Uint8Array(8+t.length+4);n.set(Ie(t.length),0),n[4]=e.charCodeAt(0),n[5]=e.charCodeAt(1),n[6]=e.charCodeAt(2),n[7]=e.charCodeAt(3),n.set(t,8);let r=n.subarray(4,8+t.length);return n.set(Ie(Qn(r)),8+t.length),n}function er(e){let t=[];for(let a=0;a<e.length;a+=65535){let c=e.subarray(a,Math.min(a+65535,e.length)),h=a+65535>=e.length,g=new Uint8Array(5+c.length);g[0]=h?1:0,g[1]=c.length&255,g[2]=c.length>>>8&255;let b=~c.length&65535;g[3]=b&255,g[4]=b>>>8&255,g.set(c,5),t.push(g)}t.length===0&&t.push(new Uint8Array([1,0,0,255,255]));let r=t.reduce((a,c)=>a+c.length,0),i=new Uint8Array(2+r+4);i[0]=120,i[1]=1;let s=2;for(let a of t)i.set(a,s),s+=a.length;return i.set(Ie(Zn(e)),s),i}function Ae(e,t,n){let r=e*4,i=new Uint8Array(t*(1+r));for(let m=0;m<t;m++){let E=m*(1+r);i[E]=0,i.set(n.subarray(m*r,(m+1)*r),E+1)}let s=new Uint8Array(13);s.set(Ie(e),0),s.set(Ie(t),4),s[8]=8,s[9]=6;let a=new Uint8Array([137,80,78,71,13,10,26,10]),c=[st("IHDR",s),st("IDAT",er(i)),st("IEND",new Uint8Array(0))],h=a.length+c.reduce((m,E)=>m+E.length,0),g=new Uint8Array(h);g.set(a,0);let b=a.length;for(let m of c)g.set(m,b),b+=m.length;return g}function Ee(e,t,n){let r=Ae(e,t,n),i="";for(let s=0;s<r.length;s++)i+=String.fromCharCode(r[s]);return`data:image/png;base64,${globalThis.btoa(i)}`}function ct(e){let t=[137,80,78,71,13,10,26,10];for(let g=0;g<8;g++)if(e[g]!==t[g])throw new j("decodePng","invalid signature");let n=0,r=0,i=[],s=8;for(;s<e.length;){let g=e[s]<<24|e[s+1]<<16|e[s+2]<<8|e[s+3],b=String.fromCharCode(e[s+4],e[s+5],e[s+6],e[s+7]),m=e.subarray(s+8,s+8+g);if(b==="IHDR"){if(n=m[0]<<24|m[1]<<16|m[2]<<8|m[3],r=m[4]<<24|m[5]<<16|m[6]<<8|m[7],m[8]!==8||m[9]!==6)throw new j("decodePng","only 8-bit RGBA is supported")}else if(b==="IDAT")for(let E=0;E<m.length;E++)i.push(m[E]);else if(b==="IEND")break;s+=12+g}let a=tr(new Uint8Array(i)),c=n*4,h=new Uint8ClampedArray(n*r*4);for(let g=0;g<r;g++){let b=g*(1+c);if(a[b]!==0)throw new j("decodePng",`unsupported scanline filter ${a[b]}`);h.set(a.subarray(b+1,b+1+c),g*c)}return he(h,n,r)}function tr(e){if(e.length<6)throw new j("decodePng","truncated zlib");let t=[],n=2;for(;n<e.length-4;){let a=e[n]&1;if((e[n]>>>1&3)!==0)throw new j("decodePng","only stored deflate blocks are supported");n+=1;let h=e[n]|e[n+1]<<8;if(n+=4,t.push(e.subarray(n,n+h)),n+=h,a)break}let r=t.reduce((a,c)=>a+c.length,0),i=new Uint8Array(r),s=0;for(let a of t)i.set(a,s),s+=a.length;return i}function Ve(e){let t=e.indexOf(","),n=t>=0?e.slice(t+1):e,r=globalThis.atob(n),i=new Uint8Array(r.length);for(let s=0;s<r.length;s++)i[s]=r.charCodeAt(s);return i}function Gt(){if(!Pt){Pt=!0;for(let e of["width","height"]){let t=Object.getOwnPropertyDescriptor(HTMLCanvasElement.prototype,e);if(!t?.set||!t.get)continue;let n=t.set;Object.defineProperty(HTMLCanvasElement.prototype,e,{configurable:!0,enumerable:t.enumerable,get:t.get,set(r){n.call(this,r);let i=we.get(this);i&&(i.resize(this.width,this.height,!0),i.onDeviceReset?.())}})}}}var Kt=()=>{let e=["ms","moz","webkit","o"];for(let t=0;t<e.length&&!window.requestAnimationFrame;++t)window.requestAnimationFrame=window[e[t]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[e[t]+"CancelAnimationFrame"]||window[e[t]+"CancelRequestAnimationFrame"]},ue=window.devicePixelRatio||1,Ce=/Headless/i.test(navigator.userAgent),wi=/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)||/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform);function Vt(){return Math.min(window.innerWidth,window.innerHeight)}var dt="data-cyberart-canvas",xe=class{constructor(t,n,r=1,i={}){this.width=t,this.height=n;let s=i.container,a=i.adoptFromDocument??!s,c=s?s.querySelector(`canvas[${dt}]`)??s.querySelector("canvas"):null;if(c)this.canvas=c,this.adopted=!0;else if(a){let h=document.getElementById("canvas")??document.querySelector("canvas");h?(this.canvas=h,this.adopted=!0):(this.canvas=document.createElement("canvas"),this.canvas.setAttribute("id","canvas"),this.adopted=!1)}else this.canvas=document.createElement("canvas"),this.adopted=!1;this.canvas.hasAttribute(dt)||this.canvas.setAttribute(dt,""),this.canvas.style.display="block",this.canvas.style.margin="auto",this.ctx=this.canvas.getContext("2d",{colorSpace:"display-p3",alpha:!1}),this.ctx.globalAlpha=r,this.ctx.imageSmoothingEnabled=!1,this.setSize(t,n)}setSize(t,n){this.width=t,this.height=n,this.canvas.width=t,this.canvas.height=n,this.canvas.style.width=`${t/ue}px`,this.canvas.style.height=`${n/ue}px`,this.imageData=this.ctx.createImageData(t,n),this.ctx.putImageData(this.imageData,0,0)}_blank(t=1){let n=t?Math.max(t,.03):1;this.ctx.fillStyle=`rgba(0,0,0,${n})`,this.ctx.fillRect(0,0,this.width,this.height)}clearAll(){this.ctx.save(),this.ctx.globalAlpha=1,this._blank(),this.ctx.restore()}};function Wt(e,t){let n=e/t,r,i;return n>1?(r=e,i=~~(e/n)):(i=t,r=~~(t*n)),{width:r,height:i,iWidth:1/r,iHeight:1/i,area:r*i,largeDim:Math.max(r,i),smallDim:Math.min(r,i),aspectRatio:n}}function $t(e,t=window.innerWidth,n=window.innerHeight){let r=Vt(),i,s;return n<t?e>1?t>=r*e?(i=r*e,s=r):(i=t,s=i/e):(i=r*e,s=r):e>1?(i=r,s=r/e):n<r/e?(s=n,i=s*e):(i=r,s=r/e),[i,s]}var lt=class{constructor(t=!1,n=!0){this.debugMode=t,this.actionMap={},this.listening=n,this.checkKeypress=this.checkKeypress.bind(this),this.registerAction=this.registerAction.bind(this),this.listening&&window.addEventListener("keydown",this.checkKeypress,!1)}checkKeypress({key:t}){this.debugMode&&console.log(`Pressed ${t}`),t in this.actionMap&&this.actionMap[t]()}inject(t){this.checkKeypress({key:t})}registerAction(t,n,r=!1){if(t.length!==1)throw new Error(`Only single-character actions may be registered. Cannot register: ${t}`);if(t in this.actionMap&&!r)throw new Error(`Action already exists for code: ${t}`);this.actionMap[t]=n}destroy(){this.listening&&window.removeEventListener("keydown",this.checkKeypress,!1),this.actionMap={}}},Bt=lt;var pt=class{constructor(t,n={}){this.x=-1;this.y=-1;this.isDown=!1;this.clicks=[];this.canvas=t,this.listening=n.listen!==!1,this.onPointerDown=this.onPointerDown.bind(this),this.onPointerMove=this.onPointerMove.bind(this),this.onPointerUp=this.onPointerUp.bind(this),this.listening&&(t.addEventListener("pointerdown",this.onPointerDown),t.addEventListener("pointermove",this.onPointerMove),t.addEventListener("pointerup",this.onPointerUp))}toCanvasCoords(t){let n=this.canvas.getBoundingClientRect();return{x:(t.clientX-n.left)*(this.canvas.width/n.width),y:(t.clientY-n.top)*(this.canvas.height/n.height)}}onPointerDown(t){let{x:n,y:r}=this.toCanvasCoords(t);this.x=n,this.y=r,this.isDown=!0,this.clicks.push({x:n,y:r})}onPointerMove(t){let{x:n,y:r}=this.toCanvasCoords(t);this.x=n,this.y=r}onPointerUp(t){let{x:n,y:r}=this.toCanvasCoords(t);this.x=n,this.y=r,this.isDown=!1}hasClick(){return this.clicks.length>0}consumeClick(){return this.clicks.shift()??null}inject(t,n,r){this.x=n,this.y=r,t==="down"?(this.isDown=!0,this.clicks.push({x:n,y:r})):t==="up"&&(this.isDown=!1)}destroy(){this.listening&&(this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp))}},jt=pt;function We(){return{now:()=>performance.now()}}function zt(e=0){let t=e;return{now:()=>t,set(n){t=n},advance(n){t+=n}}}var qt=(e,t,n,r)=>({now:e,startTime:t,elapsedSinceStart:e-t,deltaSinceLastUpdate:n===null?0:e-n,deltaSinceLastRender:r===null?0:e-r}),$e=class{constructor(t,n,r,i,s,a={}){this.startTime=0;this.lastUpdateAt=null;this.lastRenderAt=null;this.clockOffsetMs=0;this.pauseStartedAt=null;this.renderAnimation=this.renderAnimation.bind(this),this.dimensionContext=Wt(t,n),this.R=r,this.gameManager=a.gameManager,this.hostChannel=a.hostChannel,this.clock=a.clock??We(),this.canvas=new xe(this.dimensionContext.width,this.dimensionContext.height,1,a.canvasMount),this.drawingContext=this.canvas.ctx,this.keyboardManager=new Bt(!1,a.captureKeyboard??!0),this.pointerManager=new jt(this.canvas.canvas,{listen:a.listenToPointer!==!1}),this.animationCart=s;let c=a.customState;this.featureState=s.getDefaultFeatureState?.(this.R,this.dimensionContext,i,this.keyboardManager,c,this.pointerManager,this.gameManager,this.hostChannel),this.cartState=s.getDefaultState(this.R,this.dimensionContext,i,this.keyboardManager,c,this.pointerManager,this.gameManager,this.featureState,this.hostChannel),this.startTime=this.clock.now(),this.canvas.clearAll()}captureFramebuffer(){let t=this.canvas.imageData,n=new ImageData(t.width,t.height);return n.data.set(t.data),n}restoreFramebuffer(t){let n=this.canvas.imageData;return n.width!==t.width||n.height!==t.height||n.data.length!==t.data.length?!1:(n.data.set(t.data),this.drawingContext.putImageData(n,0,0),!0)}setPaused(t){let n=this.clock.now();if(t){this.pauseStartedAt===null&&(this.pauseStartedAt=n);return}this.pauseStartedAt!==null&&(this.clockOffsetMs+=n-this.pauseStartedAt,this.pauseStartedAt=null)}resolveNow(t){let n=this.pauseStartedAt!==null?t-this.pauseStartedAt:0;return t-this.clockOffsetMs-n}getElapsedSinceStart(t=this.clock.now()){return Math.max(0,this.resolveNow(t)-this.startTime)}restoreClock(t,n){this.pauseStartedAt=null,this.lastUpdateAt=null,this.lastRenderAt=null;let r=Math.max(0,t);if(typeof n=="number"&&Number.isFinite(n)){this.startTime=n,this.clockOffsetMs=this.clock.now()-n-r;return}this.clockOffsetMs=0,this.startTime=this.clock.now()-r}getRandomState(){return this.R.getState()}injectKey(t){this.keyboardManager.inject(t)}injectPointer(t,n,r){this.pointerManager.inject(t,n,r)}async updateAnimationState(t,n,r=this.clock.now()){let i=this.resolveNow(r),s=qt(i,this.startTime,this.lastUpdateAt,this.lastRenderAt);this.cartState=this.animationCart.update(this.R,t,n,this.dimensionContext,this.cartState,this.keyboardManager,this.pointerManager,this.gameManager,s,this.featureState,this.hostChannel),this.lastUpdateAt=i}async renderAnimation(t,n,r=this.clock.now()){let i=this.resolveNow(r),s=qt(i,this.startTime,this.lastUpdateAt,this.lastRenderAt);this.animationCart.render(this.R,t,n,this.dimensionContext,this.cartState,this.drawingContext,this.canvas.imageData,this.pointerManager,this.gameManager,s,this.featureState,this.hostChannel),this.lastRenderAt=i}getCanvas(){return this.canvas.canvas}getDrawDetails(){return[this.canvas.canvas,0,0,this.dimensionContext.width,this.dimensionContext.height]}teardown(){try{this.animationCart.teardown?.(this.cartState,this.featureState)}catch(t){console.error("Error during cart teardown",t)}this.keyboardManager.destroy(),this.pointerManager.destroy()}};var Be=class extends xe{constructor(t,n,r=1,i=!0,s={}){if(super(t,n,r,s),this.adopted)return;let a=s.container;if(a){this.canvas.parentNode!==a&&a.appendChild(this.canvas);return}if(i){let c=document.getElementById("canvas");c&&c!==this.canvas&&c.parentNode===document.body&&document.body.removeChild(c),document.body.appendChild(this.canvas)}}};function Yt(e){let t=parseInt(e.substring(0,8),16),n=parseInt(e.substring(8,8),16),r=parseInt(e.substring(16,8),16),i=parseInt(e.substring(24,8),16);return{next:()=>{t|=0,n|=0,r|=0,i|=0;let a=(t+n|0)+i|0;return i=i+1|0,t=n^n>>>9,n=r+(r<<3)|0,r=r<<21|r>>>11,r=r+a|0,(a>>>0)/4294967296},getRegs:()=>({a:t,b:n,c:r,d:i}),setRegs:a=>{t=a.a,n=a.b,r=a.c,i=a.d}}}var je=class{constructor(t){this.seed=t.hash,this.useA=!1,this.genA=Yt(t.hash.substring(2,32)),this.genB=Yt(t.hash.substring(34,32)),this.prngA=this.genA.next,this.prngB=this.genB.next;for(let n=0;n<1e6;n+=2)this.prngA(),this.prngB()}getState(){let t=this.genA.getRegs(),n=this.genB.getRegs();return{seed:this.seed,useA:this.useA,prngA:{a:t.a,b:t.b,c:t.c,d:t.d},prngB:{a:n.a,b:n.b,c:n.c,d:n.d}}}setState(t){if(t.seed!==this.seed)throw new Error(`Random.setState: seed ${t.seed} does not match ${this.seed}`);this.useA=t.useA,this.genA.setRegs(t.prngA),this.genB.setRegs(t.prngB)}r_zero_one(){return this.useA=!this.useA,this.useA?this.prngA():this.prngB()}dec(t,n){return t===void 0?this.r_zero_one():n===void 0?t*this.r_zero_one():t+(n-t)*this.r_zero_one()}int(t,n){return n===void 0&&(n=t,t=0),Math.floor(this.dec(t,n))}bool(t=.5){return this.r_zero_one()<t}sign(){return this.bool()?1:-1}choose(t){return t[this.int(t.length)]}};var Qt="bafybeicjwcq5lxxtfnyj4p2ugcr7ctyb5wl62cbcechj6tsabdq5whcs7u",Xt="https://ipfs.io/ipfs/";function nr(e){return e.endsWith("/")?e:`${e}/`}var Pe=null;function rr(e){return[...Array(e)].map(()=>Math.floor(Math.random()*16).toString(16)).join("")}function ir(e){return e&&e.length>0?e:[{cid:Qt}]}function sr(e){return e.startsWith("0x")?e:`0x${e}`}var Zt=/^(0[xX])?[0-9a-fA-F]{64}$/;function ar(e){let t="",n=2166136261,r=522970236;for(let i=0;t.length<64;i++){for(let s=0;s<e.length;s++)n^=e.charCodeAt(s)+i,n=Math.imul(n,16777619),r^=e.charCodeAt(s)+i*17,r=Math.imul(r,16777619);t+=(n>>>0).toString(16).padStart(8,"0"),t+=(r>>>0).toString(16).padStart(8,"0")}return`0x${t.slice(0,64)}`}function Jt(e){let t=typeof e=="number"?String(e):e;return Zt.test(t)?`0x${(t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t).toLowerCase()}`:ar(t)}function en(e,t){if(typeof e=="number"||t==="deterministic")return Jt(e);let n=String(e);return Zt.test(n)?Jt(n):n.startsWith("0x")||n.startsWith("0X")?n:`0x${n}`}function or(e){if(!e&&typeof tokenData<"u"&&tokenData?.hash)return{hash:tokenData.hash,tokenId:String(tokenData.tokenId),externalAssetDependencies:ir(tokenData.externalAssetDependencies),preferredIPFSGateway:nr(tokenData.preferredIPFSGateway||Xt),preferredArweaveGateway:tokenData.preferredArweaveGateway};let t=typeof window<"u"?new URLSearchParams(window.location.search):new URLSearchParams;return{hash:e?sr(e):t.get("hash")||`0x${rr(64)}`,tokenId:"18009999",externalAssetDependencies:[{cid:Qt}],preferredIPFSGateway:Xt}}function ht(e){let t=e?.useCache!==!1;if(t&&Pe&&!e?.hash)return Pe;let n=or(e?.hash);return t?Pe=n:Pe||(Pe=n),n}function tn(e){return new Array(32).fill(null).map((t,n)=>parseInt(e.hash.slice(2+n*2,4+n*2),16))}async function ft(){let e=await import("tone");if(typeof e.start=="function")return e;let t=e.default;return t&&typeof t.start=="function"?t:e}var sn={id:"tone",async load(){await Promise.resolve().then(()=>(rn(),dr))},async unlock(){await sn.load(),await(await ft()).start()},async resumeIfSuspended(){let e=await ft();e.context.state==="suspended"&&await e.context.resume()},async suspendIfRunning(){let t=(await ft()).context.rawContext;"suspend"in t&&t.state==="running"&&await t.suspend()}},an={tone:sn};function gt(e){if(!e)return[];let t=Array.isArray(e)?e:[e],n=[];for(let r of t){if(!(r in an)){console.warn(`Unknown audio library "${r}"`);continue}let i=r;n.includes(i)||n.push(i)}return n}function bt(e){return e.map(t=>an[t])}var qe="$cyberartTa",de=class extends Error{constructor(t){super(t),this.name="IncompatibleCartStateError"}},yt={Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array};function lr(e){for(let t of Object.keys(yt))if(e instanceof yt[t])return t}function cn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function le(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function vt(e){return le(e)?typeof e[qe]=="string"&&Array.isArray(e.d):!1}function pr(e){return e==null?!1:typeof e=="function"?!0:!(typeof e!="object"||Array.isArray(e)||cn(e)||le(e))}var hr=new Set(["audioContextStarted","midiSynths","keepRatioPrimed","audioInitStarted","musicSeekApplied"]);function on(e){return e===null?"null":vt(e)?String(e[qe]):Array.isArray(e)?"array":le(e)?"object":typeof e}function mr(e,t){return e===t||e==="null"||t==="null"}function un(e){return e.trim().toLowerCase().replace(/^0x/,"")}function dn(e,t,n,r){if(!(!n&&!r)&&un(e)!==un(t))throw new de(`Generative cart state is for seed "${t}", but the live token is "${e}"`)}function Re(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function ln(e,t){let n=e.dimensions;if(n&&Re(n.width)&&Re(n.height))return n;if(t&&Re(t.width)&&Re(t.height))return{width:t.width,height:t.height};if(le(e.state)){let r=e.state.containerWidth,i=e.state.containerHeight;if(Re(r)&&Re(i))return{width:r,height:i}}return null}function Se(e,t=new WeakSet){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)?e:null;if(!(typeof e=="function"||typeof e>"u"||typeof e=="bigint"||typeof e=="symbol")){if(cn(e)){let n=lr(e);return n?{[qe]:n,d:Array.from(e)}:void 0}if(typeof e=="object"&&!t.has(e)){t.add(e);try{if(Array.isArray(e)){let i=[],s=0;for(let a of e){let c=Se(a,t);c!==void 0&&(i.push(c),s++)}return e.length>0&&s===0?void 0:i}if(!le(e)||pr(e))return;let n=Object.keys(e),r={};for(let i of n){if(hr.has(i))continue;let s=Se(e[i],t);s!==void 0&&(r[i]=s)}return n.length>0&&Object.keys(r).length===0?void 0:r}finally{t.delete(e)}}}}function Me(e){if(vt(e)){let t=yt[e[qe]];return t?new t(e.d.map(n=>Number(n))):e}if(Array.isArray(e))return e.map(t=>Me(t));if(le(e)){let t={};for(let n of Object.keys(e))t[n]=Me(e[n]);return t}return e}function wt(e,t,n,r,i=!0){if(i&&n&&r&&n!==r)throw new de(`Cart state is for "${r}", but the live cart is "${n}"`);if(!le(t)){if(i)throw new de("Cart state snapshot is empty");return}let s=Object.keys(t);if(s.length===0){if(i)throw new de("Cart state snapshot is empty");return}let a=Se(e);if(!le(a)||Object.keys(a).length===0){if(i)throw new de("Live cart has no serializable state");return}let c=s.filter(h=>h in a);if(c.length===0){if(i)throw new de("Cart state snapshot does not overlap the live cart shape");return}for(let h of c){let g=on(a[h]),b=on(t[h]);if(!mr(g,b))throw new de(`Cart state field "${h}" has type ${b}, live cart expects ${g}`);if(g==="object"){let m=t[h],E=e[h];le(m)&&!vt(m)&&wt(E,m,void 0,void 0,!1)}}}function pn(e,t){if(!le(e)||!le(t))return;let n=Se(e);if(le(n))for(let r of Object.keys(t))r in n&&(e[r]=Me(t[r]))}function hn(e){let t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")throw new de("Cart state bundle is not an object");if(t.version!==1)throw new de(`Unsupported cart state version ${String(t.version)}`);if(typeof t.seed!="string"||typeof t.framesElapsed!="number")throw new de("Cart state bundle is missing seed or framesElapsed");return t}var He="cyberart.asset.ready",Fe="cyberart.asset.failed";function be(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function mn(e){return{type:e.status==="ready"?He:Fe,kind:"state",payload:e.detail===void 0?{id:e.id}:{id:e.id,detail:e.detail}}}function gr(e){if(!e||typeof e!="object")return 0;let t=e;return typeof t.startTime=="number"&&typeof t.lastSimulationUpdateAt=="number"?Math.max(0,t.lastSimulationUpdateAt-t.startTime):0}function br(e,t){if(typeof window.resizeTo!="function")return!1;try{if(window.top!==window)return!1}catch{return!1}let n=Math.max(1,Math.round(e)),r=Math.max(1,Math.round(t)),i=Math.max(0,window.outerWidth-window.innerWidth),s=Math.max(0,window.outerHeight-window.innerHeight);try{window.resizeTo(n+i,r+s)}catch{return!1}return Math.abs(window.innerWidth-n)<=8&&Math.abs(window.innerHeight-r)<=8}var yr=[[0,0],[16,9],[9,16],[4,3],[3,4],[2,1],[1,2],[3,1],[1,3],[1,1]],Et=yr[0],vr=Et[0]/Et[1],At=30,wr=120,Ar=3840/2160,Er=2160/3840,Ye=class{constructor(t=At,n=!1,r=window.innerWidth,i=window.innerHeight,s=!0,a,c={}){this.framesElapsed=0;this.frameRate=At;this._paused=!1;this.savedToken=!1;this.prepared=!1;this.loopRunning=!1;this.fallbackAudio=[];this.audioLibrariesInternal=[];this.virtualClock=null;this.scriptedActions=[];this.initialScriptedActions=[];this.appliedActions=[];this.consumedActionIndexes=new Set;this.outboundEvents=[];this.consecutiveErrorCount=0;this.lastErrorLogAt=0;this.reinitStayPaused=!1;this.reinitPending=!1;this.lastExportedFramebuffer=null;this.pinnedOutput=null;this.pinViewportAtImport=null;this.importing=!1;this.drawLoop=this.drawLoop.bind(this),this.loadCart=this.loadCart.bind(this),this.prepareCart=this.prepareCart.bind(this),this.beginPlayback=this.beginPlayback.bind(this),this.reinit=this.reinit.bind(this),this.tuneFramerate=this.tuneFramerate.bind(this),this.container=c.container,this.seed=c.seed,this.captureKeyboard=c.captureKeyboard??!0,this.customState=c.customState,this.hostChannel=c.hostChannel,this.fallbackAudio=gt(c.audio),this.audioLibrariesInternal=this.fallbackAudio;let h=c.deterministic;this.deterministic=!!h;let g=h&&typeof h=="object"?h:{};if(this.deterministic){if(c.clock){let b=c.clock;if(typeof b.advance!="function")throw new Error("deterministic mode requires a virtual clock with advance()");this.virtualClock=b,this.clock=b}else this.virtualClock=zt(g.origin??0),this.clock=this.virtualClock;this.initialScriptedActions=be(g.actions??[]),this.scriptedActions=be(this.initialScriptedActions)}else this.clock=c.clock??We();this.isBodyCanvas=this.container?!1:s,this.autoMode=n,this.aspectRatio=vr,this.selectedAsp=Et,this.isFullscreen=!!document.fullscreenElement,this.updateFrameRate(t),this.tempUnpause=!1,this.synchronous=Ce,this.containerWidth=r,this.containerHeight=i,this.gameManager=a,this.init(!0)}setGameManager(t){this.gameManager=t}reinit(t){if(!this.importing){if(this.shouldKeepPinnedOutput()){this.fitPinnedCanvas();return}this.reinitPending||(this.reinitStayPaused=this._paused,this.reinitPending=!0),this.paused=!0,clearTimeout(this.reinitTimeout),this.reinitTimeout=setTimeout(()=>{if(this.importing){this.paused=this.reinitStayPaused,this.reinitPending=!1;return}this.updateInProgress?this.reinit(t):(this.requestedAnimationFrame&&cancelAnimationFrame(this.requestedAnimationFrame),this.clearPinnedOutput(),this.init(),this.reloadCart(),this.paused=this.reinitStayPaused,this.reinitPending=!1)},150)}}initSeed(){this.tokenData=this.seed?ht({hash:this.seed,useCache:!1}):ht(),this.rawParams=tn(this.tokenData),this.mintNo=parseInt(this.tokenData.tokenId)%1e6,console.log("token",this.mintNo,this.tokenData.hash)}init(t=!1){t&&this.initSeed(),this.pureAspectUpdate(this.selectedAsp);let n=this.aspectRatio,[r,i]=$t(n,this.containerWidth,this.containerHeight);r*=ue,i*=ue,this.width=~~r,this.height=~~i,this.atCenterX=this.width/2,this.atCenterY=this.height/2,this.mainCanvas?this.mainCanvas.setSize(this.width,this.height):this.mainCanvas=new Be(this.width,this.height,1,this.isBodyCanvas,this.canvasMountOptions())}loadCart(t){this.prepareCart(t)&&this.beginPlayback()}prepareCart(t){if(this.prepared)return!0;try{let n=~~(this.width/1),r=~~(this.height/this.width*n),i=new je(this.tokenData),s=new $e(n,r,i,this.rawParams,t,{gameManager:this.gameManager,canvasMount:this.canvasMountOptions(),customState:this.customState,captureKeyboard:this.deterministic?!1:this.captureKeyboard,hostChannel:this.hostChannel,clock:this.clock,listenToPointer:!this.deterministic});return this.animation=s,this.animationCart=t,this.paused=!1,this.framesElapsed=0,this.outboundEvents=[],this.scriptedActions=be(this.initialScriptedActions),this.appliedActions=[],this.consumedActionIndexes=new Set,this.outboundUnsubscribe?.(),this.outboundUnsubscribe=void 0,this.deterministic&&this.hostChannel&&(this.outboundUnsubscribe=this.hostChannel.onEvent(a=>{this.outboundEvents.push(a)})),this.R=i,this.applyCartFrameRate(t,s),this.resolveAudioLibraries(t),this.prepared=!0,!0}catch(n){return console.error(n),!1}}applyCartFrameRate(t,n){let r=t.metadata,i=r?.frameRate??At,s=n.cartState?.visualMode??n.featureState?.visualMode,a=s&&r?.frameRateByVisualMode?r.frameRateByVisualMode[s]:void 0;this.updateFrameRate(typeof a=="number"&&a>0?a:i)}get audioLibraries(){return this.audioLibrariesInternal}get needsAudio(){return this.audioLibrariesInternal.length>0}resolveAudioLibraries(t){this.audioLibrariesInternal=gt(t.metadata?.audio)}async unlockAudio(){if(this.audioLibrariesInternal.length===0)return;let t=bt(this.audioLibrariesInternal);if(Ce){for(let n of t)await n.load();return}for(let n of t)await n.unlock()}async resumeAudioLibraries(){if(!(this.paused||Ce))for(let t of bt(this.audioLibrariesInternal))try{await t.resumeIfSuspended()}catch(n){console.error(`Failed to resume audio library "${t.id}" after reload`,n)}}beginPlayback(){!this.prepared||this.loopRunning||(this.prepared=!1,this.loopRunning=!0,this.consecutiveErrorCount=0,!this.deterministic&&(this.requestedAnimationFrame=requestAnimationFrame(this.drawLoop)))}get isPrepared(){return this.prepared}get isLoopRunning(){return this.loopRunning}get isDeterministic(){return this.deterministic}getClock(){return{now:this.clock.now(),framesElapsed:this.framesElapsed,frameRate:this.frameRate}}getRandomState(){return this.requirePreparedAnimation().getRandomState()}schedule(t){this.scriptedActions.push(be(t))}async getReplayMetadata(){let t=await this.exportState();return{seed:this.tokenData.hash,clock:this.getClock(),rng:this.getRandomState(),actions:be(this.scriptedActions),applied:be(this.appliedActions),events:be(this.outboundEvents),state:t.state}}async step(t=1){if(!this.deterministic)throw new Error("step() requires createRuntime({ deterministic: true })");this.requirePreparedAnimation(),this.prepared&&!this.loopRunning&&this.beginPlayback(),this.paused=!1;let n=Math.max(0,Math.floor(t));for(let r=0;r<n&&this.animation;r++){let i=this.framesElapsed;if(this.applyScheduledActions(i),await this.processFrame(this.clock.now(),{ignorePause:!0,scheduleNext:!1}),this.framesElapsed===i||(this.virtualClock?.advance(this.targetDrawTime),!this.loopRunning))break}}async advance(t){let n=Math.max(0,Math.round(t/this.targetDrawTime));await this.step(n)}applyScheduledActions(t){let n=this.animation;n&&this.scriptedActions.forEach((r,i)=>{r.atFrame===t&&(this.consumedActionIndexes.has(i)||(this.consumedActionIndexes.add(i),r.type==="pointer"?n.injectPointer(r.pointer.kind,r.pointer.x,r.pointer.y):r.type==="key"?n.injectKey(r.key):r.type==="event"?this.hostChannel?.dispatch(r.event):r.type==="asset"&&this.hostChannel?.dispatch(mn(r)),this.appliedActions.push({frame:t,action:r})))})}get paused(){return this._paused}set paused(t){this._paused!==t&&(this._paused=t,this.animation?.setPaused(t))}async waitUntilUpdateIdle(){for(;this.updateInProgress;)await new Promise(t=>{this.deterministic?queueMicrotask(t):typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>t()):setTimeout(t,0)})}requirePreparedAnimation(){if(!this.animation)throw new Error("No prepared cart");return this.animation}async exportState(){let t=this.requirePreparedAnimation(),n=this._paused;this.paused=!0,await this.waitUntilUpdateIdle();try{this.lastExportedFramebuffer=t.captureFramebuffer();let r=t.getCanvas();return{version:1,cartId:this.animationCart?.metadata?.id,generative:this.animationCart?.metadata?.generative,seed:this.tokenData.hash,framesElapsed:this.framesElapsed,elapsedSinceStart:t.getElapsedSinceStart(),dimensions:{width:r.width,height:r.height,cssWidth:this.containerWidth,cssHeight:this.containerHeight,dpr:ue},state:Se(t.cartState)}}finally{this.paused=n}}async exportStateJSON(){return JSON.stringify(await this.exportState())}peekExportedFramebuffer(){return this.lastExportedFramebuffer}peekSeed(){return this.tokenData?.hash}isGenerative(){return this.animationCart?.metadata?.generative===!0}async importState(t,n){let r=this.requirePreparedAnimation(),i=hn(t),s=this._paused,a=this.loopRunning;this.paused=!0,await this.waitUntilUpdateIdle(),wt(r.cartState,i.state,this.animationCart?.metadata?.id,i.cartId),dn(this.tokenData.hash,i.seed,this.animationCart?.metadata?.generative,i.generative),clearTimeout(this.reinitTimeout),this.reinitPending=!1,this.importing=!0;let c=ln(i,n?.framebuffer??this.lastExportedFramebuffer);if(c){this.pinOutputSize(c);let b=c.cssWidth??c.width/ue,m=c.cssHeight??c.height/ue;br(b,m),this.syncContainerFromDom(),this.pinViewportAtImport={w:this.containerWidth,h:this.containerHeight}}let h=this.customState,g=!1;try{if(this.customState=Me(i.state),this.unloadCart(),!this.prepareCart(this.animationCart))throw new Error("Failed to prepare cart while loading state");this.animation.cartState!==this.customState&&pn(this.animation.cartState,i.state),this.framesElapsed=i.framesElapsed;let b=this.animation,m=b.cartState,E=typeof i.elapsedSinceStart=="number"?i.elapsedSinceStart:gr(m);b.restoreClock(E,typeof m?.startTime=="number"?m.startTime:void 0),s&&b.setPaused(!0);let H=n?.framebuffer??this.lastExportedFramebuffer;H&&b.restoreFramebuffer(H)?m.keepRatioPrimed=!0:await b.renderAnimation(this.framesElapsed,this.rawParams),this.fitPinnedCanvas(),g=!0}catch(b){throw this.clearPinnedOutput(),this.customState=h,this.paused=s,this.animationCart&&(this.syncContainerFromDom(),this.init(),this.reloadCart()),b}finally{this.importing=!1,g&&(this.customState=h,this.paused=s,a&&this.beginPlayback())}}unloadCart(){this.loopRunning=!1,this.requestedAnimationFrame&&cancelAnimationFrame(this.requestedAnimationFrame),this.drawLoopTimeout&&clearTimeout(this.drawLoopTimeout),this.animation?.teardown(),this.animation=void 0,this.prepared=!1,this.audioLibrariesInternal=this.fallbackAudio,this.mainCanvas?.clearAll()}reloadCart(t=!1){let n=this.animationCart;if(!n)return;this.pinnedOutput&&(this.clearPinnedOutput(),this.syncContainerFromDom(),this.init());let r=this.reinitPending?this.reinitStayPaused:this._paused;this.unloadCart(),t&&this.initSeed(),this.loadCart(n),this.paused=r,!this.paused&&!Ce&&this.resumeAudioLibraries()}getFrameRate(){return this.frameRate}updateFrameRate(t){if(this.frameRate=t,t>=1)this.targetDrawTime=1e3/t;else{let r=1/(2-t);this.targetDrawTime=1e3/r}this.drawTime=this.targetDrawTime}canvasMountOptions(){return{container:this.container,adoptFromDocument:!this.container}}syncContainerFromDom(){if(this.container){this.containerWidth=this.container.clientWidth||this.containerWidth,this.containerHeight=this.container.clientHeight||this.containerHeight;return}this.containerWidth=window.innerWidth,this.containerHeight=window.innerHeight}pinOutputSize(t){this.pinnedOutput=t,this.width=~~t.width,this.height=~~t.height,this.atCenterX=this.width/2,this.atCenterY=this.height/2,this.aspectRatio=this.width/this.height,this.mainCanvas&&this.mainCanvas.setSize(this.width,this.height)}shouldKeepPinnedOutput(){return this.pinnedOutput?(this.syncContainerFromDom(),this.viewportMatches(this.pinnedCssSize())?!0:!!(this.pinViewportAtImport&&this.viewportMatches(this.pinViewportAtImport))):!1}pinnedCssSize(){let t=this.pinnedOutput;return{w:t.cssWidth??t.width/ue,h:t.cssHeight??t.height/ue}}viewportMatches(t){return Math.abs(this.containerWidth-t.w)<8&&Math.abs(this.containerHeight-t.h)<8}fitPinnedCanvas(){let t=this.pinnedOutput,n=this.canvas;if(!t||!n)return;this.container&&!this.container.style.position&&(this.container.style.position="relative");let r=this.containerWidth||window.innerWidth,i=this.containerHeight||window.innerHeight,s=t.width/ue,a=t.height/ue;if(s<1||a<1||r<1||i<1)return;let c=Math.min(r/s,i/a),h=s*c,g=a*c;n.style.position="absolute",n.style.left="50%",n.style.top="50%",n.style.transform="translate(-50%, -50%)",n.style.margin="0",n.style.width=`${h}px`,n.style.height=`${g}px`,n.style.imageRendering=Math.abs(c-1)<.01?"auto":"pixelated"}clearPinnedOutput(){let t=this.canvas;this.pinnedOutput=null,this.pinViewportAtImport=null,t&&(t.style.position="",t.style.left="",t.style.top="",t.style.transform="",t.style.imageRendering="",t.style.width="",t.style.height="",t.style.margin="auto")}get canvas(){return this.animation?.getCanvas()??this.mainCanvas?.canvas}destroy(){this.outboundUnsubscribe?.(),this.outboundUnsubscribe=void 0,this.clearPinnedOutput(),this.unloadCart(),clearTimeout(this.reinitTimeout),this.mainCanvas&&!this.mainCanvas.adopted&&this.mainCanvas.canvas.remove()}drawIt(){}tuneFramerate(t){let n=this.lastCall||t;this.lastCall=t,this.drawTime=Math.max(0,this.drawTime+this.targetDrawTime-this.lastCall+n)}async processFrame(t,n={}){let r=n.ignorePause===!0,i=n.scheduleNext!==!1;if(!this.loopRunning&&!r)return;let s=!1,a,c="update";try{if(r||!this.paused||this.tempUnpause){if(!Ce&&!r&&this.tuneFramerate(t),!this.animation)return;if(c="update",this.updateInProgress=!0,await this.animation.updateAnimationState(this.framesElapsed,this.rawParams,t),this.updateInProgress=!1,c="render",await this.animation.renderAnimation(this.framesElapsed,this.rawParams,t),this.autoMode&&this.animation.cartState.saveToken&&!this.savedToken&&!new URLSearchParams(window.location.search).get("hash")){let b=localStorage.getItem("goodones"),m=JSON.stringify(b?[...JSON.parse(b),this.tokenData.hash]:[this.tokenData.hash]);localStorage.setItem("goodones",m),this.savedToken=!0,localStorage.setItem(this.tokenData.hash,this.mainCanvas.canvas.toDataURL("image/png")),window.location.reload(),this.loopRunning=!1;return}this.framesElapsed++,this.tempUnpause&&(this.tempUnpause=!1)}c="draw",this.drawIt()}catch(h){s=!0,a=h,this.handleFrameError(h,c)}finally{this.updateInProgress=!1}s?(this.consecutiveErrorCount++,this.consecutiveErrorCount>=wr&&(this.loopRunning=!1,this.onError?.(a,{phase:c,consecutive:this.consecutiveErrorCount,stopped:!0}))):this.consecutiveErrorCount=0,!(!this.loopRunning||!i)&&(this.drawLoopTimeout=setTimeout(()=>{this.requestedAnimationFrame=requestAnimationFrame(this.drawLoop)},this.drawTime))}async drawLoop(t){await this.processFrame(t,{scheduleNext:!0})}handleFrameError(t,n){let r=performance.now();r-this.lastErrorLogAt>=1e3&&(this.lastErrorLogAt=r,console.error(`Animation ${n} error:`,t)),this.consecutiveErrorCount===0&&this.onError?.(t,{phase:n,consecutive:1,stopped:!1})}pureAspectUpdate(t){if(t[0]===0&&t[1]===0){let r=this.containerWidth||window.innerWidth,i=this.containerHeight||window.innerHeight,s=r/i;this.aspectRatio=Math.min(Ar,Math.max(Er,s))}else this.aspectRatio=t[0]/t[1]}};var Cr="HostChannel has been destroyed",Xe=class{constructor(){this.inbound=[];this.listeners=[];this.closed=!1}dispatch(t){this.requireOpen(),this.inbound.push(t),this.inbound.length>32&&this.inbound.splice(0,this.inbound.length-32)}consume(){if(this.requireOpen(),this.inbound.length===0)return[];let t=this.inbound;return this.inbound=[],t}emit(t){this.requireOpen();for(let n of this.listeners)n(t)}onEvent(t){return this.requireOpen(),this.listeners.push(t),()=>{this.listeners=this.listeners.filter(n=>n!==t)}}clearInbound(){this.requireOpen(),this.inbound=[]}clear(){this.inbound=[],this.listeners=[]}close(){this.closed=!0,this.clear()}requireOpen(){if(this.closed)throw new Error(Cr)}};var xr=["image","audio","font","spritesheet"],Rr=["timeout","cors","not-found","invalid","aborted","resolver"],Oe="cyberart:fallback/silent",fn="Asset preloader has been destroyed",Sr=4,kr=new Set(xr),Tr=new Set(Rr),Ir={timeout:"asset load timed out",cors:"CORS blocked this asset","not-found":"asset was not found",invalid:"asset declaration or resource is invalid",aborted:"asset load was aborted",resolver:"asset resolver failed"};function Pr(e){return typeof e=="string"&&kr.has(e)}function Dr(e){return typeof e=="string"&&Tr.has(e)}function Ct(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.id=="string"&&typeof t.ref=="string"&&Dr(t.code)&&typeof t.message=="string"}function Z(e){return{id:e.id,ref:e.ref,code:e.code,message:e.message&&e.message.length>0?e.message:Ir[e.code]}}function ke(e,t){return{type:e==="ready"?He:Fe,kind:"state",payload:t}}function Mr(e){return e instanceof Error&&e.name==="AbortError"||typeof DOMException<"u"&&e instanceof DOMException&&e.name==="AbortError"}function xt(e){return e?{...e}:void 0}function pe(e){let t={id:e.id,ref:e.ref,type:e.type,url:e.url};return e.integrity!==void 0&&(t.integrity=e.integrity),e.provenance&&(t.provenance=xt(e.provenance)),e.cors!==void 0&&(t.cors=e.cors),e.usedFallback&&(t.usedFallback=!0),e.managed&&(t.managed=!0),t}function Le(e){return{id:e.id,ref:e.ref,code:e.code,message:e.message}}function Hr(e){if(e.state==="ready"){let t={state:"ready",resource:pe(e.resource)};return e.failure&&(t.failure=Le(e.failure)),t}return e.state==="failed"?{state:"failed",failure:Le(e.failure)}:{state:e.state}}function Fr(e){if(!e||typeof e!="object")return Z({id:"",ref:"",code:"invalid",message:"declaration is required"});if(typeof e.id!="string"||e.id.length===0)return Z({id:typeof e.id=="string"?e.id:"",ref:typeof e.ref=="string"?e.ref:"",code:"invalid",message:"id is required"});if(typeof e.ref!="string"||e.ref.length===0)return Z({id:e.id,ref:"",code:"invalid",message:"ref is required"});if(!Pr(e.type))return Z({id:e.id,ref:e.ref,code:"invalid",message:`unsupported type ${String(e.type)}`});if(e.integrity!==void 0&&typeof e.integrity!="string")return Z({id:e.id,ref:e.ref,code:"invalid",message:"integrity must be a string"});if(e.timeoutMs!==void 0&&(typeof e.timeoutMs!="number"||!Number.isFinite(e.timeoutMs)||e.timeoutMs<0))return Z({id:e.id,ref:e.ref,code:"invalid",message:"timeoutMs must be a non-negative finite number"})}function gn(e){return{id:e.id,ref:Oe,type:e.type,url:Oe,usedFallback:!0,cors:"omit"}}function bn(e,t){return Ct(t)?{id:e.id,ref:e.ref,code:t.code,message:t.message}:Mr(t)?Z({id:e.id,ref:e.ref,code:"aborted"}):Z({id:e.id,ref:e.ref,code:"resolver",message:t instanceof Error?t.message:String(t)})}function yn(e,t){if(!t||typeof t.url!="string"||t.url.length===0)throw Z({id:e.id,ref:e.ref,code:"invalid",message:"resolver returned no url"});if(t.integrity&&e.integrity&&t.integrity!==e.integrity)throw Z({id:e.id,ref:e.ref,code:"invalid",message:"integrity mismatch"});let n=pe(t);return n.id=e.id,n.ref=t.ref||e.ref,n.type=e.type,!n.integrity&&e.integrity&&(n.integrity=e.integrity),!n.provenance&&e.provenance&&(n.provenance=xt(e.provenance)),n}function vn(e){if(typeof e?.resolver?.resolve!="function")throw new Error("createAssetPreloader: resolver is required");let t=e.emitEvents!==!1,n=e.wallClockTimeout!==!1,r=new Map,i=[],s=new Map,a=new Map,c=new Map,h=new Map,g=new Map,b=new Set,m=!1;function E(d){return d.code==="aborted"||d.code==="timeout"}function H(d,F,L){let $=bn(d,L);return $.code==="timeout"?$:F.aborted?Z({id:d.id,ref:d.ref,code:"aborted"}):$}function C(d,F){let L=g.get(d);L||(L=new Set,g.set(d,L)),L.add(F)}function O(d){if(d?.state==="ready")return`${d.resource.type}\0${d.resource.ref}`}function R(d,F){for(let[L,$]of g)if(L!==F&&$.has(d))return!0;for(let[L,$]of r)if(L!==F&&O($)===d)return!0;return!1}function G(d,F){let L=new Set(g.get(d)),$=O(F);$&&L.add($),g.delete(d);for(let o of L)R(o,d)||c.delete(o)}function K(){let d=0,F=0,L=0,$=0,o={};for(let[p,f]of r)o[p]=Hr(f),f.state==="pending"||f.state==="loading"?d+=1:f.state==="failed"?L+=1:(F+=1,(f.resource.usedFallback||f.failure)&&($+=1));return{total:r.size,pending:d,ready:F,failed:L,fallbacks:$,items:o,failures:i.map(Le)}}function z(){if(b.size===0)return;let d=K();for(let F of b)F(d)}function v(d){i.push(Le(d))}function T(d){m||!t||!e.dispatch||e.dispatch(d)}function l(d){if(d?.managed&&d.url.startsWith("blob:")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(d.url)}catch{}}function x(d,F){if(m)return;let L=r.get(d);L?.state==="ready"&&l(L.resource),r.set(d,F),z()}function U(d){if(d.fallback!==void 0)return d.fallback==="silent"?{id:`${d.id}::fallback`,ref:Oe,type:d.type}:typeof d.fallback=="string"?{id:`${d.id}::fallback`,ref:d.fallback,type:d.type}:{...d.fallback,id:typeof d.fallback.id=="string"&&d.fallback.id.length>0?d.fallback.id:`${d.id}::fallback`}}function V(d,F,L){let $=`${d.type}\0${d.ref}`,o=c.get($);if(o)return F.aborted?Promise.reject(Z({id:d.id,ref:d.ref,code:"aborted"})):(C(L,$),Promise.resolve(pe(o.resource)));if(F.aborted)return Promise.reject(Z({id:d.id,ref:d.ref,code:"aborted"}));let p=h.get($);if(!p){let A=new AbortController,w={id:d.id,ref:d.ref,type:d.type};d.integrity!==void 0&&(w.integrity=d.integrity),d.provenance&&(w.provenance=xt(d.provenance)),p={promise:Promise.resolve().then(()=>e.resolver.resolve(w,A.signal)).then(I=>{let M=yn(d,I);if(A.signal.aborted)throw Z({id:d.id,ref:d.ref,code:"aborted"});return c.set($,{resource:pe(M)}),M}).catch(I=>{throw bn(d,I)}).finally(()=>{h.delete($)}),controller:A,waiters:0},h.set($,p)}let f=p;return f.waiters+=1,new Promise((A,w)=>{let S=!1,I=(_,B)=>{S||(S=!0,F.removeEventListener("abort",M),f.waiters-=1,B&&f.waiters<=0&&f.controller.abort(),_())},M=()=>{I(()=>w(Z({id:d.id,ref:d.ref,code:"aborted"})),!0)};if(F.aborted){M();return}F.addEventListener("abort",M,{once:!0}),f.promise.then(_=>{if(!S){if(F.aborted){M();return}C(L,$),I(()=>A(pe(_)),!1)}},_=>{if(!S){if(F.aborted){M();return}I(()=>w(_),!1)}})})}function W(d,F,L){if(F.aborted)return Promise.reject(Z({id:d.id,ref:d.ref,code:"aborted"}));if(d.ref===Oe)return Promise.resolve(gn(d));let $=new AbortController,o=()=>$.abort();F.addEventListener("abort",o,{once:!0});let p=d.timeoutMs??e.timeoutMs,f,A=!1;return n&&p!==void 0&&p>0&&Number.isFinite(p)&&(f=setTimeout(()=>{A=!0,$.abort()},p)),V(d,$.signal,L).then(w=>{let S=yn(d,w);return S.id=d.id,S}).catch(w=>{throw A?Z({id:d.id,ref:d.ref,code:"timeout"}):w}).finally(()=>{f!==void 0&&clearTimeout(f),F.removeEventListener("abort",o)})}async function Q(d,F,L,$){try{return{resource:await W(d,F,$)}}catch(o){let p=H(d,F,o);if(E(p)||F.aborted||L>=Sr)throw p;let f=U(d);if(!f)throw p;if(F.aborted)throw Z({id:d.id,ref:d.ref,code:"aborted"});if(d.fallback==="silent"||f.ref===Oe)return{resource:gn(d),failure:p};try{let A=await Q(f,F,L+1,$);return{resource:{...pe(A.resource),id:d.id,usedFallback:!0},failure:p}}catch(A){let w=Ct(A)&&!E(A)&&!F.aborted?A:H(d,F,A);throw!E(w)&&!F.aborted&&v(p),w}}}async function ee(d,F){if(m)throw new Error(fn);let L=r.get(d.id);if(L?.state==="ready"||L?.state==="failed")return;let $=s.get(d.id);if($){await $;return}let o=(async()=>{let p=Fr(d);if(p){x(d.id,{state:"failed",failure:p}),v(p),T(ke("failed",{id:d.id,ref:d.ref,failure:p}));return}x(d.id,{state:"loading"});let f=a.get(d.id)??new AbortController;a.has(d.id)||a.set(d.id,f);try{let A=await Q(d,f.signal,F,d.id);if(m)return;if(f.signal.aborted){let w=Z({id:d.id,ref:d.ref,code:"aborted"});x(d.id,{state:"failed",failure:w}),v(w),T(ke("failed",{id:d.id,ref:d.ref,failure:w}));return}if(A.resource.id=d.id,A.failure){x(d.id,{state:"ready",resource:A.resource,failure:A.failure}),v(A.failure),T(ke("failed",{id:d.id,ref:d.ref,failure:A.failure,resource:pe(A.resource)})),T(ke("ready",{id:d.id,ref:A.resource.ref,resource:pe(A.resource),failure:A.failure}));return}x(d.id,{state:"ready",resource:A.resource}),T(ke("ready",{id:d.id,ref:d.ref,resource:pe(A.resource)}))}catch(A){if(m)return;let w=Ct(A)&&!E(A)&&!f.signal.aborted?{...Le(A),id:d.id}:H(d,f.signal,A);x(d.id,{state:"failed",failure:w}),v(w),T(ke("failed",{id:d.id,ref:d.ref,failure:w}))}finally{a.get(d.id)===f&&a.delete(d.id)}})();s.set(d.id,o);try{await o}finally{s.delete(d.id)}}return{async preload(d){if(m)throw new Error(fn);let F=Array.isArray(d)?d:[];for(let L of F)L&&typeof L.id=="string"&&L.id.length>0&&(r.has(L.id)||r.set(L.id,{state:"pending"}),a.has(L.id)||a.set(L.id,new AbortController));return z(),await Promise.all(F.map(L=>ee(L,0))),K()},get(d){let F=r.get(d);if(F?.state==="ready")return pe(F.resource)},getProgress(){return K()},onProgress(d){return b.add(d),()=>{b.delete(d)}},abort(d){if(!m){if(d!==void 0){a.get(d)?.abort();return}for(let F of a.values())F.abort()}},forget(d){if(m)return;if(d===void 0){for(let L of r.values())L.state==="ready"&&l(L.resource);r.clear(),i.length=0,c.clear(),g.clear(),z();return}let F=r.get(d);F?.state==="ready"&&l(F.resource),G(d,F),r.delete(d);for(let L=i.length-1;L>=0;L--)i[L].id===d&&i.splice(L,1);z()},dispose(){if(!m){m=!0;for(let d of a.values())d.abort();a.clear();for(let d of r.values())d.state==="ready"&&l(d.resource);r.clear(),i.length=0,s.clear();for(let d of h.values())d.controller.abort();c.clear(),h.clear(),g.clear(),b.clear()}}}}function Je(e){Kt();let{container:t,seed:n,captureKeyboard:r=!1,audio:i,deterministic:s,assets:a}=e,c=n===void 0?void 0:en(n,s?"deterministic":"live"),h=new Xe;if(a&&typeof a.resolver?.resolve!="function")throw new Error("createRuntime: assets.resolver is required");let g=a?vn({resolver:a.resolver,timeoutMs:a.timeoutMs,emitEvents:a.emitEvents??!s,wallClockTimeout:!s,dispatch:v=>h.dispatch(v)}):void 0,b=!1,m=null,E,H=!1,C=t.clientWidth||window.innerWidth,O=t.clientHeight||window.innerHeight,R=new Ye(30,!1,C,O,!1,void 0,{container:t,seed:c,captureKeyboard:r,hostChannel:h,audio:i,deterministic:s}),G=()=>{let v=t.clientWidth||window.innerWidth,T=t.clientHeight||window.innerHeight;return v===R.containerWidth&&T===R.containerHeight?!1:(R.containerWidth=v,R.containerHeight=T,!0)},K=null;return!R.isDeterministic&&typeof ResizeObserver<"u"&&(K=new ResizeObserver(()=>{if(b||!m)return;G()&&H&&R.reinit()}),K.observe(t)),R.onError=(v,T)=>{E?.(v,T)},{get tokenData(){return R.tokenData},get hostChannel(){return h},get assets(){return g},get onError(){return E},set onError(v){E=v},mount(v,T={}){if(b)throw new Error("createRuntime: cannot mount on a destroyed runtime");m?.destroy(),H=!1,R.customState=T.initialState,R.setGameManager(T.gameManager);let l=T.onEvent?h.onEvent(T.onEvent):()=>{};if(!R.prepareCart(v))throw l(),new Error("createRuntime: failed to prepare cart");let x=!1,U={async start(){if(!x){if(G()&&R.isPrepared&&(R.init(),R.unloadCart(),!R.prepareCart(v)))throw new Error("createRuntime: failed to prepare cart");R.needsAudio&&(await R.unlockAudio(),x)||(H=!0,R.beginPlayback())}},pause(){x||(R.paused=!0)},resume(){x||(R.paused=!1)},dispatch(V){x||h.dispatch(V)},snapshot(){if(x)return{seed:"",pngDataUrl:""};let V=R.canvas;return{seed:R.tokenData.hash,metadata:v.metadata,pngDataUrl:V?V.toDataURL("image/png"):""}},destroy(){x||(x=!0,H=!1,l(),h.clearInbound(),R.unloadCart(),m===U&&(m=null))},reload(){if(!x){if(!H){if(R.isPrepared&&(R.unloadCart(),!R.prepareCart(v)))throw new Error("createRuntime: failed to prepare cart");return}R.reloadCart()}},reinit(V){if(!x){if(!H){G();return}R.reinit(V)}},getCartState(){return R.animation?.cartState},exportState(){return x?Promise.reject(new Error("Cart handle has been destroyed")):R.exportState()},exportStateJSON(){return x?Promise.reject(new Error("Cart handle has been destroyed")):R.exportStateJSON()},async importState(V,W){if(x)throw new Error("Cart handle has been destroyed");await R.importState(V,W)},peekExportedFramebuffer(){return x?null:R.peekExportedFramebuffer()},peekSeed(){if(!x)return R.peekSeed()},isGenerative(){return x?!1:R.isGenerative()},async step(V=1){if(x)throw new Error("Cart handle has been destroyed");await R.step(V)},async advance(V){if(x)throw new Error("Cart handle has been destroyed");await R.advance(V)},schedule(V){x||R.schedule(V)},getClock(){if(x)throw new Error("Cart handle has been destroyed");return R.getClock()},getRandomState(){if(x)throw new Error("Cart handle has been destroyed");return R.getRandomState()},getReplayMetadata(){return x?Promise.reject(new Error("Cart handle has been destroyed")):R.getReplayMetadata()},get canvas(){return R.canvas},get paused(){return R.paused},set paused(V){x||(R.paused=V)},get tokenData(){return R.tokenData},get isPrepared(){return R.isPrepared},get isLoopRunning(){return R.isLoopRunning},get needsAudio(){return R.needsAudio},get audioLibraries(){return R.audioLibraries}};return m=U,U},async unlockAudio(){await R.unlockAudio()},destroy(){b||(b=!0,m?.destroy(),m=null,K?.disconnect(),K=null,g?.dispose(),h.close(),R.destroy())}}}var wn="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",An=320,En=180,Or="Headless harness has been destroyed",Cn=!1;function Qe(e={}){if(e.glyphAtlas&&ot(e.glyphAtlas),typeof globalThis.ImageData>"u"){class n{constructor(i,s,a){this.colorSpace="srgb";typeof i=="number"?(this.width=i,this.height=s??0,this.data=new Uint8ClampedArray(this.width*this.height*4)):(this.data=i,this.width=s??0,this.height=a??i.length/4/this.width)}}globalThis.ImageData=n}Gt();let t=HTMLCanvasElement.prototype;t.getContext=function(r,i){return String(r??"2d").toLowerCase()!=="2d"?null:ut(this,{alpha:i?.alpha!==!1,glyphAtlas:e.glyphAtlas})},t.toDataURL=function(r){if(r&&r!=="image/png")throw new j(`toDataURL(${r})`);return Ot(this)??wn},Cn=!0}function Lr(e,t){let n=document.createElement("div");return Object.defineProperty(n,"clientWidth",{value:e,configurable:!0}),Object.defineProperty(n,"clientHeight",{value:t,configurable:!0}),document.body.appendChild(n),n}function _r(e){let t=e.indexOf(","),n=t>=0?e.slice(t+1):e,r=globalThis.atob(n),i=new Uint8Array(r.length);for(let s=0;s<r.length;s++)i[s]=r.charCodeAt(s);return i}function Ur(){return typeof process<"u"&&!!process.versions?.node}async function Nr(e,t){if(!Ur())throw new Error("captureFrame(path) requires Node.js; omit the path to get the snapshot only");let n;try{({writeFile:n}=await import("node:fs/promises"))}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`captureFrame(path) could not load node:fs/promises (${i}). Omit the path, or run under Node.`)}try{await n(e,_r(t))}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`captureFrame could not write ${e}: ${i}`)}}function Gr(e){Cn||Qe();let t=e.width??An,n=e.height??En,r=Lr(t,n),i=[],s=[],a=!1,c=e.onEvent,h=e.onError,g=Je({container:r,seed:e.seed,deterministic:{origin:e.origin,actions:e.actions??[]}});g.onError=(C,O)=>{s.push({error:C,info:O}),h?.(C,O)},Object.defineProperty(g,"onError",{configurable:!0,enumerable:!0,get(){return h},set(C){h=C}});let b=C=>{i.push(C),c?.(C)},m=g.mount(e.cart,{initialState:e.initialState,gameManager:e.gameManager,onEvent:b}),E=()=>{if(a)throw new Error(Or)};return{runtime:g,container:r,get events(){return i.slice()},get errors(){return s.slice()},get cart(){return m},async step(C=1){E(),await m.step(C)},async advance(C){E(),await m.advance(C)},schedule(C){E(),m.schedule(C)},dispatch(C){E(),m.dispatch(C)},start(){return E(),m.start()},pause(){E(),m.pause()},resume(){E(),m.resume()},get paused(){return m.paused},key(C){E(),m.schedule({type:"key",atFrame:m.getClock().framesElapsed,key:C})},click(C,O){E(),m.schedule({type:"pointer",atFrame:m.getClock().framesElapsed,pointer:{kind:"down",x:C,y:O}})},async inspect(){E();let C=await m.getReplayMetadata();return{state:C.state,events:i.slice(),errors:s.slice(),replay:C,clock:m.getClock()}},async captureFrame(C){E();let O=m.snapshot();return C&&await Nr(C,O.pngDataUrl),O},remount(C={}){return E(),i.length=0,s.length=0,"onEvent"in C&&(c=C.onEvent),m=g.mount(e.cart,{initialState:C.initialState??e.initialState,gameManager:C.gameManager??e.gameManager,onEvent:b}),m},destroy(){if(!a){a=!0;try{m.destroy()}finally{try{g.destroy()}finally{r.remove()}}}}}}var xn="CYBERART_UPDATE_GOLDEN";function Rn(e=typeof process<"u"?process.env:void 0){let t=e?.[xn];return t==="1"||t==="true"}function Rt(e){return ct(Ve(e))}function Sn(e,t,n={}){if(e.width!==t.width||e.height!==t.height){let b=Vr(e,t);return{match:!1,differingPixels:e.width*e.height,width:e.width,height:e.height,artifacts:b,updatedGolden:!1}}let r=n.tolerance??0,i=n.perceptualThreshold,s=n.maxDifferingPixels??0,a=new Uint8ClampedArray(e.width*e.height*4),c=0;for(let b=0;b<e.data.length;b+=4){let m=Math.abs(e.data[b]-t.data[b]),E=Math.abs(e.data[b+1]-t.data[b+1]),H=Math.abs(e.data[b+2]-t.data[b+2]),C=Math.abs(e.data[b+3]-t.data[b+3]),O=.299*m+.587*E+.114*H,R=n.alphaTolerance??r;(i!==void 0?O<=i&&C<=R:m<=r&&E<=r&&H<=r&&C<=R)?(a[b]=0,a[b+1]=0,a[b+2]=0,a[b+3]=255):(c+=1,a[b]=255,a[b+1]=0,a[b+2]=255,a[b+3]=255)}let h=St(t,e,he(a,e.width,e.height),c);return n.updateGolden===!0||Rn()?{match:!0,differingPixels:0,width:e.width,height:e.height,artifacts:St(e,e,he(a,e.width,e.height),0),updatedGolden:!0}:{match:c<=s,differingPixels:c,width:e.width,height:e.height,artifacts:h,updatedGolden:!1}}function kn(e,t,n={}){let r=Sn(e,t,n);if(!r.match){let i=new Error(`Visual assertion failed: ${r.differingPixels} differing pixels (${r.width}\xD7${r.height}). Review expected/actual/diff PNG buffers on the result.`);throw i.visual=r,i}return r}function Kr(e,t,n={}){return kn(Rt(e),Rt(t),n)}function St(e,t,n,r){let i=Ae(e.width,e.height,e.data),s=Ae(t.width,t.height,t.data),a=Ae(n.width,n.height,n.data);return{expectedPng:i,actualPng:s,diffPng:a,expectedDataUrl:Ee(e.width,e.height,e.data),actualDataUrl:Ee(t.width,t.height,t.data),diffDataUrl:Ee(n.width,n.height,n.data),differingPixels:r}}function Vr(e,t){let n=Math.max(e.width,t.width),r=Math.max(e.height,t.height),i=new Uint8ClampedArray(n*r*4);for(let s=0;s<i.length;s+=4)i[s]=255,i[s+1]=0,i[s+2]=255,i[s+3]=255;return St(t,e,he(i,n,r),n*r)}async function Wr(e,t,n={}){let{mkdir:r,writeFile:i}=await import("node:fs/promises"),{join:s}=await import("path");await r(e,{recursive:!0});let a=s(e,n.expected??"expected.png"),c=s(e,n.actual??"actual.png"),h=s(e,n.diff??"diff.png");return await i(a,t.expectedPng),await i(c,t.actualPng),await i(h,t.diffPng),{expectedPath:a,actualPath:c,diffPath:h}}var Tn="cyberart.state.save",In="cyberart.state.load";var Ze=1,_e="cyberart.diagnostic.rejected",kt=8,$r=new Set(["intent","state","diagnostic"]),Br=new Set([Tn,In]);function Pn(e){return typeof e=="string"&&$r.has(e)}function jr(e){if(e.kind!==void 0)return Pn(e.kind)?e.kind:void 0;if(!(typeof e.type!="string"||e.type.length===0)){if(Br.has(e.type))return"intent";for(let t of e.type.split("."))if(Pn(t))return t}}function zr(e,t){let n=e.split("."),r=t.split(".");if(n.length!==r.length)return!1;for(let i=0;i<n.length;i++)if(n[i]!=="*"&&n[i]!==r[i])return!1;return!0}function Te(e,t){for(let n of e)if(zr(n,t))return!0;return!1}function qr(e){if(e===void 0)return{ok:!0,value:void 0};try{return{ok:!0,value:JSON.parse(JSON.stringify(e))}}catch{return{ok:!1}}}function Tt(e,t){if(!e||typeof e.type!="string"||e.type.length===0)return{ok:!1,reason:"malformed",detail:"type is required"};if(e.schemaVersion!==void 0&&e.schemaVersion!==Ze)return{ok:!1,reason:"malformed",detail:`unsupported schemaVersion ${String(e.schemaVersion)}`};let n=jr(e);if(!n)return{ok:!1,reason:"malformed",detail:`cannot infer kind from type "${e.type}"`};let r=qr(e.payload);if(!r.ok)return{ok:!1,reason:"malformed",detail:"payload is not JSON-serializable"};let i=t.createId(),s=typeof e.correlationId=="string"&&e.correlationId.length>0?e.correlationId:i,a=typeof e.causationId=="string"&&e.causationId.length>0?e.causationId:t.causationId,c=typeof e.target=="string"&&e.target.length>0?e.target:void 0,h=t.maxHops??kt,g=t.parentHops===void 0?h:Math.max(0,t.parentHops-1),b=typeof e.idempotencyKey=="string"&&e.idempotencyKey.length>0?e.idempotencyKey:void 0,m={schemaVersion:Ze,type:e.type,kind:n,source:t.source,id:i,correlationId:s,seq:t.seq,hops:g};return c&&(m.target=c),a&&(m.causationId=a),b&&(m.idempotencyKey=b),r.value!==void 0&&(m.payload=r.value),{ok:!0,envelope:m}}var Yr=new Set(["rate-limited","storm-detected","hop-limit","loop-detected","not-subscribed"]),Xr=8,Jr=8,Qr=16,Zr=256,ei=256,ti=["*.intent.*"];function Dn(e={}){let t=e.hostSource??"host",n="router",r=e.maxPerTurn??Xr,i=e.maxCausationDepth??Jr,s=e.maxHops??kt,a=e.maxCorrelationPerTurn??Qr,c=e.maxIndex??Zr,h=e.maxDecisions??ei,g=e.maxPerWindow,b=e.windowMs??1e3,m=e.now??Date.now,E=0,H=e.createId??(()=>`evt-${++E}`),C=new Map,O=[],R=[],G=new Map,K=new Map,z=new Map,v=[],T=0,l=0,x=0;function U(u){try{return JSON.parse(JSON.stringify(u))}catch{return u}}function V(u){for(v.push(u);v.length>h;)v.shift();for(let y of R)try{y(U(u))}catch{}}function W(u,y){let k={outcome:y.outcome,source:y.source,type:u.type,kind:u.kind,envelopeId:u.id,deliveredTo:y.deliveredTo,hops:u.hops,seq:u.seq,correlationId:u.correlationId,schemaVersion:u.schemaVersion,turn:x,time:m()};return y.reason&&(k.reason=y.reason),y.detail&&(k.detail=y.detail),y.priorEnvelopeId&&(k.priorEnvelopeId=y.priorEnvelopeId),u.target&&(k.target=u.target),u.causationId&&(k.causationId=u.causationId),u.idempotencyKey&&(k.idempotencyKey=u.idempotencyKey),u.payload!==void 0&&(k.payload=U(u.payload)),k}let Q=[],ee=!1;function d(u,y,k){for(u.set(y,k);u.size>c;){let P=u.keys().next().value;if(P===void 0)break;u.delete(P)}}function F(u){d(G,u.id,{type:u.type,source:u.source,causationId:u.causationId,hops:u.hops,correlationId:u.correlationId,idempotencyKey:u.idempotencyKey})}function L(u,y){y&&(u.correlationId||(u.correlationId=y.correlationId),u.causationId||(u.causationId=y.id),!u.idempotencyKey&&y.idempotencyKey&&(u.idempotencyKey=`${y.idempotencyKey}::${u.type}`))}function $(u,y){if(u){let k=G.get(u);return k?k.hops:s}return y}function o(u,y){return`${u}\0${y}`}function p(u,y){u.idempotencyKey&&d(z,o(u.source,u.idempotencyKey),y)}function f(u,y){if(y)return z.get(o(u,y))}function A(u){return f(u.source,u.idempotencyKey)}function w(u){return u.seq+=1,u.seq}function S(u,y){if(!(typeof y.causationId=="string"&&y.causationId.length>0))return u.lastDelivered}function I(u){let y=new Set,k=new Set([`${u.type}\0${u.source}`]),P=u.causationId,D=0;for(;P;){if(D+=1,D>i||y.has(P))return!0;y.add(P);let N=G.get(P);if(!N)break;let oe=`${N.type}\0${N.source}`;if(k.has(oe))return!0;k.add(oe),P=N.causationId}return!1}function M(u){let y=(K.get(u)??0)+1;return K.set(u,y),y}function _(u,y){g!==void 0&&(u.emitTimestamps=u.emitTimestamps.filter(k=>y-k<b))}function B(u,y){return(y.kind==="state"||y.kind==="diagnostic")&&!u.authoritative?!1:Te(u.emit,y.type)}function X(u){for(let y of O)if(Te(y.patterns,u.type))try{y.listener(u)}catch{}}function q(u){let y=[];if(u.target){let k=C.get(u.target);return!k||!Te(k.subscribe,u.type)||(k.channel.dispatch(u),k.lastDelivered={id:u.id,hops:u.hops,correlationId:u.correlationId,idempotencyKey:u.idempotencyKey},y.push(k.id)),y}for(let k of C.values())Te(k.subscribe,u.type)&&(k.channel.dispatch(u),k.lastDelivered={id:u.id,hops:u.hops,correlationId:u.correlationId,idempotencyKey:u.idempotencyKey},y.push(k.id));return y}function re(u,y,k,P,D,N,oe){let ne={reason:P,eventType:y,source:k};D&&(ne.detail=D),l+=1;let ce=H(),fe={schemaVersion:Ze,type:_e,kind:"diagnostic",source:n,id:ce,correlationId:N??ce,seq:l,hops:0,payload:ne};oe&&(fe.causationId=oe),F(fe);let Ue=C.get(u);Ue&&Ue.channel.dispatch(fe),X(fe)}function J(u,y,k,P,D){if(re(u,D?.type??(typeof y.type=="string"?y.type:""),D?.source??u,k,P,D?.correlationId,D?.id),D?.idempotencyKey&&!Yr.has(k)&&p(D,{status:"rejected"}),D)V(W(D,{outcome:"rejected",reason:k,detail:P,source:u,deliveredTo:[]}));else{let N={outcome:"rejected",reason:k,source:u,type:typeof y.type=="string"?y.type:"",deliveredTo:[],turn:x,time:m()};P&&(N.detail=P),typeof y.idempotencyKey=="string"&&(N.idempotencyKey=y.idempotencyKey),V(N)}}function ae(u,y){F(u),p(u,{status:"accepted",envelope:u}),M(u.correlationId),X(u);let k=q(u);V(W(u,{outcome:"accepted",source:y,deliveredTo:k}))}function ie(u,y,k,P){let D=P?.type??(typeof y.type=="string"?y.type:""),N={outcome:"duplicate",reason:"duplicate",detail:k.status==="accepted"?"idempotent accepted":"idempotent rejected",source:u,type:D,deliveredTo:[],turn:x,time:m()};P?(N.kind=P.kind,N.envelopeId=P.id,N.hops=P.hops,N.seq=P.seq,N.correlationId=P.correlationId,N.schemaVersion=P.schemaVersion,P.target&&(N.target=P.target),P.causationId&&(N.causationId=P.causationId),P.idempotencyKey&&(N.idempotencyKey=P.idempotencyKey),P.payload!==void 0&&(N.payload=U(P.payload))):typeof y.idempotencyKey=="string"&&(N.idempotencyKey=y.idempotencyKey),k.status==="accepted"&&(N.priorEnvelopeId=k.envelope.id,N.envelopeId||(N.envelopeId=k.envelope.id)),V(N)}function Y(u,y,k,P){if(!k.ok){J(u,y,"malformed",k.detail);return}let D=k.envelope,N=A(D);if(N)return ie(u,y,N,D),N.status==="accepted"?N.envelope:void 0;if(D.hops<1){J(u,y,"hop-limit","no hops remaining",D);return}if(D.target&&D.target!==t){let oe=C.get(D.target);if(!oe){J(u,y,"unknown-target",`unknown target "${D.target}"`,D);return}if(!Te(oe.subscribe,D.type)){J(u,y,"not-subscribed",`target "${D.target}" does not subscribe to ${D.type}`,D);return}}if(P){if(!B(P,D)){J(u,y,"unauthorized","source may not emit this event",D);return}if(P.emitsThisTurn+=1,P.emitsThisTurn>r){J(u,y,"rate-limited","maxPerTurn exceeded",D);return}if(g!==void 0){let ne=m();if(_(P,ne),P.emitTimestamps.push(ne),P.emitTimestamps.length>g){J(u,y,"rate-limited","maxPerWindow exceeded",D);return}}if(I(D)){J(u,y,"loop-detected","causation chain cycle or depth exceeded",D);return}if((K.get(D.correlationId)??0)+1>a){J(u,y,"storm-detected","correlationId storm",D);return}if(e.validate){let ne;try{ne=e.validate(D)}catch(ce){let fe=ce instanceof Error?ce.message:"validate threw";J(u,y,"host-rejected",fe,D);return}if(ne!==!0){J(u,y,"host-rejected",ne.detail,D);return}}}else{if(I(D)){J(u,y,"loop-detected","causation chain cycle or depth exceeded",D);return}if((K.get(D.correlationId)??0)+1>a){J(u,y,"storm-detected","correlationId storm",D);return}}return ae(D,u),D}function te(u,y){let k=C.get(u);if(!k)return;let P={...y},D=S(k,P);L(P,D);let N=f(k.id,P.idempotencyKey);if(N){ie(u,P,N);return}let oe=w(k),ne=Tt(P,{source:k.id,createId:H,seq:oe,causationId:D?.id,maxHops:s,parentHops:$(P.causationId??D?.id,D?.hops)});Y(u,P,ne,k)}function ve(u,y){let k=y?.cause,P={...u};L(P,k);let D=f(t,P.idempotencyKey);if(D)return ie(t,P,D),D.status==="accepted"?D.envelope:void 0;T+=1;let N=Tt(P,{source:t,createId:H,seq:T,causationId:P.causationId,maxHops:s,parentHops:$(P.causationId,k?.hops)});return Y(t,P,N,void 0)}function ye(){if(!ee){ee=!0;try{for(;Q.length>0;){let u=Q.shift();u&&(u.kind==="cart"?te(u.participantId,u.event):u.result=ve(u.event,u.extras))}}finally{ee=!1}}}function me(u){Q.push(u),ye()}return{attach(u,y,k={}){if(u===t||u===n)throw new Error(`createEventRouter: "${u}" is a reserved participant id`);for(let N of C.values())if(N.channel===y&&N.id!==u)throw new Error(`createEventRouter: channel already attached as "${N.id}"`);C.get(u)?.unsubscribe();let D={id:u,channel:y,emit:k.emit??ti,subscribe:k.subscribe??[],authoritative:k.authoritative===!0,seq:0,emitsThisTurn:0,emitTimestamps:[],unsubscribe:()=>{}};D.unsubscribe=y.onEvent(N=>{me({kind:"cart",participantId:u,event:N})}),C.set(u,D)},detach(u){let y=C.get(u);y&&(y.unsubscribe(),C.delete(u))},publish(u,y){let k={kind:"publish",event:u,extras:y};return me(k),k.result},subscribe(u,y){let k={patterns:u,listener:y};return O.push(k),()=>{let P=O.indexOf(k);P>=0&&O.splice(P,1)}},subscribeDecision(u){return R.push(u),()=>{let y=R.indexOf(u);y>=0&&R.splice(y,1)}},inspectParticipants(){return[...C.values()].map(u=>({id:u.id,emit:u.emit.slice(),subscribe:u.subscribe.slice(),authoritative:u.authoritative}))},inspectDecisions(){return v.map(u=>U(u))},turn(){x+=1,K.clear();for(let u of C.values())u.emitsThisTurn=0,u.lastDelivered=void 0,g!==void 0&&_(u,m())}}}var ni=320,ri=180,ii=1024,si="Runtime group has been destroyed";function ai(e){let t="";for(let n=0;n<32;n++){let r=e.charCodeAt(n%Math.max(e.length,1))+n*17&255;t+=r.toString(16).padStart(2,"0")}return`0x${t}`}function oi(e,t){let n=document.createElement("div");return Object.defineProperty(n,"clientWidth",{value:e,configurable:!0}),Object.defineProperty(n,"clientHeight",{value:t,configurable:!0}),document.body.appendChild(n),n}function Hn(e){let t=e.capability,n={},r=e.emit??t?.emit,i=e.subscribe??t?.subscribe,s=e.authoritative??t?.authoritative;return r&&(n.emit=r),i&&(n.subscribe=i),s!==void 0&&(n.authoritative=s),n}function Mn(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function ui(e){let t=new Set([_e,"*.*","*.*.*","*.*.*.*","*.*.*.*.*"]);for(let n of e){let r=Hn(n);for(let i of r.emit??[])t.add(i);for(let i of r.subscribe??[])t.add(i)}return[...t]}function Fn(e){if(!e.participants.length)throw new Error("createRuntimeGroup: at least one participant is required");let t=new Set;for(let l of e.participants){if(!l.id)throw new Error("createRuntimeGroup: participant id is required");if(t.has(l.id))throw new Error(`createRuntimeGroup: duplicate participant id "${l.id}"`);t.add(l.id)}let n=e.origin??0,r=e.width??ni,i=e.height??ri,s=e.maxTrace??ii,a=[...e.participants].sort((l,x)=>l.id.localeCompare(x.id)),c=[],h=new Map,g=0,b=e.createId??e.router?.createId??(()=>`evt-${++g}`),m=e.now??e.router?.now??(()=>{let l=c[0];if(!l)return n;try{return l.cart.getClock().now}catch{return n}}),E=Dn({...e.router,createId:b,now:m,validate:e.validate??e.router?.validate}),H=[],C=!1,O=!1,R=()=>{},G=l=>x=>{l.events.push(x),l.userOnEvent?.(x)},K=()=>{if(O)throw new Error(si)},z=()=>{R();for(let l of c){try{E.detach(l.id)}catch{}try{l.runtime.destroy()}catch{}l.ownsContainer&&l.container.remove()}c.length=0,h.clear()};try{for(let l of a){let x=l.width??r,U=l.height??i,V=!l.container,W=l.container??oi(x,U),Q=Je({container:W,seed:l.seed??ai(l.id),deterministic:{origin:n}}),ee={id:l.id,kind:l.kind??"render",cartDef:l.cart,initialState:l.initialState,gameManager:l.gameManager,userOnEvent:l.onEvent,runtime:Q,container:W,ownsContainer:V,cart:void 0,events:[],errors:[]};Q.onError=(d,F)=>{ee.errors.push({error:d,info:F})},E.attach(l.id,Q.hostChannel,Hn(l)),ee.cart=Q.mount(l.cart,{initialState:l.initialState,gameManager:l.gameManager,onEvent:G(ee)}),c.push(ee),h.set(ee.id,ee)}R=E.subscribe(ui(a),l=>{for(H.push(Mn(l));H.length>s;)H.shift()})}catch(l){throw z(),l}let v=l=>({id:l.id,kind:l.kind,runtime:l.runtime,container:l.container,get events(){return l.events.slice()},get errors(){return l.errors.slice()},get cart(){return l.cart}});return{router:E,origin:n,get paused(){return C},participant(l){K();let x=h.get(l);if(!x)throw new Error(`createRuntimeGroup: unknown participant "${l}"`);return v(x)},async step(l=1){if(K(),C)return;let x=Math.max(0,Math.floor(l));for(let U=0;U<x;U++){E.turn();for(let V of c)try{await V.cart.step(1)}catch(W){V.errors.push({error:W,info:{phase:"update",consecutive:V.errors.length+1,stopped:!1}})}}},pause(){K(),C=!0;for(let l of c)l.cart.pause()},resume(){K(),C=!1;for(let l of c)l.cart.resume()},reset(){K(),H.length=0;for(let l of c)l.events.length=0,l.errors.length=0,l.cart=l.runtime.mount(l.cartDef,{initialState:l.initialState,gameManager:l.gameManager,onEvent:G(l)});E.turn()},resize(l,x){K();let U=Math.max(1,l|0),V=Math.max(1,x|0);for(let W of c){Object.defineProperty(W.container,"clientWidth",{value:U,configurable:!0}),Object.defineProperty(W.container,"clientHeight",{value:V,configurable:!0});let Q=W.cart.canvas;Q&&(Q.width=U,Q.height=V)}},detach(l){K();let x=h.get(l);if(!x)throw new Error(`createRuntimeGroup: unknown participant "${l}"`);try{E.detach(x.id)}catch{}try{x.runtime.destroy()}catch{}x.ownsContainer&&x.container.remove();let U=c.indexOf(x);U>=0&&c.splice(U,1),h.delete(l)},dispatch(l,x){K();let U=h.get(l);if(!U)throw new Error(`createRuntimeGroup: unknown participant "${l}"`);U.cart.dispatch(x)},publish(l,x){return K(),E.publish(l,x)},inspectParticipants(){K();let l=new Map(c.map(x=>[x.id,x.kind]));return E.inspectParticipants().map(x=>({...x,kind:l.get(x.id)??"render"}))},async inspect(){K();let l={},x={},U=new Map(E.inspectParticipants().map(W=>[W.id,W]));for(let W of c){let Q=await W.cart.getReplayMetadata(),ee=W.cart.getClock();x[W.id]=ee;let d=U.get(W.id);l[W.id]={state:Q.state,events:W.events.slice(),errors:W.errors.slice(),kind:W.kind,clock:ee,emit:d?.emit.slice()??[],subscribe:d?.subscribe.slice()??[],authoritative:d?.authoritative===!0}}let V=H.map(W=>Mn(W));return{participants:l,trace:V,diagnostics:{paused:C,participantIds:c.map(W=>W.id),clocks:x,rejections:V.filter(W=>W.type===_e).map(W=>W.payload)}}},destroy(){if(!O){O=!0,C=!1;try{z()}finally{H.length=0}}}}}function ci(e){return Qe(),Fn(e)}var It=1,di=512,li="[REDACTED]",pi=new Set([He,Fe]);function se(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function et(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(i=>et(i,t));if(typeof e!="object")return e;let n=e,r={};for(let[i,s]of Object.entries(n))r[i]=t.has(i)?li:et(s,t);return r}function hi(e){return e instanceof Error&&typeof e.message=="string"?e.message:"error"}function mi(e,t){return t?!(t.types&&!t.types.includes(e.type)||t.sources&&!t.sources.includes(e.source)||t.outcomes&&!t.outcomes.includes(e.outcome)||t.correlationId&&e.correlationId!==t.correlationId):!0}function On(e){return JSON.stringify({outcome:e.outcome,reason:e.reason,source:e.source,target:e.target,type:e.type,kind:e.kind,envelopeId:e.envelopeId,priorEnvelopeId:e.priorEnvelopeId,correlationId:e.correlationId,causationId:e.causationId,hops:e.hops,seq:e.seq,idempotencyKey:e.idempotencyKey,deliveredTo:e.deliveredTo,payload:e.payload})}function fi(e,t){if(e.length!==t.length)return{ok:!1,detail:`record count ${t.length} !== ${e.length}`};for(let n=0;n<e.length;n++){let r=On(e[n]),i=On(t[n]);if(r!==i)return{ok:!1,detail:`record ${n} differs`}}return{ok:!0}}function Ln(e){let t=new Map,n=[];for(let s of e){if(s.outcome==="duplicate"){n.push(void 0);continue}let a={envelopeId:s.envelopeId,type:s.type,source:s.source,outcome:s.outcome,children:[]};s.reason&&(a.reason=s.reason),n.push(a),s.envelopeId&&!t.has(s.envelopeId)&&t.set(s.envelopeId,a)}let r=new Set;for(let s=0;s<e.length;s++){let a=e[s],c=n[s];if(!c)continue;let h=a.causationId?t.get(a.causationId):void 0;h&&h!==c&&(h.children.push(c),r.add(c))}let i=[];for(let s of n)s&&!r.has(s)&&i.push(s);return i}function _n(e,t){let n={id:e.id,emit:e.emit.slice(),subscribe:e.subscribe.slice(),authoritative:e.authoritative,errorCount:0};return t&&(n.kind=t),n}function gi(e,t,n){let r=t.errors[t.errors.length-1],i={id:e,kind:t.kind,emit:t.emit.slice(),subscribe:t.subscribe.slice(),authoritative:t.authoritative,clock:se(t.clock),state:et(t.state,n),errorCount:t.errors.length};return r&&(i.lastError=hi(r.error)),i}function Un(e={}){let t=new Set(e.redactedKeys??[]),n=e.maxRecords??di,r=e.registry,i=0,s=0,a=!1,c=[],h=[],g,b=[],m=0,E=[],H={},C=()=>{},O=()=>{if(a)throw new Error("Replay inspector has been destroyed")},R=v=>{let T=r?.get(v.type),l={index:s,turn:v.turn,time:v.time,outcome:v.outcome,source:v.source,type:v.type,deliveredTo:v.deliveredTo.slice(),payload:et(v.payload,t)};for(s+=1,v.reason&&(l.reason=v.reason),v.detail&&(l.detail=v.detail),v.target&&(l.target=v.target),v.kind&&(l.kind=v.kind),v.envelopeId&&(l.envelopeId=v.envelopeId),v.priorEnvelopeId&&(l.priorEnvelopeId=v.priorEnvelopeId),v.correlationId&&(l.correlationId=v.correlationId),v.causationId&&(l.causationId=v.causationId),v.hops!==void 0&&(l.hops=v.hops),v.seq!==void 0&&(l.seq=v.seq),v.idempotencyKey&&(l.idempotencyKey=v.idempotencyKey),v.schemaVersion!==void 0&&(l.schemaVersion=v.schemaVersion),T&&(l.payloadSchemaVersion=T.payloadSchema.version),c.push(l);c.length>n;)c.shift(),i+=1},G=v=>c.filter(T=>mi(T,v)).map(T=>se(T)),K=v=>v?v.inspectParticipants().map(T=>_n(T,T.kind)):E.map(T=>se(T)),z={watchRouter(v){if(O(),C(),E=v.inspectParticipants().map(l=>_n(l)),c.length===0)for(let l of v.inspectDecisions())R(l);let T=v.subscribeDecision(l=>R(l));return C=()=>{T(),C=()=>{}},h.push(C),C},bind(v){O(),g&&C(),g=v,m=v.origin,z.watchRouter(v.router),E=K(v);let T={publish(l,x){O();let U={kind:"publish",event:se(l)};return x?.cause&&(U.extras={cause:se(x.cause)}),b.push(U),v.publish(l,x)},dispatch(l,x){O();let U=se(x);typeof U.type=="string"&&pi.has(U.type)?b.push({kind:"asset",participantId:l,event:U}):b.push({kind:"dispatch",participantId:l,event:U}),v.dispatch(l,x)},async step(l=1){O(),b.push({kind:"step",frames:l}),await v.step(l)},async report(){O();let l=await v.inspect(),x=[];for(let U of Object.keys(l.participants).sort())x.push(gi(U,l.participants[U],t));E=x,H={};for(let U of x)H[U.id]=se(U.state);return z.report()},async exportTrace(l){return await T.report(),z.exportTrace(l)},unbind(){C(),g=void 0}};return T},importTrace(v){O();let T=typeof v=="string"?JSON.parse(v):v;if(T.schemaVersion!==It)throw new Error("Replay inspector: unsupported export schemaVersion");i=0,s=0,c.length=0,b=se(T.tape??[]),m=T.origin??0,E=se(T.participants??[]),H=se(T.snapshots??{});for(let l of T.records??[])R({outcome:l.outcome,reason:l.reason,detail:l.detail,source:l.source,type:l.type,kind:l.kind,envelopeId:l.envelopeId,priorEnvelopeId:l.priorEnvelopeId,target:l.target,deliveredTo:l.deliveredTo,hops:l.hops,seq:l.seq,correlationId:l.correlationId,causationId:l.causationId,idempotencyKey:l.idempotencyKey,schemaVersion:l.schemaVersion,payload:l.payload,turn:l.turn,time:l.time})},exportTrace(v){return O(),{schemaVersion:It,origin:m,redactedKeys:[...t],participants:se(E),tape:se(b),records:G(v),snapshots:se(H)}},report(v){O();let T=G(v);return{schemaVersion:It,participants:se(E),records:T,trees:Ln(T),dropped:i}},causationTree(v){O();let T=G(v?{correlationId:v}:void 0);return Ln(T)},records(){return O(),c.map(v=>se(v))},reset(){O(),c.length=0,b=[],i=0,s=0,H={},g&&(E=K(g))},destroy(){if(!a){for(a=!0,C();h.length>0;)h.pop()?.();c.length=0,b=[],E=[],H={},g=void 0}}};return z}async function bi(e,t,n={}){let r=Un({redactedKeys:n.redactedKeys??e.redactedKeys,maxRecords:n.maxRecords,registry:n.registry}),i=r.bind(t);try{for(let a of e.tape)a.kind==="publish"?i.publish(a.event,a.extras):a.kind==="dispatch"||a.kind==="asset"?i.dispatch(a.participantId,a.event):await i.step(a.frames);let s=await i.report();return{inspector:r,report:s}}catch(s){throw r.destroy(),s}}async function js(e,t){let n=e.captureComposedFrame();if(!t)return n;let{writeFile:r}=await import("node:fs/promises");return await r(t,Ve(n.pngDataUrl)),{...n,path:t}}export{En as DEFAULT_HEADLESS_HEIGHT,An as DEFAULT_HEADLESS_WIDTH,wn as HEADLESS_PNG_DATA_URL,j as HeadlessUnsupportedOperationError,xn as UPDATE_GOLDEN_ENV,kn as assertPixelsEqual,Kr as assertPngDataUrlsEqual,ut as attachHeadlessCanvas2D,Sn as compareImageData,fi as compareReplayTraces,Ut as createDefaultGlyphAtlas,Gr as createHeadlessHarness,ci as createHeadlessMultiCartHarness,Kn as createImageFixture,Un as createReplayInspector,ct as decodePng,Ae as encodePng,Ee as encodePngDataUrl,Vn as getHeadlessSurface,Rt as imageDataFromPngDataUrl,Qe as installHeadlessCanvas,he as makeImageData,bi as replayExportedTrace,ot as setDefaultGlyphAtlas,Rn as shouldUpdateGolden,js as writeComposedFrame,Wr as writeVisualArtifacts};
8
+ var Ir=Object.defineProperty;var on=(e,t)=>()=>(e&&(t=e(e=0)),t);var Tr=(e,t)=>{for(var n in t)Ir(e,n,{get:t[n],enumerable:!0})};var ei={};function Zr(e,t){let n=e.indexOf(Mn);if(n===-1)return null;let r=n+Mn.length,o=`const __cyberSkip=new Set(${JSON.stringify(t)});const __cyberOrig=registerProcessor;registerProcessor=(n,p)=>__cyberSkip.has(n)?undefined:__cyberOrig(n,p);`;return e.slice(0,r)+o+e.slice(r)}var Ht,nt,Qr,Ke,Mn,Fn=on(()=>{"use strict";Ht=/AudioWorkletProcessor with name:\s*["'`][^"'`]+["'`]\s+is already registered/i,nt="__cyberartWorkletPatchApplied";typeof window<"u"&&!window[nt]&&(window.addEventListener("error",e=>{let t=e?.message??"";Ht.test(t)&&(e.preventDefault(),e.stopImmediatePropagation())},!0),window.addEventListener("unhandledrejection",e=>{let t=e?.reason,n=typeof t=="string"?t:t?.message??"";Ht.test(n)&&e.preventDefault()}),window[nt]=!0);Qr=!1,Ke=(...e)=>{Qr&&console.log("[workletPatch]",...e)},Mn="((AudioWorkletProcessor,registerProcessor)=>{";if(typeof AudioWorklet<"u"&&!AudioWorklet.prototype[nt]){let e=new WeakMap,t=/registerProcessor\s*\(\s*['"`]([^'"`]+)['"`]/g,n=AudioWorklet.prototype.addModule,r=0;AudioWorklet.prototype.addModule=async function(o,s){let u=++r,f=e.get(this);f||(f=new Set,e.set(this,f)),Ke(`#${u} addModule`,{url:o.slice(0,64),isBlob:o.startsWith("blob:"),knownBefore:[...f]});let b=o,h=null;if(o.startsWith("blob:")){let m=null;try{m=await(await fetch(o)).text()}catch(A){Ke(`#${u} blob fetch failed`,A)}if(m!==null){let A=new Set;for(let D of m.matchAll(t))A.add(D[1]);if(A.size>0){let D=[...A].filter(v=>f.has(v)),x=[...A].filter(v=>!f.has(v));if(D.length>0&&x.length===0){Ke(`#${u} short-circuit \u2014 all processors already registered`,D);return}if(D.length>0&&x.length>0){let v=Zr(m,D);if(v!==null){let M=new Blob([v],{type:"application/javascript"});h=URL.createObjectURL(M),b=h,Ke(`#${u} rewrote blob; skipping`,D,"allowing",x)}else Ke(`#${u} blob rewrite failed; passing original through`)}x.forEach(v=>f.add(v))}}}return n.call(this,b,s).then(()=>{h&&URL.revokeObjectURL(h)},m=>{h&&URL.revokeObjectURL(h);let A=(m&&m.message)??"";if(!(Ht.test(A)||/already registered/i.test(A)))throw m})},AudioWorklet.prototype[nt]=!0}});var On={};Tr(On,{AUDIO_LIBRARIES:()=>Ot,adaptersFor:()=>ot,importTone:()=>rt,normalizeAudioLibraries:()=>it});async function rt(){let e=await import("tone");if(typeof e.start=="function")return e;let t=e.default;return t&&typeof t.start=="function"?t:e}function it(e){if(!e)return[];let t=Array.isArray(e)?e:[e],n=[];for(let r of t){if(!(r in Ot)){console.warn(`Unknown audio library "${r}"`);continue}let i=r;n.includes(i)||n.push(i)}return n}function ot(e){return e.map(t=>Ot[t])}var Hn,Ot,Lt=on(()=>{"use strict";Hn={id:"tone",async load(){await Promise.resolve().then(()=>(Fn(),ei))},async unlock(){await Hn.load(),await(await rt()).start()},async resumeIfSuspended(){let e=await rt();e.context.state==="suspended"&&await e.context.resume()},async suspendIfRunning(){let t=(await rt()).context.rawContext;"suspend"in t&&t.state==="running"&&await t.suspend()}},Ot={tone:Hn}});var Y=class extends Error{constructor(n,r){super(r?`Headless Canvas2D does not support ${n}: ${r}`:`Headless Canvas2D does not support ${n}`);this.name="HeadlessUnsupportedOperationError";this.operation=n}},we=class{constructor(t,n,r,i,o,s=0,u=0){this.stops=[];this.kind=t,this.x0=n,this.y0=r,this.x1=i,this.y1=o,this.r0=s,this.r1=u}addColorStop(t,n){if(!Number.isFinite(t)||t<0||t>1)throw new Y("addColorStop","offset must be in [0, 1]");this.stops.push({offset:t,color:Je(n)}),this.stops.sort((r,i)=>r.offset-i.offset)}colorAt(t){let n=t<0?0:t>1?1:t;if(this.stops.length===0)return{r:0,g:0,b:0,a:0};if(this.stops.length===1||n<=this.stops[0].offset)return this.stops[0].color;let r=this.stops[this.stops.length-1];if(n>=r.offset)return r.color;for(let i=1;i<this.stops.length;i++){let o=this.stops[i],s=this.stops[i-1];if(n<=o.offset){let u=o.offset-s.offset,f=u===0?0:(n-s.offset)/u;return Lr(s.color,o.color,f)}}return r.color}},wt={a:1,b:0,c:0,d:1,e:0,f:0},Pr={black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",blue:"#0000ff",cyan:"#00ffff",magenta:"#ff00ff",yellow:"#ffff00",gold:"#ffd700",orange:"#ffa500",navy:"#000080",gray:"#808080",grey:"#808080",transparent:"#00000000"},Re=new WeakMap,cn,sn=!1,xt=class{constructor(t,n,r,i){this.context=null;this.onDeviceReset=null;this.canvas=t,this.width=Math.max(0,n|0),this.height=Math.max(0,r|0),this.alpha=i.alpha!==!1,this.pixels=new Uint8ClampedArray(this.width*this.height*4),this.glyphAtlas=i.glyphAtlas??cn??mn(),this.alpha||this.fillOpaqueBlack()}resize(t,n,r=!1){let i=Math.max(0,t|0),o=Math.max(0,n|0);i!==this.width||o!==this.height?(this.width=i,this.height=o,this.pixels=new Uint8ClampedArray(i*o*4)):r&&this.pixels.fill(0),this.alpha||this.fillOpaqueBlack()}fillOpaqueBlack(){let t=this.pixels;for(let n=3;n<t.length;n+=4)t[n]=255}};function Dr(e,t,n){let r=n??new Uint8ClampedArray(e*t*4);if(r.length!==e*t*4)throw new Y("createImageFixture","data length must be width*height*4");return{__headlessImage:!0,width:e,height:t,data:r}}function Rt(e){cn=e}function Mr(e){return Re.get(e)}function It(e,t={}){let n=Re.get(e);if(n?.context)return n.context;let r=Math.max(0,Number(e.width)||0),i=Math.max(0,Number(e.height)||0),o=new xt(e,r,i,t);Re.set(e,o);let s=Fr(o);return o.context=s,s}function ln(e){let t=Re.get(e);if(t)return t.resize(e.width,e.height,!1),Te(t.width,t.height,t.pixels)}function Fr(e){let t={...wt},n=[],r="#000000",i="#000000",o={r:0,g:0,b:0,a:255},s={r:0,g:0,b:0,a:255},u=1,f="source-over",b=1,h="butt",m="10px sans-serif",A="start",D="alphabetic",x=null,v=!0,M=[],L=null,E=(d,y)=>{L={points:[c(d,y)],closed:!1},M.push(L)},S=(d,y)=>{if(!L){E(d,y);return}L.points.push(c(d,y))},g=()=>{if(!L||L.points.length===0)return;L.closed=!0;let d=L.points[0];L.points.push({x:d.x,y:d.y})},c=(d,y)=>({x:t.a*d+t.c*y+t.e,y:t.b*d+t.d*y+t.f}),a=()=>{if(f!=="source-over"&&f!=="copy")throw new Y("globalCompositeOperation",f)},k=()=>{e.resize(e.canvas.width,e.canvas.height,!1)},V=()=>{t={...wt},n.length=0,M.length=0,L=null,x=null,r="#000000",i="#000000",o={r:0,g:0,b:0,a:255},s={r:0,g:0,b:0,a:255},u=1,f="source-over",b=1,h="butt",m="10px sans-serif",A="start",D="alphabetic",v=!0};e.onDeviceReset=V;let B=(d,y,w,I=f)=>{if(d<0||y<0||d>=e.width||y>=e.height||x&&x[y*e.width+d]===0)return;let R=(y*e.width+d)*4,T=e.pixels;if(I==="copy"){T[R]=w.r,T[R+1]=w.g,T[R+2]=w.b,T[R+3]=e.alpha?w.a:255;return}let O=Math.round(w.a/255*u*255);if(O<=0)return;if(O>=255){T[R]=w.r,T[R+1]=w.g,T[R+2]=w.b,T[R+3]=255;return}let U=O/255,G=T[R+3]/255,z=U+G*(1-U);if(z<=0){T[R]=0,T[R+1]=0,T[R+2]=0,T[R+3]=e.alpha?0:255;return}T[R]=Math.round((w.r*U+T[R]*G*(1-U))/z),T[R+1]=Math.round((w.g*U+T[R+1]*G*(1-U))/z),T[R+2]=Math.round((w.b*U+T[R+2]*G*(1-U))/z),T[R+3]=e.alpha?Math.round(z*255):255},$=(d,y,w,I)=>{if(!(d instanceof we))return y;let R=Ye(t,w+.5,I+.5);return Or(d,R.x,R.y)},K=(d,y,w,I,R)=>{a(),k();let T=Et(d,e.width,e.height);if(T)for(let O=T.minY;O<=T.maxY;O++)for(let U=T.minX;U<=T.maxX;U++){let G=U+.5,z=O+.5;an(d,G,z,I)&&B(U,O,$(y,w,U,O),R)}},q=d=>{a(),k();let y=Math.sqrt(Math.abs(t.a*t.d-t.b*t.c)),w=b*(y===0?1:y)/2,I=Et(d,e.width,e.height,w+1);if(I)for(let R=I.minY;R<=I.maxY;R++)for(let T=I.minX;T<=I.maxX;T++)Nr(d,T+.5,R+.5,w,h)&&B(T,R,$(i,s,T,R))},p=(d,y)=>{if(d instanceof we){y==="fillStyle"?(r=d,o={r:0,g:0,b:0,a:255}):(i=d,s={r:0,g:0,b:0,a:255});return}if(typeof d!="string")throw new Y(y,String(d));let w=Je(d);y==="fillStyle"?(r=d,o=w):(i=d,s=w)},F={get canvas(){return e.canvas},get fillStyle(){return r},set fillStyle(d){p(d,"fillStyle")},get strokeStyle(){return i},set strokeStyle(d){p(d,"strokeStyle")},get globalAlpha(){return u},set globalAlpha(d){u=pn(d)},get globalCompositeOperation(){return f},set globalCompositeOperation(d){if(d!=="source-over"&&d!=="copy")throw new Y("globalCompositeOperation",d);f=d},get lineWidth(){return b},set lineWidth(d){b=Number.isFinite(d)&&d>0?d:1},get lineCap(){return h},set lineCap(d){if(d!=="butt"&&d!=="round"&&d!=="square")throw new Y("lineCap",String(d));h=d},get font(){return m},set font(d){m=d},get textAlign(){return A},set textAlign(d){if(d!=="start"&&d!=="left"&&d!=="center"&&d!=="right"&&d!=="end")throw new Y("textAlign",String(d));A=d},get textBaseline(){return D},set textBaseline(d){D=d},get imageSmoothingEnabled(){return v},set imageSmoothingEnabled(d){v=!!d},imageSmoothingQuality:"low",lineJoin:"miter",miterLimit:10,lineDashOffset:0,shadowBlur:0,shadowColor:"rgba(0, 0, 0, 0)",shadowOffsetX:0,shadowOffsetY:0,setGlyphAtlas(d){e.glyphAtlas=d},save(){n.push({transform:{...t},fillStyle:r,strokeStyle:i,fillStyleRaw:r,strokeStyleRaw:i,globalAlpha:u,globalCompositeOperation:f,lineWidth:b,lineCap:h,font:m,textAlign:A,textBaseline:D,clip:x?x.slice():null,imageSmoothingEnabled:v})},restore(){let d=n.pop();d&&(t=d.transform,r=d.fillStyleRaw,i=d.strokeStyleRaw,r instanceof we?o={r:0,g:0,b:0,a:255}:o=Je(r),i instanceof we?s={r:0,g:0,b:0,a:255}:s=Je(i),u=d.globalAlpha,f=d.globalCompositeOperation,b=d.lineWidth,h=d.lineCap,m=d.font,A=d.textAlign,D=d.textBaseline,x=d.clip,v=d.imageSmoothingEnabled)},beginPath(){M.length=0,L=null},closePath:g,moveTo:E,lineTo:S,rect(d,y,w,I){E(d,y),S(d+w,y),S(d+w,y+I),S(d,y+I),g()},quadraticCurveTo(d,y,w,I){let R=L?.points[L.points.length-1];if(!R){E(w,I);return}let T=Ye(t,R.x,R.y);Kr(T.x,T.y,d,y,w,I,16,(O,U)=>{L.points.push(c(O,U))})},bezierCurveTo(d,y,w,I,R,T){let O=L?.points[L.points.length-1];if(!O){E(R,T);return}let U=Ye(t,O.x,O.y);Vr(U.x,U.y,d,y,w,I,R,T,24,(G,z)=>{L.points.push(c(G,z))})},arc(d,y,w,I,R,T=!1){if(w<0)throw new Y("arc","negative radius");let O=un(d,y,w,I,R,T);if(O.length===0)return;let U=O[0];L?L.points.push(c(U.x,U.y)):E(U.x,U.y);for(let G=1;G<O.length;G++)L.points.push(c(O[G].x,O[G].y))},ellipse(d,y,w,I,R,T,O,U=!1){if(w<0||I<0)throw new Y("ellipse","negative radius");let G=un(0,0,1,T,O,U),z=Math.cos(R),Z=Math.sin(R);for(let X=0;X<G.length;X++){let se=G[X].x*w,ee=G[X].y*I,ce=d+se*z-ee*Z,ae=y+se*Z+ee*z;X===0&&!L?E(ce,ae):S(ce,ae)}},fill(d="nonzero"){K(At(M),r,o,d)},stroke(){q(At(M))},clip(d="nonzero"){let y=new Uint8Array(e.width*e.height),w=At(M),I=Et(w,e.width,e.height);if(I)for(let R=I.minY;R<=I.maxY;R++)for(let T=I.minX;T<=I.maxX;T++)an(w,T+.5,R+.5,d)&&(y[R*e.width+T]=1);if(!x){x=y;return}for(let R=0;R<x.length;R++)x[R]=x[R]&&y[R]?1:0},fillRect(d,y,w,I){K(H(d,y,w,I),r,o,"nonzero")},strokeRect(d,y,w,I){q(H(d,y,w,I))},clearRect(d,y,w,I){let R=e.alpha?{r:0,g:0,b:0,a:0}:{r:0,g:0,b:0,a:255};K(H(d,y,w,I),"#000000",R,"nonzero","copy")},fillText(d,y,w){j(String(d),y,w,r,o,!0)},strokeText(d,y,w){j(String(d),y,w,i,s,!1)},measureText(d){return{width:dn(String(d),m,e.glyphAtlas)}},translate(d,y){t=qe(t,{a:1,b:0,c:0,d:1,e:d,f:y})},rotate(d){let y=Math.cos(d),w=Math.sin(d);t=qe(t,{a:y,b:w,c:-w,d:y,e:0,f:0})},scale(d,y){t=qe(t,{a:d,b:0,c:0,d:y,e:0,f:0})},transform(d,y,w,I,R,T){t=qe(t,{a:d,b:y,c:w,d:I,e:R,f:T})},setTransform(d,y,w,I,R,T){if(d&&typeof d=="object"){t={a:d.a,b:d.b,c:d.c,d:d.d,e:d.e,f:d.f};return}t={a:Number(d)||0,b:Number(y)||0,c:Number(w)||0,d:Number(I)||0,e:Number(R)||0,f:Number(T)||0}},resetTransform(){t={...wt}},getTransform(){return{...t}},createLinearGradient(d,y,w,I){return new we("linear",d,y,w,I)},createRadialGradient(d,y,w,I,R,T){if(w<0||T<0)throw new Y("createRadialGradient","negative radius");return new we("radial",d,y,I,R,w,T)},createImageData(d,y){return typeof d=="object"?be(new Uint8ClampedArray(d.width*d.height*4),d.width,d.height):be(new Uint8ClampedArray(d*(y??0)*4),d,y??0)},getImageData(d,y,w,I){k();let R=d|0,T=y|0,O=w|0,U=I|0,G=new Uint8ClampedArray(O*U*4);for(let z=0;z<U;z++)for(let Z=0;Z<O;Z++){let X=R+Z,se=T+z,ee=(z*O+Z)*4;if(X<0||se<0||X>=e.width||se>=e.height)continue;let ce=(se*e.width+X)*4;G[ee]=e.pixels[ce],G[ee+1]=e.pixels[ce+1],G[ee+2]=e.pixels[ce+2],G[ee+3]=e.pixels[ce+3]}return be(G,O,U)},putImageData(d,y,w){k();let I=y|0,R=w|0,T=d.data;for(let O=0;O<d.height;O++)for(let U=0;U<d.width;U++){let G=I+U,z=R+O;if(G<0||z<0||G>=e.width||z>=e.height)continue;let Z=(O*d.width+U)*4,X=(z*e.width+G)*4;e.pixels[X]=T[Z],e.pixels[X+1]=T[Z+1],e.pixels[X+2]=T[Z+2],e.pixels[X+3]=e.alpha?T[Z+3]:255}},drawImage(d,...y){let w=Hr(d),I=0,R=0,T=w.width,O=w.height,U,G,z,Z;if(y.length===2)U=y[0],G=y[1],z=T,Z=O;else if(y.length===4)U=y[0],G=y[1],z=y[2],Z=y[3];else if(y.length===8)I=y[0],R=y[1],T=y[2],O=y[3],U=y[4],G=y[5],z=y[6],Z=y[7];else throw new Y("drawImage","invalid argument count");a(),k();let X=[c(U,G),c(U+z,G),c(U+z,G+Z),c(U,G+Z)],se=Math.max(0,Math.floor(Math.min(...X.map(Q=>Q.x)))),ee=Math.min(e.width-1,Math.ceil(Math.max(...X.map(Q=>Q.x)))),ce=Math.max(0,Math.floor(Math.min(...X.map(Q=>Q.y)))),ae=Math.min(e.height-1,Math.ceil(Math.max(...X.map(Q=>Q.y))));for(let Q=ce;Q<=ae;Q++)for(let ne=se;ne<=ee;ne++){let xe=Ye(t,ne+.5,Q+.5),Ee=(xe.x-U)/z,ve=(xe.y-G)/Z;if(Ee<0||ve<0||Ee>=1||ve>=1)continue;let l=Math.floor(I+Ee*T),C=Math.floor(R+ve*O);if(l<0||C<0||l>=w.width||C>=w.height)continue;let P=(C*w.width+l)*4;B(ne,Q,{r:w.data[P],g:w.data[P+1],b:w.data[P+2],a:w.data[P+3]})}},setLineDash(d){if(d.length>0)throw new Y("setLineDash","non-empty dash")},getLineDash(){return[]},createPattern(){throw new Y("createPattern")}};function H(d,y,w,I){let R=c(d,y),T=c(d+w,y),O=c(d+w,y+I),U=c(d,y+I);return[{closed:!0,points:[R,T,O,U,R]}]}function j(d,y,w,I,R,T){a();let O=e.glyphAtlas,U=fn(m),G=U/O.cellHeight,z=dn(d,m,O),Z=y;A==="center"?Z=y-z/2:(A==="right"||A==="end")&&(Z=y-z);let X=w;D==="top"||D==="hanging"?X=w:D==="middle"?X=w-U/2:X=w-U;let se=Z,ee=(O.cellWidth+1)*G;for(let ce of d){let ae=O.glyphs[ce]??O.glyphs[ce.toUpperCase()];if(!ae){se+=ee;continue}for(let Q=0;Q<O.cellHeight;Q++)for(let ne=0;ne<O.cellWidth;ne++){if(ae[Q*O.cellWidth+ne]===0)continue;if(!T){let re=ne===0||ae[Q*O.cellWidth+ne-1]===0,me=ne===O.cellWidth-1||ae[Q*O.cellWidth+ne+1]===0,Se=Q===0||ae[(Q-1)*O.cellWidth+ne]===0,ze=Q===O.cellHeight-1||ae[(Q+1)*O.cellWidth+ne]===0;if(!re&&!me&&!Se&&!ze)continue}let xe=se+ne*G,Ee=X+Q*G,ve=se+(ne+1)*G,l=X+(Q+1)*G,C=c(xe,Ee),P=c(ve,l),_=Math.max(0,Math.floor(Math.min(C.x,P.x))),N=Math.min(e.width-1,Math.ceil(Math.max(C.x,P.x))-1),W=Math.max(0,Math.floor(Math.min(C.y,P.y))),le=Math.min(e.height-1,Math.ceil(Math.max(C.y,P.y))-1);for(let re=W;re<=le;re++)for(let me=_;me<=N;me++)B(me,re,$(I,R,me,re))}se+=ee}}return new Proxy(F,{get(d,y,w){if(Reflect.has(d,y))return Reflect.get(d,y,w);if(typeof y=="symbol")return;let I=String(y);if(!(I==="then"||I==="toJSON"))return(...R)=>{throw new Y(I)}},set(d,y,w,I){if(y==="shadowBlur"&&w)throw new Y("shadowBlur");if((y==="shadowOffsetX"||y==="shadowOffsetY")&&w)throw new Y(String(y));if(y==="filter"&&w&&w!=="none")throw new Y("filter",String(w));if(Reflect.has(d,y))return Reflect.set(d,y,w,I);throw new Y(String(y))}})}function Hr(e){if(e&&typeof e=="object"&&"__headlessImage"in e){let t=e;return{width:t.width,height:t.height,data:t.data}}if(e&&typeof e=="object"&&"data"in e&&"width"in e&&"height"in e){let t=e;if(t.data instanceof Uint8ClampedArray)return{width:t.width,height:t.height,data:t.data}}if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement){let t=Re.get(e);if(!t)throw new Y("drawImage","source canvas has no headless surface");return{width:t.width,height:t.height,data:t.pixels}}throw new Y("drawImage","source must be ImageData, a headless canvas, or createImageFixture()")}function Or(e,t,n){if(e.kind==="linear"){let s=e.x1-e.x0,u=e.y1-e.y0,f=s*s+u*u,b=f===0?0:((t-e.x0)*s+(n-e.y0)*u)/f;return e.colorAt(b)}let r=Math.hypot(t-e.x1,n-e.y1),i=e.r1-e.r0,o=i===0?0:(r-e.r0)/i;return e.colorAt(o)}function Lr(e,t,n){return{r:Math.round(e.r+(t.r-e.r)*n),g:Math.round(e.g+(t.g-e.g)*n),b:Math.round(e.b+(t.b-e.b)*n),a:Math.round(e.a+(t.a-e.a)*n)}}function qe(e,t){return{a:e.a*t.a+e.c*t.b,b:e.b*t.a+e.d*t.b,c:e.a*t.c+e.c*t.d,d:e.b*t.c+e.d*t.d,e:e.a*t.e+e.c*t.f+e.e,f:e.b*t.e+e.d*t.f+e.f}}function Ye(e,t,n){let r=e.a*e.d-e.b*e.c;if(r===0)return{x:t,y:n};let i=e.d/r,o=-e.b/r,s=-e.c/r,u=e.a/r,f=(e.c*e.f-e.d*e.e)/r,b=(e.b*e.e-e.a*e.f)/r;return{x:i*t+s*n+f,y:o*t+u*n+b}}function At(e){return e.map(t=>({closed:t.closed,points:t.points.map(n=>({x:n.x,y:n.y}))}))}function Et(e,t,n,r=0){let i=1/0,o=1/0,s=-1/0,u=-1/0;for(let f of e)for(let b of f.points)i=Math.min(i,b.x),o=Math.min(o,b.y),s=Math.max(s,b.x),u=Math.max(u,b.y);return Number.isFinite(i)?{minX:Math.max(0,Math.floor(i-r)),minY:Math.max(0,Math.floor(o-r)),maxX:Math.min(t-1,Math.ceil(s+r)),maxY:Math.min(n-1,Math.ceil(u+r))}:null}function an(e,t,n,r){let i=0,o=0;for(let s of e){let u=s.points;if(!(u.length<2))for(let f=1;f<u.length;f++){let b=u[f-1],h=u[f],m=_r(b.x,b.y,h.x,h.y,t,n);i+=m,m!==0&&(o+=1)}}return r==="evenodd"?o%2===1:i!==0}function _r(e,t,n,r,i,o){if(t<=o==r<=o)return 0;let s=e+(o-t)/(r-t)*(n-e);return i<s?r>t?1:-1:0}function Nr(e,t,n,r,i){for(let o of e){let s=o.points;for(let u=1;u<s.length;u++){let f=s[u-1],b=s[u];if(i==="round"){if(Ur(t,n,f.x,f.y,b.x,b.y)<=r)return!0;continue}let h=b.x-f.x,m=b.y-f.y,A=Math.hypot(h,m);if(A===0){if(Math.hypot(t-f.x,n-f.y)<=r)return!0;continue}let D=h/A,x=m/A,v=f.x,M=f.y,L=b.x,E=b.y;i==="square"&&(v-=D*r,M-=x*r,L+=D*r,E+=x*r);let S=L-v,g=E-M,c=S*S+g*g,a=((t-v)*S+(n-M)*g)/c;if(a<0||a>1)continue;let k=v+a*S,V=M+a*g;if(Math.hypot(t-k,n-V)<=r)return!0}}return!1}function Ur(e,t,n,r,i,o){let s=i-n,u=o-r,f=s*s+u*u;if(f===0)return Math.hypot(e-n,t-r);let b=((e-n)*s+(t-r)*u)/f;return b=b<0?0:b>1?1:b,Math.hypot(e-(n+b*s),t-(r+b*u))}function Kr(e,t,n,r,i,o,s,u){for(let f=1;f<=s;f++){let b=f/s,h=1-b;u(h*h*e+2*h*b*n+b*b*i,h*h*t+2*h*b*r+b*b*o)}}function Vr(e,t,n,r,i,o,s,u,f,b){for(let h=1;h<=f;h++){let m=h/f,A=1-m,D=A*A,x=m*m;b(D*A*e+3*D*m*n+3*A*x*i+x*m*s,D*A*t+3*D*m*r+3*A*x*o+x*m*u)}}function un(e,t,n,r,i,o){let s=r,u=i;!o&&u<s&&(u+=Math.PI*2),o&&s<u&&(s+=Math.PI*2);let f=u-s,b=Math.max(8,Math.min(360,Math.ceil(Math.abs(f)*Math.max(n,1)))),h=[];for(let m=0;m<=b;m++){let A=s+f*m/b;h.push({x:e+Math.cos(A)*n,y:t+Math.sin(A)*n})}return h}function pn(e){return Number.isFinite(e)?e<0?0:e>1?1:e:1}function Je(e){let t=e.trim().toLowerCase(),r=Pr[t]??t;if(r==="transparent")return{r:0,g:0,b:0,a:0};if(r[0]==="#"){let o=r.slice(1);if(o.length===3)return{r:parseInt(o[0]+o[0],16),g:parseInt(o[1]+o[1],16),b:parseInt(o[2]+o[2],16),a:255};if(o.length===6)return{r:parseInt(o.slice(0,2),16),g:parseInt(o.slice(2,4),16),b:parseInt(o.slice(4,6),16),a:255};if(o.length===8)return{r:parseInt(o.slice(0,2),16),g:parseInt(o.slice(2,4),16),b:parseInt(o.slice(4,6),16),a:parseInt(o.slice(6,8),16)}}let i=r.match(/^rgba?\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)(?:\s*,\s*([0-9.]+))?\s*\)$/);if(i)return{r:Ct(Number(i[1])),g:Ct(Number(i[2])),b:Ct(Number(i[3])),a:i[4]===void 0?255:Math.round(pn(Number(i[4]))*255)};throw new Y("fillStyle",e)}function Ct(e){return Number.isFinite(e)?e<0?0:e>255?255:Math.round(e):0}function fn(e){let t=e.match(/([0-9]+(?:\.[0-9]+)?)px/);return t?Number(t[1]):10}function dn(e,t,n){let r=fn(t)/n.cellHeight;return e.length*(n.cellWidth+1)*r}function be(e,t,n){if(typeof ImageData=="function")try{return new ImageData(e,t,n)}catch{try{let r=new ImageData(t,n);return r.data.set(e),r}catch{}}return{data:e,width:t,height:n,colorSpace:"srgb"}}function mn(){let n={" ":new Uint8Array(35)},r={0:[14,17,19,21,25,17,14],1:[4,12,4,4,4,4,14],2:[14,17,1,2,4,8,31],3:[14,17,1,6,1,17,14],4:[2,6,10,18,31,2,2],5:[31,16,30,1,1,17,14],6:[14,16,30,17,17,17,14],7:[31,1,2,4,8,8,8],8:[14,17,17,14,17,17,14],9:[14,17,17,15,1,1,14],A:[14,17,17,31,17,17,17],B:[30,17,17,30,17,17,30],C:[14,17,16,16,16,17,14],D:[30,17,17,17,17,17,30],E:[31,16,16,30,16,16,31],F:[31,16,16,30,16,16,16],G:[14,17,16,23,17,17,14],H:[17,17,17,31,17,17,17],I:[14,4,4,4,4,4,14],K:[17,18,20,24,20,18,17],L:[16,16,16,16,16,16,31],M:[17,27,21,21,17,17,17],N:[17,25,21,19,17,17,17],O:[14,17,17,17,17,17,14],P:[30,17,17,30,16,16,16],R:[30,17,17,30,20,18,17],S:[15,16,16,14,1,1,30],T:[31,4,4,4,4,4,4],U:[17,17,17,17,17,17,14],V:[17,17,17,17,17,10,4],W:[17,17,17,21,21,21,10],Y:[17,17,10,4,4,4,4],Z:[31,1,2,4,8,16,31],".":[0,0,0,0,0,0,4],"-":[0,0,0,31,0,0,0],"+":[0,4,4,31,4,4,0],"*":[0,21,14,31,14,21,0],"!":[4,4,4,4,4,0,4],"?":[14,17,1,2,4,0,4],"/":[1,2,2,4,8,8,16],":":[0,4,0,0,0,4,0],"\u2713":[1,1,2,2,20,8,0]};for(let[i,o]of Object.entries(r)){let s=new Uint8Array(35);for(let u=0;u<7;u++)for(let f=0;f<5;f++)s[u*5+f]=o[u]&1<<4-f?1:0;n[i]=s,n[i.toLowerCase()]=s}return{cellWidth:5,cellHeight:7,glyphs:n}}var hn=new Uint32Array(256);for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;hn[e]=t>>>0}function Br(e){let t=4294967295;for(let n=0;n<e.length;n++)t=hn[(t^e[n])&255]^t>>>8;return(t^4294967295)>>>0}function Gr(e){let t=1,n=0;for(let r=0;r<e.length;r++)t=(t+e[r])%65521,n=(n+t)%65521;return(n<<16|t)>>>0}function Ne(e){return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,e&255])}function kt(e,t){let n=new Uint8Array(8+t.length+4);n.set(Ne(t.length),0),n[4]=e.charCodeAt(0),n[5]=e.charCodeAt(1),n[6]=e.charCodeAt(2),n[7]=e.charCodeAt(3),n.set(t,8);let r=n.subarray(4,8+t.length);return n.set(Ne(Br(r)),8+t.length),n}function $r(e){let t=[];for(let s=0;s<e.length;s+=65535){let u=e.subarray(s,Math.min(s+65535,e.length)),f=s+65535>=e.length,b=new Uint8Array(5+u.length);b[0]=f?1:0,b[1]=u.length&255,b[2]=u.length>>>8&255;let h=~u.length&65535;b[3]=h&255,b[4]=h>>>8&255,b.set(u,5),t.push(b)}t.length===0&&t.push(new Uint8Array([1,0,0,255,255]));let r=t.reduce((s,u)=>s+u.length,0),i=new Uint8Array(2+r+4);i[0]=120,i[1]=1;let o=2;for(let s of t)i.set(s,o),o+=s.length;return i.set(Ne(Gr(e)),o),i}function Ie(e,t,n){let r=e*4,i=new Uint8Array(t*(1+r));for(let m=0;m<t;m++){let A=m*(1+r);i[A]=0,i.set(n.subarray(m*r,(m+1)*r),A+1)}let o=new Uint8Array(13);o.set(Ne(e),0),o.set(Ne(t),4),o[8]=8,o[9]=6;let s=new Uint8Array([137,80,78,71,13,10,26,10]),u=[kt("IHDR",o),kt("IDAT",$r(i)),kt("IEND",new Uint8Array(0))],f=s.length+u.reduce((m,A)=>m+A.length,0),b=new Uint8Array(f);b.set(s,0);let h=s.length;for(let m of u)b.set(m,h),h+=m.length;return b}function Te(e,t,n){let r=Ie(e,t,n),i="";for(let o=0;o<r.length;o++)i+=String.fromCharCode(r[o]);return`data:image/png;base64,${globalThis.btoa(i)}`}function Tt(e){let t=[137,80,78,71,13,10,26,10];for(let b=0;b<8;b++)if(e[b]!==t[b])throw new Y("decodePng","invalid signature");let n=0,r=0,i=[],o=8;for(;o<e.length;){let b=e[o]<<24|e[o+1]<<16|e[o+2]<<8|e[o+3],h=String.fromCharCode(e[o+4],e[o+5],e[o+6],e[o+7]),m=e.subarray(o+8,o+8+b);if(h==="IHDR"){if(n=m[0]<<24|m[1]<<16|m[2]<<8|m[3],r=m[4]<<24|m[5]<<16|m[6]<<8|m[7],m[8]!==8||m[9]!==6)throw new Y("decodePng","only 8-bit RGBA is supported")}else if(h==="IDAT")for(let A=0;A<m.length;A++)i.push(m[A]);else if(h==="IEND")break;o+=12+b}let s=Wr(new Uint8Array(i)),u=n*4,f=new Uint8ClampedArray(n*r*4);for(let b=0;b<r;b++){let h=b*(1+u);if(s[h]!==0)throw new Y("decodePng",`unsupported scanline filter ${s[h]}`);f.set(s.subarray(h+1,h+1+u),b*u)}return be(f,n,r)}function Wr(e){if(e.length<6)throw new Y("decodePng","truncated zlib");let t=[],n=2;for(;n<e.length-4;){let s=e[n]&1;if((e[n]>>>1&3)!==0)throw new Y("decodePng","only stored deflate blocks are supported");n+=1;let f=e[n]|e[n+1]<<8;if(n+=4,t.push(e.subarray(n,n+f)),n+=f,s)break}let r=t.reduce((s,u)=>s+u.length,0),i=new Uint8Array(r),o=0;for(let s of t)i.set(s,o),o+=s.length;return i}function Xe(e){let t=e.indexOf(","),n=t>=0?e.slice(t+1):e,r=globalThis.atob(n),i=new Uint8Array(r.length);for(let o=0;o<r.length;o++)i[o]=r.charCodeAt(o);return i}function gn(){if(!sn){sn=!0;for(let e of["width","height"]){let t=Object.getOwnPropertyDescriptor(HTMLCanvasElement.prototype,e);if(!t?.set||!t.get)continue;let n=t.set;Object.defineProperty(HTMLCanvasElement.prototype,e,{configurable:!0,enumerable:t.enumerable,get:t.get,set(r){n.call(this,r);let i=Re.get(this);i&&(i.resize(this.width,this.height,!0),i.onDeviceReset?.())}})}}}var yn=()=>{let e=["ms","moz","webkit","o"];for(let t=0;t<e.length&&!window.requestAnimationFrame;++t)window.requestAnimationFrame=window[e[t]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[e[t]+"CancelAnimationFrame"]||window[e[t]+"CancelRequestAnimationFrame"]},fe=window.devicePixelRatio||1,Pe=/Headless/i.test(navigator.userAgent),_o=/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)||/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform);function bn(){return Math.min(window.innerWidth,window.innerHeight)}var Pt="data-cyberart-canvas",De=class{constructor(t,n,r=1,i={}){this.width=t,this.height=n;let o=i.container,s=i.adoptFromDocument??!o,u=o?o.querySelector(`canvas[${Pt}]`)??o.querySelector("canvas"):null;if(u)this.canvas=u,this.adopted=!0;else if(s){let f=document.getElementById("canvas")??document.querySelector("canvas");f?(this.canvas=f,this.adopted=!0):(this.canvas=document.createElement("canvas"),this.canvas.setAttribute("id","canvas"),this.adopted=!1)}else this.canvas=document.createElement("canvas"),this.adopted=!1;this.canvas.hasAttribute(Pt)||this.canvas.setAttribute(Pt,""),this.canvas.style.display="block",this.canvas.style.margin="auto",this.ctx=this.canvas.getContext("2d",{colorSpace:"display-p3",alpha:!1}),this.ctx.globalAlpha=r,this.ctx.imageSmoothingEnabled=!1,this.setSize(t,n)}setSize(t,n){this.width=t,this.height=n,this.canvas.width=t,this.canvas.height=n,this.canvas.style.width=`${t/fe}px`,this.canvas.style.height=`${n/fe}px`,this.imageData=this.ctx.createImageData(t,n),this.ctx.putImageData(this.imageData,0,0)}_blank(t=1){let n=t?Math.max(t,.03):1;this.ctx.fillStyle=`rgba(0,0,0,${n})`,this.ctx.fillRect(0,0,this.width,this.height)}clearAll(){this.ctx.save(),this.ctx.globalAlpha=1,this._blank(),this.ctx.restore()}};function vn(e,t){let n=e/t,r,i;return n>1?(r=e,i=~~(e/n)):(i=t,r=~~(t*n)),{width:r,height:i,iWidth:1/r,iHeight:1/i,area:r*i,largeDim:Math.max(r,i),smallDim:Math.min(r,i),aspectRatio:n}}function Sn(e,t=window.innerWidth,n=window.innerHeight){let r=bn(),i,o;return n<t?e>1?t>=r*e?(i=r*e,o=r):(i=t,o=i/e):(i=r*e,o=r):e>1?(i=r,o=r/e):n<r/e?(o=n,i=o*e):(i=r,o=r/e),[i,o]}var Dt=class{constructor(t=!1,n=!0){this.debugMode=t,this.actionMap={},this.listening=n,this.checkKeypress=this.checkKeypress.bind(this),this.registerAction=this.registerAction.bind(this),this.listening&&window.addEventListener("keydown",this.checkKeypress,!1)}checkKeypress({key:t}){this.debugMode&&console.log(`Pressed ${t}`),t in this.actionMap&&this.actionMap[t]()}inject(t){this.checkKeypress({key:t})}registerAction(t,n,r=!1){if(t.length!==1)throw new Error(`Only single-character actions may be registered. Cannot register: ${t}`);if(t in this.actionMap&&!r)throw new Error(`Action already exists for code: ${t}`);this.actionMap[t]=n}destroy(){this.listening&&window.removeEventListener("keydown",this.checkKeypress,!1),this.actionMap={}}},wn=Dt;var Mt=class{constructor(t,n={}){this.x=-1;this.y=-1;this.isDown=!1;this.clicks=[];this.canvas=t,this.listening=n.listen!==!1,this.onPointerDown=this.onPointerDown.bind(this),this.onPointerMove=this.onPointerMove.bind(this),this.onPointerUp=this.onPointerUp.bind(this),this.listening&&(t.addEventListener("pointerdown",this.onPointerDown),t.addEventListener("pointermove",this.onPointerMove),t.addEventListener("pointerup",this.onPointerUp))}toCanvasCoords(t){let n=this.canvas.getBoundingClientRect();return{x:(t.clientX-n.left)*(this.canvas.width/n.width),y:(t.clientY-n.top)*(this.canvas.height/n.height)}}onPointerDown(t){let{x:n,y:r}=this.toCanvasCoords(t);this.x=n,this.y=r,this.isDown=!0,this.clicks.push({x:n,y:r})}onPointerMove(t){let{x:n,y:r}=this.toCanvasCoords(t);this.x=n,this.y=r}onPointerUp(t){let{x:n,y:r}=this.toCanvasCoords(t);this.x=n,this.y=r,this.isDown=!1}hasClick(){return this.clicks.length>0}consumeClick(){return this.clicks.shift()??null}inject(t,n,r){this.x=n,this.y=r,t==="down"?(this.isDown=!0,this.clicks.push({x:n,y:r})):t==="up"&&(this.isDown=!1)}destroy(){this.listening&&(this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp))}},An=Mt;function Qe(){return{now:()=>performance.now()}}function En(e=0){let t=e;return{now:()=>t,set(n){t=n},advance(n){t+=n}}}var Cn=(e,t,n,r)=>({now:e,startTime:t,elapsedSinceStart:e-t,deltaSinceLastUpdate:n===null?0:e-n,deltaSinceLastRender:r===null?0:e-r}),Ze=class{constructor(t,n,r,i,o,s={}){this.startTime=0;this.lastUpdateAt=null;this.lastRenderAt=null;this.clockOffsetMs=0;this.pauseStartedAt=null;this.renderAnimation=this.renderAnimation.bind(this),this.dimensionContext=vn(t,n),this.R=r,this.gameManager=s.gameManager,this.hostChannel=s.hostChannel,this.clock=s.clock??Qe(),this.canvas=new De(this.dimensionContext.width,this.dimensionContext.height,1,s.canvasMount),this.drawingContext=this.canvas.ctx,this.keyboardManager=new wn(!1,s.captureKeyboard??!0),this.pointerManager=new An(this.canvas.canvas,{listen:s.listenToPointer!==!1}),this.animationCart=o;let u=s.customState;this.featureState=o.getDefaultFeatureState?.(this.R,this.dimensionContext,i,this.keyboardManager,u,this.pointerManager,this.gameManager,this.hostChannel),this.cartState=o.getDefaultState(this.R,this.dimensionContext,i,this.keyboardManager,u,this.pointerManager,this.gameManager,this.featureState,this.hostChannel),this.startTime=this.clock.now(),this.canvas.clearAll()}captureFramebuffer(){let t=this.canvas.imageData,n=new ImageData(t.width,t.height);return n.data.set(t.data),n}restoreFramebuffer(t){let n=this.canvas.imageData;return n.width!==t.width||n.height!==t.height||n.data.length!==t.data.length?!1:(n.data.set(t.data),this.drawingContext.putImageData(n,0,0),!0)}setPaused(t){let n=this.clock.now();if(t){this.pauseStartedAt===null&&(this.pauseStartedAt=n);return}this.pauseStartedAt!==null&&(this.clockOffsetMs+=n-this.pauseStartedAt,this.pauseStartedAt=null)}resolveNow(t){let n=this.pauseStartedAt!==null?t-this.pauseStartedAt:0;return t-this.clockOffsetMs-n}getElapsedSinceStart(t=this.clock.now()){return Math.max(0,this.resolveNow(t)-this.startTime)}restoreClock(t,n){this.pauseStartedAt=null,this.lastUpdateAt=null,this.lastRenderAt=null;let r=Math.max(0,t);if(typeof n=="number"&&Number.isFinite(n)){this.startTime=n,this.clockOffsetMs=this.clock.now()-n-r;return}this.clockOffsetMs=0,this.startTime=this.clock.now()-r}getRandomState(){return this.R.getState()}injectKey(t){this.keyboardManager.inject(t)}injectPointer(t,n,r){this.pointerManager.inject(t,n,r)}async updateAnimationState(t,n,r=this.clock.now()){let i=this.resolveNow(r),o=Cn(i,this.startTime,this.lastUpdateAt,this.lastRenderAt);this.cartState=this.animationCart.update(this.R,t,n,this.dimensionContext,this.cartState,this.keyboardManager,this.pointerManager,this.gameManager,o,this.featureState,this.hostChannel),this.lastUpdateAt=i}async renderAnimation(t,n,r=this.clock.now()){let i=this.resolveNow(r),o=Cn(i,this.startTime,this.lastUpdateAt,this.lastRenderAt);this.animationCart.render(this.R,t,n,this.dimensionContext,this.cartState,this.drawingContext,this.canvas.imageData,this.pointerManager,this.gameManager,o,this.featureState,this.hostChannel),this.lastRenderAt=i}getCanvas(){return this.canvas.canvas}getDrawDetails(){return[this.canvas.canvas,0,0,this.dimensionContext.width,this.dimensionContext.height]}teardown(){try{this.animationCart.teardown?.(this.cartState,this.featureState)}catch(t){console.error("Error during cart teardown",t)}this.keyboardManager.destroy(),this.pointerManager.destroy()}};var et=class extends De{constructor(t,n,r=1,i=!0,o={}){if(super(t,n,r,o),this.adopted)return;let s=o.container;if(s){this.canvas.parentNode!==s&&s.appendChild(this.canvas);return}if(i){let u=document.getElementById("canvas");u&&u!==this.canvas&&u.parentNode===document.body&&document.body.removeChild(u),document.body.appendChild(this.canvas)}}};function kn(e){let t=parseInt(e.substring(0,8),16),n=parseInt(e.substring(8,8),16),r=parseInt(e.substring(16,8),16),i=parseInt(e.substring(24,8),16);return{next:()=>{t|=0,n|=0,r|=0,i|=0;let s=(t+n|0)+i|0;return i=i+1|0,t=n^n>>>9,n=r+(r<<3)|0,r=r<<21|r>>>11,r=r+s|0,(s>>>0)/4294967296},getRegs:()=>({a:t,b:n,c:r,d:i}),setRegs:s=>{t=s.a,n=s.b,r=s.c,i=s.d}}}var tt=class{constructor(t){this.seed=t.hash,this.useA=!1,this.genA=kn(t.hash.substring(2,32)),this.genB=kn(t.hash.substring(34,32)),this.prngA=this.genA.next,this.prngB=this.genB.next;for(let n=0;n<1e6;n+=2)this.prngA(),this.prngB()}getState(){let t=this.genA.getRegs(),n=this.genB.getRegs();return{seed:this.seed,useA:this.useA,prngA:{a:t.a,b:t.b,c:t.c,d:t.d},prngB:{a:n.a,b:n.b,c:n.c,d:n.d}}}setState(t){if(t.seed!==this.seed)throw new Error(`Random.setState: seed ${t.seed} does not match ${this.seed}`);this.useA=t.useA,this.genA.setRegs(t.prngA),this.genB.setRegs(t.prngB)}r_zero_one(){return this.useA=!this.useA,this.useA?this.prngA():this.prngB()}dec(t,n){return t===void 0?this.r_zero_one():n===void 0?t*this.r_zero_one():t+(n-t)*this.r_zero_one()}int(t,n){return n===void 0&&(n=t,t=0),Math.floor(this.dec(t,n))}bool(t=.5){return this.r_zero_one()<t}sign(){return this.bool()?1:-1}choose(t){return t[this.int(t.length)]}};var In="bafybeicjwcq5lxxtfnyj4p2ugcr7ctyb5wl62cbcechj6tsabdq5whcs7u",xn="https://ipfs.io/ipfs/";function jr(e){return e.endsWith("/")?e:`${e}/`}var Ue=null;function zr(e){return[...Array(e)].map(()=>Math.floor(Math.random()*16).toString(16)).join("")}function qr(e){return e&&e.length>0?e:[{cid:In}]}function Yr(e){return e.startsWith("0x")?e:`0x${e}`}var Tn=/^(0[xX])?[0-9a-fA-F]{64}$/;function Jr(e){let t="",n=2166136261,r=522970236;for(let i=0;t.length<64;i++){for(let o=0;o<e.length;o++)n^=e.charCodeAt(o)+i,n=Math.imul(n,16777619),r^=e.charCodeAt(o)+i*17,r=Math.imul(r,16777619);t+=(n>>>0).toString(16).padStart(8,"0"),t+=(r>>>0).toString(16).padStart(8,"0")}return`0x${t.slice(0,64)}`}function Rn(e){let t=typeof e=="number"?String(e):e;return Tn.test(t)?`0x${(t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t).toLowerCase()}`:Jr(t)}function Pn(e,t){if(typeof e=="number"||t==="deterministic")return Rn(e);let n=String(e);return Tn.test(n)?Rn(n):n.startsWith("0x")||n.startsWith("0X")?n:`0x${n}`}function Xr(e){if(!e&&typeof tokenData<"u"&&tokenData?.hash)return{hash:tokenData.hash,tokenId:String(tokenData.tokenId),externalAssetDependencies:qr(tokenData.externalAssetDependencies),preferredIPFSGateway:jr(tokenData.preferredIPFSGateway||xn),preferredArweaveGateway:tokenData.preferredArweaveGateway};let t=typeof window<"u"?new URLSearchParams(window.location.search):new URLSearchParams;return{hash:e?Yr(e):t.get("hash")||`0x${zr(64)}`,tokenId:"18009999",externalAssetDependencies:[{cid:In}],preferredIPFSGateway:xn}}function Ft(e){let t=e?.useCache!==!1;if(t&&Ue&&!e?.hash)return Ue;let n=Xr(e?.hash);return t?Ue=n:Ue||(Ue=n),n}function Dn(e){return new Array(32).fill(null).map((t,n)=>parseInt(e.hash.slice(2+n*2,4+n*2),16))}Lt();var st="$cyberartTa",oe=class extends Error{constructor(t){super(t),this.name="IncompatibleCartStateError"}},_t={Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array};function ti(e){for(let t of Object.keys(_t))if(e instanceof _t[t])return t}function Nn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function he(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Nt(e){return he(e)?typeof e[st]=="string"&&Array.isArray(e.d):!1}function ni(e){return e==null?!1:typeof e=="function"?!0:!(typeof e!="object"||Array.isArray(e)||Nn(e)||he(e))}var ri=new Set(["audioContextStarted","midiSynths","keepRatioPrimed","audioInitStarted","musicSeekApplied"]);function Ln(e){return e===null?"null":Nt(e)?String(e[st]):Array.isArray(e)?"array":he(e)?"object":typeof e}function ii(e,t){return e===t||e==="null"||t==="null"}function _n(e){return e.trim().toLowerCase().replace(/^0x/,"")}function Un(e,t,n,r){if(!(!n&&!r)&&_n(e)!==_n(t))throw new oe(`Generative cart state is for seed "${t}", but the live token is "${e}"`)}function Me(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function Kn(e,t){let n=e.dimensions;if(n&&Me(n.width)&&Me(n.height))return n;if(t&&Me(t.width)&&Me(t.height))return{width:t.width,height:t.height};if(he(e.state)){let r=e.state.containerWidth,i=e.state.containerHeight;if(Me(r)&&Me(i))return{width:r,height:i}}return null}function Fe(e,t=new WeakSet){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)?e:null;if(!(typeof e=="function"||typeof e>"u"||typeof e=="bigint"||typeof e=="symbol")){if(Nn(e)){let n=ti(e);return n?{[st]:n,d:Array.from(e)}:void 0}if(typeof e=="object"&&!t.has(e)){t.add(e);try{if(Array.isArray(e)){let i=[],o=0;for(let s of e){let u=Fe(s,t);u!==void 0&&(i.push(u),o++)}return e.length>0&&o===0?void 0:i}if(!he(e)||ni(e))return;let n=Object.keys(e),r={};for(let i of n){if(ri.has(i))continue;let o=Fe(e[i],t);o!==void 0&&(r[i]=o)}return n.length>0&&Object.keys(r).length===0?void 0:r}finally{t.delete(e)}}}}function Ve(e){if(Nt(e)){let t=_t[e[st]];return t?new t(e.d.map(n=>Number(n))):e}if(Array.isArray(e))return e.map(t=>Ve(t));if(he(e)){let t={};for(let n of Object.keys(e))t[n]=Ve(e[n]);return t}return e}function Ut(e,t,n,r,i=!0){if(i&&n&&r&&n!==r)throw new oe(`Cart state is for "${r}", but the live cart is "${n}"`);if(!he(t)){if(i)throw new oe("Cart state snapshot is empty");return}let o=Object.keys(t);if(o.length===0){if(i)throw new oe("Cart state snapshot is empty");return}let s=Fe(e);if(!he(s)||Object.keys(s).length===0){if(i)throw new oe("Live cart has no serializable state");return}let u=o.filter(f=>f in s);if(u.length===0){if(i)throw new oe("Cart state snapshot does not overlap the live cart shape");return}for(let f of u){let b=Ln(s[f]),h=Ln(t[f]);if(!ii(b,h))throw new oe(`Cart state field "${f}" has type ${h}, live cart expects ${b}`);if(b==="object"){let m=t[f],A=e[f];he(m)&&!Nt(m)&&Ut(A,m,void 0,void 0,!1)}}}function Vn(e,t){if(!he(e)||!he(t))return;let n=Fe(e);if(he(n))for(let r of Object.keys(t))r in n&&(e[r]=Ve(t[r]))}function ge(e){let t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")throw new oe("Cart state bundle is not an object");if(t.version!==1)throw new oe(`Unsupported cart state version ${String(t.version)}`);if(typeof t.seed!="string"||typeof t.framesElapsed!="number")throw new oe("Cart state bundle is missing seed or framesElapsed");return t}var Ce="cyberart.asset.ready",ke="cyberart.asset.failed";function Ae(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function Bn(e){return{type:e.status==="ready"?Ce:ke,kind:"state",payload:e.detail===void 0?{id:e.id}:{id:e.id,detail:e.detail}}}function si(e){if(!e||typeof e!="object")return 0;let t=e;return typeof t.startTime=="number"&&typeof t.lastSimulationUpdateAt=="number"?Math.max(0,t.lastSimulationUpdateAt-t.startTime):0}function ai(e,t){if(typeof window.resizeTo!="function")return!1;try{if(window.top!==window)return!1}catch{return!1}let n=Math.max(1,Math.round(e)),r=Math.max(1,Math.round(t)),i=Math.max(0,window.outerWidth-window.innerWidth),o=Math.max(0,window.outerHeight-window.innerHeight);try{window.resizeTo(n+i,r+o)}catch{return!1}return Math.abs(window.innerWidth-n)<=8&&Math.abs(window.innerHeight-r)<=8}var ui=[[0,0],[16,9],[9,16],[4,3],[3,4],[2,1],[1,2],[3,1],[1,3],[1,1]],Vt=ui[0],di=Vt[0]/Vt[1],Kt=30,ci=120,li=3840/2160,pi=2160/3840,at=class{constructor(t=Kt,n=!1,r=window.innerWidth,i=window.innerHeight,o=!0,s,u={}){this.framesElapsed=0;this.frameRate=Kt;this._paused=!1;this.savedToken=!1;this.prepared=!1;this.loopRunning=!1;this.fallbackAudio=[];this.audioLibrariesInternal=[];this.virtualClock=null;this.scriptedActions=[];this.initialScriptedActions=[];this.appliedActions=[];this.consumedActionIndexes=new Set;this.outboundEvents=[];this.consecutiveErrorCount=0;this.lastErrorLogAt=0;this.reinitStayPaused=!1;this.reinitPending=!1;this.lastExportedFramebuffer=null;this.pinnedOutput=null;this.pinViewportAtImport=null;this.importing=!1;this.drawLoop=this.drawLoop.bind(this),this.loadCart=this.loadCart.bind(this),this.prepareCart=this.prepareCart.bind(this),this.beginPlayback=this.beginPlayback.bind(this),this.reinit=this.reinit.bind(this),this.tuneFramerate=this.tuneFramerate.bind(this),this.container=u.container,this.seed=u.seed,this.captureKeyboard=u.captureKeyboard??!0,this.customState=u.customState,this.hostChannel=u.hostChannel,this.fallbackAudio=it(u.audio),this.audioLibrariesInternal=this.fallbackAudio;let f=u.deterministic;this.deterministic=!!f;let b=f&&typeof f=="object"?f:{};if(this.deterministic){if(u.clock){let h=u.clock;if(typeof h.advance!="function")throw new Error("deterministic mode requires a virtual clock with advance()");this.virtualClock=h,this.clock=h}else this.virtualClock=En(b.origin??0),this.clock=this.virtualClock;this.initialScriptedActions=Ae(b.actions??[]),this.scriptedActions=Ae(this.initialScriptedActions)}else this.clock=u.clock??Qe();this.isBodyCanvas=this.container?!1:o,this.autoMode=n,this.aspectRatio=di,this.selectedAsp=Vt,this.isFullscreen=!!document.fullscreenElement,this.updateFrameRate(t),this.tempUnpause=!1,this.synchronous=Pe,this.containerWidth=r,this.containerHeight=i,this.gameManager=s,this.init(!0)}setGameManager(t){this.gameManager=t}reinit(t){if(!this.importing){if(this.shouldKeepPinnedOutput()){this.fitPinnedCanvas();return}this.reinitPending||(this.reinitStayPaused=this._paused,this.reinitPending=!0),this.paused=!0,clearTimeout(this.reinitTimeout),this.reinitTimeout=setTimeout(()=>{if(this.importing){this.paused=this.reinitStayPaused,this.reinitPending=!1;return}this.updateInProgress?this.reinit(t):(this.requestedAnimationFrame&&cancelAnimationFrame(this.requestedAnimationFrame),this.clearPinnedOutput(),this.init(),this.reloadCart(),this.paused=this.reinitStayPaused,this.reinitPending=!1)},150)}}initSeed(){this.tokenData=this.seed?Ft({hash:this.seed,useCache:!1}):Ft(),this.rawParams=Dn(this.tokenData),this.mintNo=parseInt(this.tokenData.tokenId)%1e6,console.log("token",this.mintNo,this.tokenData.hash)}init(t=!1){t&&this.initSeed(),this.pureAspectUpdate(this.selectedAsp);let n=this.aspectRatio,[r,i]=Sn(n,this.containerWidth,this.containerHeight);r*=fe,i*=fe,this.width=~~r,this.height=~~i,this.atCenterX=this.width/2,this.atCenterY=this.height/2,this.mainCanvas?this.mainCanvas.setSize(this.width,this.height):this.mainCanvas=new et(this.width,this.height,1,this.isBodyCanvas,this.canvasMountOptions())}loadCart(t){this.prepareCart(t)&&this.beginPlayback()}prepareCart(t){if(this.prepared)return!0;try{let n=~~(this.width/1),r=~~(this.height/this.width*n),i=new tt(this.tokenData),o=new Ze(n,r,i,this.rawParams,t,{gameManager:this.gameManager,canvasMount:this.canvasMountOptions(),customState:this.customState,captureKeyboard:this.deterministic?!1:this.captureKeyboard,hostChannel:this.hostChannel,clock:this.clock,listenToPointer:!this.deterministic});return this.animation=o,this.animationCart=t,this.paused=!1,this.framesElapsed=0,this.outboundEvents=[],this.scriptedActions=Ae(this.initialScriptedActions),this.appliedActions=[],this.consumedActionIndexes=new Set,this.outboundUnsubscribe?.(),this.outboundUnsubscribe=void 0,this.deterministic&&this.hostChannel&&(this.outboundUnsubscribe=this.hostChannel.onEvent(s=>{this.outboundEvents.push(s)})),this.R=i,this.applyCartFrameRate(t,o),this.resolveAudioLibraries(t),this.prepared=!0,!0}catch(n){return console.error(n),!1}}applyCartFrameRate(t,n){let r=t.metadata,i=r?.frameRate??Kt,o=n.cartState?.visualMode??n.featureState?.visualMode,s=o&&r?.frameRateByVisualMode?r.frameRateByVisualMode[o]:void 0;this.updateFrameRate(typeof s=="number"&&s>0?s:i)}get audioLibraries(){return this.audioLibrariesInternal}get needsAudio(){return this.audioLibrariesInternal.length>0}resolveAudioLibraries(t){this.audioLibrariesInternal=it(t.metadata?.audio)}async unlockAudio(){if(this.audioLibrariesInternal.length===0)return;let t=ot(this.audioLibrariesInternal);if(Pe){for(let n of t)await n.load();return}for(let n of t)await n.unlock()}async resumeAudioLibraries(){if(!(this.paused||Pe))for(let t of ot(this.audioLibrariesInternal))try{await t.resumeIfSuspended()}catch(n){console.error(`Failed to resume audio library "${t.id}" after reload`,n)}}beginPlayback(){!this.prepared||this.loopRunning||(this.prepared=!1,this.loopRunning=!0,this.consecutiveErrorCount=0,!this.deterministic&&(this.requestedAnimationFrame=requestAnimationFrame(this.drawLoop)))}get isPrepared(){return this.prepared}get isLoopRunning(){return this.loopRunning}get isDeterministic(){return this.deterministic}getClock(){return{now:this.clock.now(),framesElapsed:this.framesElapsed,frameRate:this.frameRate}}getRandomState(){return this.requirePreparedAnimation().getRandomState()}schedule(t){this.scriptedActions.push(Ae(t))}async getReplayMetadata(){let t=await this.exportState();return{seed:this.tokenData.hash,clock:this.getClock(),rng:this.getRandomState(),actions:Ae(this.scriptedActions),applied:Ae(this.appliedActions),events:Ae(this.outboundEvents),state:t.state}}async step(t=1){if(!this.deterministic)throw new Error("step() requires createRuntime({ deterministic: true })");this.requirePreparedAnimation(),this.prepared&&!this.loopRunning&&this.beginPlayback(),this.paused=!1;let n=Math.max(0,Math.floor(t));for(let r=0;r<n&&this.animation;r++){let i=this.framesElapsed;if(this.applyScheduledActions(i),await this.processFrame(this.clock.now(),{ignorePause:!0,scheduleNext:!1}),this.framesElapsed===i||(this.virtualClock?.advance(this.targetDrawTime),!this.loopRunning))break}}async advance(t){let n=Math.max(0,Math.round(t/this.targetDrawTime));await this.step(n)}applyScheduledActions(t){let n=this.animation;n&&this.scriptedActions.forEach((r,i)=>{r.atFrame===t&&(this.consumedActionIndexes.has(i)||(this.consumedActionIndexes.add(i),r.type==="pointer"?n.injectPointer(r.pointer.kind,r.pointer.x,r.pointer.y):r.type==="key"?n.injectKey(r.key):r.type==="event"?this.hostChannel?.dispatch(r.event):r.type==="asset"&&this.hostChannel?.dispatch(Bn(r)),this.appliedActions.push({frame:t,action:r})))})}get paused(){return this._paused}set paused(t){this._paused!==t&&(this._paused=t,this.animation?.setPaused(t))}async waitUntilUpdateIdle(){for(;this.updateInProgress;)await new Promise(t=>{this.deterministic?queueMicrotask(t):typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>t()):setTimeout(t,0)})}requirePreparedAnimation(){if(!this.animation)throw new Error("No prepared cart");return this.animation}async exportState(){let t=this.requirePreparedAnimation(),n=this._paused;this.paused=!0,await this.waitUntilUpdateIdle();try{this.lastExportedFramebuffer=t.captureFramebuffer();let r=t.getCanvas();return{version:1,cartId:this.animationCart?.metadata?.id,generative:this.animationCart?.metadata?.generative,seed:this.tokenData.hash,framesElapsed:this.framesElapsed,elapsedSinceStart:t.getElapsedSinceStart(),dimensions:{width:r.width,height:r.height,cssWidth:this.containerWidth,cssHeight:this.containerHeight,dpr:fe},state:Fe(t.cartState)}}finally{this.paused=n}}async exportStateJSON(){return JSON.stringify(await this.exportState())}peekExportedFramebuffer(){return this.lastExportedFramebuffer}peekSeed(){return this.tokenData?.hash}isGenerative(){return this.animationCart?.metadata?.generative===!0}async importState(t,n){let r=this.requirePreparedAnimation(),i=ge(t),o=this._paused,s=this.loopRunning;this.paused=!0,await this.waitUntilUpdateIdle(),Ut(r.cartState,i.state,this.animationCart?.metadata?.id,i.cartId),Un(this.tokenData.hash,i.seed,this.animationCart?.metadata?.generative,i.generative),clearTimeout(this.reinitTimeout),this.reinitPending=!1,this.importing=!0;let u=Kn(i,n?.framebuffer??this.lastExportedFramebuffer);if(u){this.pinOutputSize(u);let h=u.cssWidth??u.width/fe,m=u.cssHeight??u.height/fe;ai(h,m),this.syncContainerFromDom(),this.pinViewportAtImport={w:this.containerWidth,h:this.containerHeight}}let f=this.customState,b=!1;try{if(this.customState=Ve(i.state),this.unloadCart(),!this.prepareCart(this.animationCart))throw new Error("Failed to prepare cart while loading state");this.animation.cartState!==this.customState&&Vn(this.animation.cartState,i.state),this.framesElapsed=i.framesElapsed;let h=this.animation,m=h.cartState,A=typeof i.elapsedSinceStart=="number"?i.elapsedSinceStart:si(m);h.restoreClock(A,typeof m?.startTime=="number"?m.startTime:void 0),o&&h.setPaused(!0);let D=n?.framebuffer??this.lastExportedFramebuffer;D&&h.restoreFramebuffer(D)?m.keepRatioPrimed=!0:await h.renderAnimation(this.framesElapsed,this.rawParams),this.fitPinnedCanvas(),b=!0}catch(h){throw this.clearPinnedOutput(),this.customState=f,this.paused=o,this.animationCart&&(this.syncContainerFromDom(),this.init(),this.reloadCart()),h}finally{this.importing=!1,b&&(this.customState=f,this.paused=o,s&&this.beginPlayback())}}unloadCart(){this.loopRunning=!1,this.requestedAnimationFrame&&cancelAnimationFrame(this.requestedAnimationFrame),this.drawLoopTimeout&&clearTimeout(this.drawLoopTimeout),this.animation?.teardown(),this.animation=void 0,this.prepared=!1,this.audioLibrariesInternal=this.fallbackAudio,this.mainCanvas?.clearAll()}reloadCart(t=!1){let n=this.animationCart;if(!n)return;this.pinnedOutput&&(this.clearPinnedOutput(),this.syncContainerFromDom(),this.init());let r=this.reinitPending?this.reinitStayPaused:this._paused;this.unloadCart(),t&&this.initSeed(),this.loadCart(n),this.paused=r,!this.paused&&!Pe&&this.resumeAudioLibraries()}getFrameRate(){return this.frameRate}updateFrameRate(t){if(this.frameRate=t,t>=1)this.targetDrawTime=1e3/t;else{let r=1/(2-t);this.targetDrawTime=1e3/r}this.drawTime=this.targetDrawTime}canvasMountOptions(){return{container:this.container,adoptFromDocument:!this.container}}syncContainerFromDom(){if(this.container){this.containerWidth=this.container.clientWidth||this.containerWidth,this.containerHeight=this.container.clientHeight||this.containerHeight;return}this.containerWidth=window.innerWidth,this.containerHeight=window.innerHeight}pinOutputSize(t){this.pinnedOutput=t,this.width=~~t.width,this.height=~~t.height,this.atCenterX=this.width/2,this.atCenterY=this.height/2,this.aspectRatio=this.width/this.height,this.mainCanvas&&this.mainCanvas.setSize(this.width,this.height)}shouldKeepPinnedOutput(){return this.pinnedOutput?(this.syncContainerFromDom(),this.viewportMatches(this.pinnedCssSize())?!0:!!(this.pinViewportAtImport&&this.viewportMatches(this.pinViewportAtImport))):!1}pinnedCssSize(){let t=this.pinnedOutput;return{w:t.cssWidth??t.width/fe,h:t.cssHeight??t.height/fe}}viewportMatches(t){return Math.abs(this.containerWidth-t.w)<8&&Math.abs(this.containerHeight-t.h)<8}fitPinnedCanvas(){let t=this.pinnedOutput,n=this.canvas;if(!t||!n)return;this.container&&!this.container.style.position&&(this.container.style.position="relative");let r=this.containerWidth||window.innerWidth,i=this.containerHeight||window.innerHeight,o=t.width/fe,s=t.height/fe;if(o<1||s<1||r<1||i<1)return;let u=Math.min(r/o,i/s),f=o*u,b=s*u;n.style.position="absolute",n.style.left="50%",n.style.top="50%",n.style.transform="translate(-50%, -50%)",n.style.margin="0",n.style.width=`${f}px`,n.style.height=`${b}px`,n.style.imageRendering=Math.abs(u-1)<.01?"auto":"pixelated"}clearPinnedOutput(){let t=this.canvas;this.pinnedOutput=null,this.pinViewportAtImport=null,t&&(t.style.position="",t.style.left="",t.style.top="",t.style.transform="",t.style.imageRendering="",t.style.width="",t.style.height="",t.style.margin="auto")}get canvas(){return this.animation?.getCanvas()??this.mainCanvas?.canvas}destroy(){this.outboundUnsubscribe?.(),this.outboundUnsubscribe=void 0,this.clearPinnedOutput(),this.unloadCart(),clearTimeout(this.reinitTimeout),this.mainCanvas&&!this.mainCanvas.adopted&&this.mainCanvas.canvas.remove()}drawIt(){}tuneFramerate(t){let n=this.lastCall||t;this.lastCall=t,this.drawTime=Math.max(0,this.drawTime+this.targetDrawTime-this.lastCall+n)}async processFrame(t,n={}){let r=n.ignorePause===!0,i=n.scheduleNext!==!1;if(!this.loopRunning&&!r)return;let o=!1,s,u="update";try{if(r||!this.paused||this.tempUnpause){if(!Pe&&!r&&this.tuneFramerate(t),!this.animation)return;if(u="update",this.updateInProgress=!0,await this.animation.updateAnimationState(this.framesElapsed,this.rawParams,t),this.updateInProgress=!1,u="render",await this.animation.renderAnimation(this.framesElapsed,this.rawParams,t),this.autoMode&&this.animation.cartState.saveToken&&!this.savedToken&&!new URLSearchParams(window.location.search).get("hash")){let h=localStorage.getItem("goodones"),m=JSON.stringify(h?[...JSON.parse(h),this.tokenData.hash]:[this.tokenData.hash]);localStorage.setItem("goodones",m),this.savedToken=!0,localStorage.setItem(this.tokenData.hash,this.mainCanvas.canvas.toDataURL("image/png")),window.location.reload(),this.loopRunning=!1;return}this.framesElapsed++,this.tempUnpause&&(this.tempUnpause=!1)}u="draw",this.drawIt()}catch(f){o=!0,s=f,this.handleFrameError(f,u)}finally{this.updateInProgress=!1}o?(this.consecutiveErrorCount++,this.consecutiveErrorCount>=ci&&(this.loopRunning=!1,this.onError?.(s,{phase:u,consecutive:this.consecutiveErrorCount,stopped:!0}))):this.consecutiveErrorCount=0,!(!this.loopRunning||!i)&&(this.drawLoopTimeout=setTimeout(()=>{this.requestedAnimationFrame=requestAnimationFrame(this.drawLoop)},this.drawTime))}async drawLoop(t){await this.processFrame(t,{scheduleNext:!0})}handleFrameError(t,n){let r=performance.now();r-this.lastErrorLogAt>=1e3&&(this.lastErrorLogAt=r,console.error(`Animation ${n} error:`,t)),this.consecutiveErrorCount===0&&this.onError?.(t,{phase:n,consecutive:1,stopped:!1})}pureAspectUpdate(t){if(t[0]===0&&t[1]===0){let r=this.containerWidth||window.innerWidth,i=this.containerHeight||window.innerHeight,o=r/i;this.aspectRatio=Math.min(li,Math.max(pi,o))}else this.aspectRatio=t[0]/t[1]}};var fi="HostChannel has been destroyed",ut=class{constructor(){this.inbound=[];this.listeners=[];this.closed=!1}dispatch(t){this.requireOpen(),this.inbound.push(t),this.inbound.length>32&&this.inbound.splice(0,this.inbound.length-32)}consume(){if(this.requireOpen(),this.inbound.length===0)return[];let t=this.inbound;return this.inbound=[],t}emit(t){this.requireOpen();for(let n of this.listeners)n(t)}onEvent(t){return this.requireOpen(),this.listeners.push(t),()=>{this.listeners=this.listeners.filter(n=>n!==t)}}clearInbound(){this.requireOpen(),this.inbound=[]}clear(){this.inbound=[],this.listeners=[]}close(){this.closed=!0,this.clear()}requireOpen(){if(this.closed)throw new Error(fi)}};var pe=2,Gt=1,$t="0.0.5",$n="0",Wn="1970-01-01T00:00:00.000Z";function ue(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ct(e){return JSON.parse(JSON.stringify(e))}function J(e,t,n,r){e.push(r?{code:t,detail:n,path:r}:{code:t,detail:n})}function jn(e,t,n){try{let r=JSON.stringify(e);if(r===void 0){J(n,"invalid-field",`${t} is not JSON-serializable`,t);return}return JSON.parse(r)}catch{J(n,"invalid-field",`${t} is not JSON-serializable`,t);return}}function ie(e){return typeof e=="string"&&e.length>0}function dt(e){return typeof e=="number"&&Number.isFinite(e)}function mi(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))}function Wt(e){return!ue(e)||typeof e.schemaVersion=="number"?!1:typeof e.version=="number"&&typeof e.seed=="string"&&typeof e.framesElapsed=="number"&&"state"in e}function lt(e){if(ue(e)){if(typeof e.schemaVersion=="number")return Number.isInteger(e.schemaVersion)?e.schemaVersion:void 0;if(Wt(e))return Gt}}function Bt(e,t,n){try{return ct(ge(e))}catch(r){let i=r instanceof Error?r.message:"engineState is not a cart state bundle";J(n,"invalid-engine-state",i,t);return}}function hi(e,t,n){if(!ue(e)){J(n,"invalid-field","cart must be an object",t);return}ie(e.id)||J(n,"invalid-field","cart.id must be a non-empty string",`${t}.id`),ie(e.version)||J(n,"invalid-field","cart.version must be a non-empty string",`${t}.version`);let r={id:typeof e.id=="string"?e.id:"",version:typeof e.version=="string"?e.version:""};return e.generative!==void 0&&(typeof e.generative!="boolean"?J(n,"invalid-field","cart.generative must be a boolean",`${t}.generative`):r.generative=e.generative),r.id&&r.version?r:void 0}function gi(e,t,n){if(!ue(e)){J(n,"invalid-field","clock must be an object",t);return}if(!dt(e.framesElapsed)){J(n,"invalid-field","clock.framesElapsed must be a finite number",`${t}.framesElapsed`);return}let r={framesElapsed:e.framesElapsed};return e.elapsedSinceStart!==void 0&&(dt(e.elapsedSinceStart)?r.elapsedSinceStart=e.elapsedSinceStart:J(n,"invalid-field","clock.elapsedSinceStart must be a finite number",`${t}.elapsedSinceStart`)),e.now!==void 0&&(dt(e.now)?r.now=e.now:J(n,"invalid-field","clock.now must be a finite number",`${t}.now`)),e.frameRate!==void 0&&(dt(e.frameRate)?r.frameRate=e.frameRate:J(n,"invalid-field","clock.frameRate must be a finite number",`${t}.frameRate`)),r}function yi(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){J(n,"invalid-field","modules must be an array",t);return}let r=[];return e.forEach((i,o)=>{let s=`${t}[${o}]`;if(!ue(i)||!ie(i.id)||!ie(i.version)){J(n,"invalid-field","module refs need non-empty id and version",s);return}r.push({id:i.id,version:i.version})}),r}function bi(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){J(n,"invalid-field","assets must be an array",t);return}let r=[];return e.forEach((i,o)=>{let s=`${t}[${o}]`;if(!ue(i)||!ie(i.id)){J(n,"invalid-field","asset refs need a non-empty id",s);return}let u={id:i.id};i.version!==void 0&&(ie(i.version)?u.version=i.version:J(n,"invalid-field","asset.version must be a non-empty string",`${s}.version`)),i.ref!==void 0&&(ie(i.ref)?u.ref=i.ref:J(n,"invalid-field","asset.ref must be a non-empty string",`${s}.ref`)),r.push(u)}),r}function vi(e,t,n){if(e===void 0)return;if(!ue(e)||!ie(e.seed)){J(n,"invalid-field","rng must include a seed",t);return}if(!ue(e.prngA)||!ue(e.prngB)){J(n,"invalid-field","rng must include prngA and prngB",t);return}if(typeof e.useA!="boolean"){J(n,"invalid-field","rng.useA must be a boolean",`${t}.useA`);return}return jn(e,t,n)}function Si(e,t,n){if(e===void 0)return;if(!ue(e)){J(n,"invalid-field","provenance must be an object",t);return}let r={};return e.source!==void 0&&(ie(e.source)?r.source=e.source:J(n,"invalid-field","provenance.source must be a non-empty string",`${t}.source`)),e.integrity!==void 0&&(!ue(e.integrity)||!ie(e.integrity.alg)||!ie(e.integrity.hash)?J(n,"invalid-field","provenance.integrity needs alg and hash strings",`${t}.integrity`):r.integrity={alg:e.integrity.alg,hash:e.integrity.hash}),r}function zn(e,t){e.schemaVersion!==void 0&&e.schemaVersion!==pe&&J(t,"invalid-schema",`defineSnapshot produces schema ${pe}`,"schemaVersion"),ie(e.seed)||J(t,"invalid-field","seed must be a non-empty string","seed");let n=e.runtimeVersion===void 0?$t:e.runtimeVersion;ie(n)||J(t,"invalid-field","runtimeVersion must be a non-empty string","runtimeVersion");let r=e.createdAt===void 0?new Date().toISOString():e.createdAt;mi(r)||J(t,"invalid-field","createdAt must be an ISO-8601 date","createdAt");let i=hi(e.cart,"cart",t),o=gi(e.clock,"clock",t),s=Bt(e.engineState,"engineState",t),u=yi(e.modules,"modules",t),f=bi(e.assets,"assets",t),b=vi(e.rng,"rng",t),h=Si(e.provenance,"provenance",t),m;if(e.hostState!==void 0&&(m=jn(e.hostState,"hostState",t)),e.hostStateRef!==void 0&&!ie(e.hostStateRef)&&J(t,"invalid-field","hostStateRef must be a non-empty string","hostStateRef"),t.length>0||!i||!o||!s||!ie(e.seed))return;let A={schemaVersion:pe,runtimeVersion:n,cart:i,seed:e.seed,clock:o,engineState:s,createdAt:r};return u&&u.length>0&&(A.modules=u),b&&(A.rng=b),m!==void 0&&(A.hostState=m),ie(e.hostStateRef)&&(A.hostStateRef=e.hostStateRef),f&&f.length>0&&(A.assets=f),h&&(h.source||h.integrity)&&(A.provenance=h),A}function wi(e){if(!ue(e))return{ok:!1,errors:[{code:"invalid-snapshot",detail:"Snapshot input is not an object"}]};let t=[],n=zn(e,t);return!n||t.length>0?{ok:!1,errors:t}:{ok:!0,snapshot:n}}function pt(e,t){return ie(e.cartId)?wi({cart:{id:e.cartId,version:t?.cartVersion??$n,generative:e.generative},modules:t?.modules,seed:e.seed,rng:t?.rng,clock:t?.clock??{framesElapsed:e.framesElapsed,elapsedSinceStart:e.elapsedSinceStart},engineState:e,hostState:t?.hostState,hostStateRef:t?.hostStateRef,assets:t?.assets,createdAt:t?.createdAt,provenance:t?.provenance,runtimeVersion:t?.runtimeVersion}):{ok:!1,errors:[{code:"invalid-field",detail:"cart.id is required",path:"cart.id"}]}}function Gn(e){let t=ct(e),n={schemaVersion:Gt,engineState:t,seed:t.seed,clock:{framesElapsed:t.framesElapsed,elapsedSinceStart:t.elapsedSinceStart}};return t.cartId&&(n.cart={id:t.cartId,version:$n,generative:t.generative}),n}function jt(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return{ok:!1,errors:[{code:"invalid-json",detail:"Snapshot JSON could not be parsed"}]}}if(!ue(t))return{ok:!1,errors:[{code:"invalid-snapshot",detail:"Snapshot is not an object"}]};if(Wt(t))try{return{ok:!0,snapshot:Gn(ge(t))}}catch(r){return{ok:!1,errors:[{code:"invalid-engine-state",detail:r instanceof Error?r.message:"Cart state bundle is invalid"}]}}let n=lt(t);if(n===void 0)return{ok:!1,errors:[{code:"invalid-snapshot",detail:"Snapshot is missing schemaVersion and is not a cart state bundle",path:"schemaVersion"}]};if(n===Gt){let r=[],i=Bt(t.engineState,"engineState",r);return!i||r.length>0?{ok:!1,errors:r}:{ok:!0,snapshot:Gn(i)}}if(n!==pe){if(n>pe)return{ok:!1,errors:[{code:"unsupported-schema",detail:`Snapshot schema ${n} is newer than ${pe}`,path:"schemaVersion"}]};let r=[],i=Bt(t.engineState,"engineState",r);return i?{ok:!0,snapshot:{schemaVersion:n,engineState:i,seed:typeof t.seed=="string"?t.seed:i.seed,clock:{framesElapsed:i.framesElapsed,elapsedSinceStart:i.elapsedSinceStart}}}:{ok:!1,errors:r.length?r:[{code:"invalid-snapshot",detail:`Snapshot schema ${n} is missing engineState`,path:"engineState"}]}}return Be(t)}function Be(e){if(!ue(e))return{ok:!1,errors:[{code:"invalid-snapshot",detail:"Snapshot is not an object"}]};if(e.schemaVersion!==pe)return{ok:!1,errors:[{code:"invalid-schema",detail:`Expected snapshot schema ${pe}`,path:"schemaVersion"}]};let t=[],n=zn(e,t);return!n||t.length>0?{ok:!1,errors:t}:{ok:!0,snapshot:n}}function He(e){return e.map(t=>t.detail).join("; ")}function qn(e){if(Wt(e))return ge(e);if(ue(e)&&e.engineState!==void 0)return ge(e.engineState);throw new Error("Legacy snapshot is missing engine state")}function Ai(){return[{from:1,to:2,migrate:xi}]}function Ei(e){let t=[...e?.migrations??Ai()],n=new Map;for(let r of t){if(!Number.isInteger(r.from)||!Number.isInteger(r.to)||r.to!==r.from+1)throw new Error(`Snapshot migration must step from n to n+1 (got ${String(r.from)} \u2192 ${String(r.to)})`);if(typeof r.migrate!="function")throw new Error(`Snapshot migration ${r.from} \u2192 ${r.to} is missing migrate()`);if(n.has(r.from))throw new Error(`Duplicate snapshot migration from schema ${r.from}`);n.set(r.from,r)}return{migrations:t,get(r){return n.get(r)}}}var Ci=Ei();function ki(){return Ci}function xi(e){let t=qn(e),n=pt(t,{createdAt:Wn,runtimeVersion:$t});if(n.ok===!1)throw new Error(He(n.errors));return n.snapshot}function Yn(e){try{return ct(e)}catch{return}}function Jn(e,t=ki()){let n=Yn(e);if(n===void 0)return{ok:!1,errors:[{code:"invalid-snapshot",detail:"Snapshot is not JSON-serializable"}]};let r=n,i=lt(r);if(i===void 0){let o=jt(r);if(o.ok===!1)return o;r=o.snapshot,i=o.snapshot.schemaVersion}if(i>pe)return{ok:!1,errors:[{code:"unsupported-schema",detail:`Snapshot schema ${i} is newer than ${pe}`,path:"schemaVersion"}]};if(i===pe)return Be(r);for(;i<pe;){let o=t.get(i);if(!o)return{ok:!1,errors:[{code:"missing-migration",detail:`No snapshot migration from schema ${i} to ${i+1}`,path:"schemaVersion"}]};let s;try{s=o.migrate(Yn(r))}catch(f){let b=f instanceof Error?f.message:"Migration threw";return{ok:!1,errors:[{code:"invalid-migration-result",detail:`Migration ${o.from} \u2192 ${o.to} failed: ${b}`,path:"schemaVersion"}]}}let u=lt(s);if(u!==o.to)return{ok:!1,errors:[{code:"invalid-migration-result",detail:`Migration ${o.from} \u2192 ${o.to} produced schema ${String(u)}`,path:"schemaVersion"}]};if(o.to===pe){let f=Be(s);if(f.ok===!1)return{ok:!1,errors:[{code:"invalid-migration-result",detail:`Migration ${o.from} \u2192 ${o.to} did not produce a valid snapshot`,path:"schemaVersion"},...f.errors]};r=f.snapshot}else r=s;i=o.to}return Be(r)}function Xn(e,t){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{return{ok:!1,errors:[{code:"invalid-json",detail:"Snapshot JSON could not be parsed"}]}}if(!n||typeof n!="object")return{ok:!1,errors:[{code:"invalid-snapshot",detail:"Snapshot is not an object"}]};if(typeof n.schemaVersion=="number"){let i=Jn(n,t);if(i.ok===!1)return i;try{return{ok:!0,bundle:ge(i.snapshot.engineState),snapshot:i.snapshot}}catch(o){return{ok:!1,errors:[{code:"invalid-engine-state",detail:o instanceof Error?o.message:"engineState is not a cart state bundle",path:"engineState"}]}}}try{return{ok:!0,bundle:ge(n)}}catch(i){return{ok:!1,errors:[{code:"invalid-engine-state",detail:i instanceof Error?i.message:"Cart state bundle is invalid"}]}}}function Qn(e,t){let n=jt(e);return n.ok===!1?n:Jn(n.snapshot,t)}var Ri=["image","audio","font","spritesheet"],Ii=["timeout","cors","not-found","invalid","aborted","resolver"],Ge="cyberart:fallback/silent",Zn="Asset preloader has been destroyed",Ti=4,Pi=new Set(Ri),Di=new Set(Ii),Mi={timeout:"asset load timed out",cors:"CORS blocked this asset","not-found":"asset was not found",invalid:"asset declaration or resource is invalid",aborted:"asset load was aborted",resolver:"asset resolver failed"};function Fi(e){return typeof e=="string"&&Pi.has(e)}function Hi(e){return typeof e=="string"&&Di.has(e)}function zt(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.id=="string"&&typeof t.ref=="string"&&Hi(t.code)&&typeof t.message=="string"}function te(e){return{id:e.id,ref:e.ref,code:e.code,message:e.message&&e.message.length>0?e.message:Mi[e.code]}}function Oe(e,t){return{type:e==="ready"?Ce:ke,kind:"state",payload:t}}function Oi(e){return e instanceof Error&&e.name==="AbortError"||typeof DOMException<"u"&&e instanceof DOMException&&e.name==="AbortError"}function qt(e){return e?{...e}:void 0}function ye(e){let t={id:e.id,ref:e.ref,type:e.type,url:e.url};return e.integrity!==void 0&&(t.integrity=e.integrity),e.provenance&&(t.provenance=qt(e.provenance)),e.cors!==void 0&&(t.cors=e.cors),e.usedFallback&&(t.usedFallback=!0),e.managed&&(t.managed=!0),t}function $e(e){return{id:e.id,ref:e.ref,code:e.code,message:e.message}}function Li(e){if(e.state==="ready"){let t={state:"ready",resource:ye(e.resource)};return e.failure&&(t.failure=$e(e.failure)),t}return e.state==="failed"?{state:"failed",failure:$e(e.failure)}:{state:e.state}}function _i(e){if(!e||typeof e!="object")return te({id:"",ref:"",code:"invalid",message:"declaration is required"});if(typeof e.id!="string"||e.id.length===0)return te({id:typeof e.id=="string"?e.id:"",ref:typeof e.ref=="string"?e.ref:"",code:"invalid",message:"id is required"});if(typeof e.ref!="string"||e.ref.length===0)return te({id:e.id,ref:"",code:"invalid",message:"ref is required"});if(!Fi(e.type))return te({id:e.id,ref:e.ref,code:"invalid",message:`unsupported type ${String(e.type)}`});if(e.integrity!==void 0&&typeof e.integrity!="string")return te({id:e.id,ref:e.ref,code:"invalid",message:"integrity must be a string"});if(e.timeoutMs!==void 0&&(typeof e.timeoutMs!="number"||!Number.isFinite(e.timeoutMs)||e.timeoutMs<0))return te({id:e.id,ref:e.ref,code:"invalid",message:"timeoutMs must be a non-negative finite number"})}function er(e){return{id:e.id,ref:Ge,type:e.type,url:Ge,usedFallback:!0,cors:"omit"}}function tr(e,t){return zt(t)?{id:e.id,ref:e.ref,code:t.code,message:t.message}:Oi(t)?te({id:e.id,ref:e.ref,code:"aborted"}):te({id:e.id,ref:e.ref,code:"resolver",message:t instanceof Error?t.message:String(t)})}function nr(e,t){if(!t||typeof t.url!="string"||t.url.length===0)throw te({id:e.id,ref:e.ref,code:"invalid",message:"resolver returned no url"});if(t.integrity&&e.integrity&&t.integrity!==e.integrity)throw te({id:e.id,ref:e.ref,code:"invalid",message:"integrity mismatch"});let n=ye(t);return n.id=e.id,n.ref=t.ref||e.ref,n.type=e.type,!n.integrity&&e.integrity&&(n.integrity=e.integrity),!n.provenance&&e.provenance&&(n.provenance=qt(e.provenance)),n}function rr(e){if(typeof e?.resolver?.resolve!="function")throw new Error("createAssetPreloader: resolver is required");let t=e.emitEvents!==!1,n=e.wallClockTimeout!==!1,r=new Map,i=[],o=new Map,s=new Map,u=new Map,f=new Map,b=new Map,h=new Set,m=!1;function A(p){return p.code==="aborted"||p.code==="timeout"}function D(p,F,H){let j=tr(p,H);return j.code==="timeout"?j:F.aborted?te({id:p.id,ref:p.ref,code:"aborted"}):j}function x(p,F){let H=b.get(p);H||(H=new Set,b.set(p,H)),H.add(F)}function v(p){if(p?.state==="ready")return`${p.resource.type}\0${p.resource.ref}`}function M(p,F){for(let[H,j]of b)if(H!==F&&j.has(p))return!0;for(let[H,j]of r)if(H!==F&&v(j)===p)return!0;return!1}function L(p,F){let H=new Set(b.get(p)),j=v(F);j&&H.add(j),b.delete(p);for(let d of H)M(d,p)||u.delete(d)}function E(){let p=0,F=0,H=0,j=0,d={};for(let[y,w]of r)d[y]=Li(w),w.state==="pending"||w.state==="loading"?p+=1:w.state==="failed"?H+=1:(F+=1,(w.resource.usedFallback||w.failure)&&(j+=1));return{total:r.size,pending:p,ready:F,failed:H,fallbacks:j,items:d,failures:i.map($e)}}function S(){if(h.size===0)return;let p=E();for(let F of h)F(p)}function g(p){i.push($e(p))}function c(p){m||!t||!e.dispatch||e.dispatch(p)}function a(p){if(p?.managed&&p.url.startsWith("blob:")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(p.url)}catch{}}function k(p,F){if(m)return;let H=r.get(p);H?.state==="ready"&&a(H.resource),r.set(p,F),S()}function V(p){if(p.fallback!==void 0)return p.fallback==="silent"?{id:`${p.id}::fallback`,ref:Ge,type:p.type}:typeof p.fallback=="string"?{id:`${p.id}::fallback`,ref:p.fallback,type:p.type}:{...p.fallback,id:typeof p.fallback.id=="string"&&p.fallback.id.length>0?p.fallback.id:`${p.id}::fallback`}}function B(p,F,H){let j=`${p.type}\0${p.ref}`,d=u.get(j);if(d)return F.aborted?Promise.reject(te({id:p.id,ref:p.ref,code:"aborted"})):(x(H,j),Promise.resolve(ye(d.resource)));if(F.aborted)return Promise.reject(te({id:p.id,ref:p.ref,code:"aborted"}));let y=f.get(j);if(!y){let I=new AbortController,R={id:p.id,ref:p.ref,type:p.type};p.integrity!==void 0&&(R.integrity=p.integrity),p.provenance&&(R.provenance=qt(p.provenance)),y={promise:Promise.resolve().then(()=>e.resolver.resolve(R,I.signal)).then(O=>{let U=nr(p,O);if(I.signal.aborted)throw te({id:p.id,ref:p.ref,code:"aborted"});return u.set(j,{resource:ye(U)}),U}).catch(O=>{throw tr(p,O)}).finally(()=>{f.delete(j)}),controller:I,waiters:0},f.set(j,y)}let w=y;return w.waiters+=1,new Promise((I,R)=>{let T=!1,O=(G,z)=>{T||(T=!0,F.removeEventListener("abort",U),w.waiters-=1,z&&w.waiters<=0&&w.controller.abort(),G())},U=()=>{O(()=>R(te({id:p.id,ref:p.ref,code:"aborted"})),!0)};if(F.aborted){U();return}F.addEventListener("abort",U,{once:!0}),w.promise.then(G=>{if(!T){if(F.aborted){U();return}x(H,j),O(()=>I(ye(G)),!1)}},G=>{if(!T){if(F.aborted){U();return}O(()=>R(G),!1)}})})}function $(p,F,H){if(F.aborted)return Promise.reject(te({id:p.id,ref:p.ref,code:"aborted"}));if(p.ref===Ge)return Promise.resolve(er(p));let j=new AbortController,d=()=>j.abort();F.addEventListener("abort",d,{once:!0});let y=p.timeoutMs??e.timeoutMs,w,I=!1;return n&&y!==void 0&&y>0&&Number.isFinite(y)&&(w=setTimeout(()=>{I=!0,j.abort()},y)),B(p,j.signal,H).then(R=>{let T=nr(p,R);return T.id=p.id,T}).catch(R=>{throw I?te({id:p.id,ref:p.ref,code:"timeout"}):R}).finally(()=>{w!==void 0&&clearTimeout(w),F.removeEventListener("abort",d)})}async function K(p,F,H,j){try{return{resource:await $(p,F,j)}}catch(d){let y=D(p,F,d);if(A(y)||F.aborted||H>=Ti)throw y;let w=V(p);if(!w)throw y;if(F.aborted)throw te({id:p.id,ref:p.ref,code:"aborted"});if(p.fallback==="silent"||w.ref===Ge)return{resource:er(p),failure:y};try{let I=await K(w,F,H+1,j);return{resource:{...ye(I.resource),id:p.id,usedFallback:!0},failure:y}}catch(I){let R=zt(I)&&!A(I)&&!F.aborted?I:D(p,F,I);throw!A(R)&&!F.aborted&&g(y),R}}}async function q(p,F){if(m)throw new Error(Zn);let H=r.get(p.id);if(H?.state==="ready"||H?.state==="failed")return;let j=o.get(p.id);if(j){await j;return}let d=(async()=>{let y=_i(p);if(y){k(p.id,{state:"failed",failure:y}),g(y),c(Oe("failed",{id:p.id,ref:p.ref,failure:y}));return}k(p.id,{state:"loading"});let w=s.get(p.id)??new AbortController;s.has(p.id)||s.set(p.id,w);try{let I=await K(p,w.signal,F,p.id);if(m)return;if(w.signal.aborted){let R=te({id:p.id,ref:p.ref,code:"aborted"});k(p.id,{state:"failed",failure:R}),g(R),c(Oe("failed",{id:p.id,ref:p.ref,failure:R}));return}if(I.resource.id=p.id,I.failure){k(p.id,{state:"ready",resource:I.resource,failure:I.failure}),g(I.failure),c(Oe("failed",{id:p.id,ref:p.ref,failure:I.failure,resource:ye(I.resource)})),c(Oe("ready",{id:p.id,ref:I.resource.ref,resource:ye(I.resource),failure:I.failure}));return}k(p.id,{state:"ready",resource:I.resource}),c(Oe("ready",{id:p.id,ref:p.ref,resource:ye(I.resource)}))}catch(I){if(m)return;let R=zt(I)&&!A(I)&&!w.signal.aborted?{...$e(I),id:p.id}:D(p,w.signal,I);k(p.id,{state:"failed",failure:R}),g(R),c(Oe("failed",{id:p.id,ref:p.ref,failure:R}))}finally{s.get(p.id)===w&&s.delete(p.id)}})();o.set(p.id,d);try{await d}finally{o.delete(p.id)}}return{async preload(p){if(m)throw new Error(Zn);let F=Array.isArray(p)?p:[];for(let H of F)H&&typeof H.id=="string"&&H.id.length>0&&(r.has(H.id)||r.set(H.id,{state:"pending"}),s.has(H.id)||s.set(H.id,new AbortController));return S(),await Promise.all(F.map(H=>q(H,0))),E()},get(p){let F=r.get(p);if(F?.state==="ready")return ye(F.resource)},getProgress(){return E()},onProgress(p){return h.add(p),()=>{h.delete(p)}},abort(p){if(!m){if(p!==void 0){s.get(p)?.abort();return}for(let F of s.values())F.abort()}},forget(p){if(m)return;if(p===void 0){for(let H of r.values())H.state==="ready"&&a(H.resource);r.clear(),i.length=0,u.clear(),b.clear(),S();return}let F=r.get(p);F?.state==="ready"&&a(F.resource),L(p,F),r.delete(p);for(let H=i.length-1;H>=0;H--)i[H].id===p&&i.splice(H,1);S()},dispose(){if(!m){m=!0;for(let p of s.values())p.abort();s.clear();for(let p of r.values())p.state==="ready"&&a(p.resource);r.clear(),i.length=0,o.clear();for(let p of f.values())p.controller.abort();u.clear(),f.clear(),b.clear(),h.clear()}}}}var ir=.25;function Le(e){return e.error===void 0?{state:e.state}:{state:e.state,error:e.error}}function Yt(e){return!Number.isFinite(e)||e<0?0:e>1?1:e}function Ni(e){return e instanceof Error&&e.message?e.message:String(e)}async function Ui(){let{adaptersFor:e}=await Promise.resolve().then(()=>(Lt(),On)),t=e(["tone"]),n=typeof navigator<"u"&&/Headless/i.test(navigator.userAgent);for(let r of t)n?await r.load():await r.unlock()}function Ki(e){if(!e||typeof e!="object")return;let t=e.id;return typeof t=="string"&&t.length>0?t:void 0}function or(e={}){let t=e.toneStart??Ui,n=!!e.reducedSensory,r=new Set,i=new Map,o=new Map,s=new Map,u=[],f={state:"locked"},b,h=!1,m=!1;function A(S){for(let g of u.slice())g(S)}function D(S,g){let c=i.get(S);if(c)return g&&!c.participantId&&(c.participantId=g),c;let a={id:S,participantId:g,gain:1,muted:!1,duckGain:1,priority:0,manualDuck:!1};return i.set(S,a),a}function x(S){return h||S.muted?0:Yt(S.gain*S.duckGain)}function v(S){return{id:S.id,participantId:S.participantId,gain:S.gain,muted:S.muted,duckGain:S.duckGain,priority:S.priority,effectiveGain:x(S)}}function M(){let S=-1/0;for(let g of s.values())g.priority>S&&(S=g.priority);for(let g of i.values())if(!g.manualDuck){if(S===-1/0){g.duckGain=1;continue}g.duckGain=g.priority<S?ir:1}}async function L(){if(m||f.state==="unlocked")return Le(f);if(b)return await b,Le(f);f={state:"unlocking"},b=(async()=>{try{await t(),f={state:"unlocked"}}catch(S){f={state:"failed",error:Ni(S)}}})();try{await b}finally{b=void 0}return Le(f)}return{unlock:L,status(){return Le(f)},authorize(S){m||typeof S!="string"||S.length===0||r.add(S)},revoke(S){m||r.delete(S)},isAuthorized(S){return S===void 0||S.length===0?r.size===0:r.size===0?!0:r.has(S)},setChannelGain(S,g,c){m||typeof S!="string"||S.length===0||(D(S,c).gain=Yt(g))},setPriority(S,g,c){m||typeof S!="string"||S.length===0||(D(S,c).priority=Number.isFinite(g)?g:0,M())},mute(){m||(h=!0,A({type:"mute"}))},unmute(){m||(h=!1,A({type:"mute"}))},muteChannel(S,g){m||typeof S!="string"||S.length===0||(D(S,g).muted=!0,A({type:"mute"}))},unmuteChannel(S){if(m)return;let g=i.get(S);g&&(g.muted=!1,A({type:"mute"}))},duck(S,g=ir){if(m||typeof S!="string"||S.length===0)return;let c=D(S);c.manualDuck=!0,c.duckGain=Yt(g)},unduck(S){if(m)return;let g=i.get(S);g&&(g.manualDuck=!1,M())},effectiveGain(S){let g=i.get(S);return g?x(g):h?0:1},handleHostEvent(S){if(m||!S||typeof S!="object")return;let g=Ki(S.payload);if(g){if(S.type===Ce){o.set(g,"ready"),A({type:"asset",id:g,status:"ready"});return}S.type===ke&&(o.set(g,"failed"),A({type:"asset",id:g,status:"failed"}))}},assetStatus(S){return o.get(S)},noteCueStarted(S){if(m)return;s.set(S.idempotencyKey,{idempotencyKey:S.idempotencyKey,channelId:S.channelId,participantId:S.participantId,priority:S.priority});let g=D(S.channelId,S.participantId);S.priority>g.priority&&(g.priority=S.priority),M()},noteCueEnded(S){s.delete(S)&&M()},teardown(S){if(!m&&!(typeof S!="string"||S.length===0)){r.delete(S);for(let[g,c]of[...s.entries()])c.participantId===S&&s.delete(g);for(let[g,c]of[...i.entries()])c.participantId===S&&i.delete(g);M(),A({type:"teardown",participantId:S})}},onNotice(S){return u.push(S),()=>{let g=u.indexOf(S);g>=0&&u.splice(g,1)}},inspect(){let S=[...o.entries()].sort(([c],[a])=>c<a?-1:c>a?1:0),g={};for(let[c,a]of S)g[c]=a;return{status:Le(f),reducedSensory:n,muted:h,authorized:[...r].sort(),channels:[...i.values()].sort((c,a)=>c.id<a.id?-1:c.id>a.id?1:0).map(v),assets:g}},destroy(){m||(m=!0,s.clear(),i.clear(),r.clear(),A({type:"destroy"}),u.length=0)},get reducedSensory(){return n},get muted(){return h}}}function sr(e,t){let n=e.dispatch.bind(e);e.dispatch=r=>{t.handleHostEvent(r),n(r)}}function ft(e){yn();let{container:t,seed:n,captureKeyboard:r=!1,audio:i,deterministic:o,assets:s,audioBroker:u,audioParticipantId:f}=e,b=n===void 0?void 0:Pn(n,o?"deterministic":"live"),h=new ut;if(u&&(sr(h,u),f&&u.authorize(f)),s&&typeof s.resolver?.resolve!="function")throw new Error("createRuntime: assets.resolver is required");let m=s?rr({resolver:s.resolver,timeoutMs:s.timeoutMs,emitEvents:s.emitEvents??!o,wallClockTimeout:!o,dispatch:a=>h.dispatch(a)}):void 0,A=!1,D=null,x,v=!1,M=t.clientWidth||window.innerWidth,L=t.clientHeight||window.innerHeight,E=new at(30,!1,M,L,!1,void 0,{container:t,seed:b,captureKeyboard:r,hostChannel:h,audio:i,deterministic:o}),S=()=>{let a=t.clientWidth||window.innerWidth,k=t.clientHeight||window.innerHeight;return a===E.containerWidth&&k===E.containerHeight?!1:(E.containerWidth=a,E.containerHeight=k,!0)},g=null;return!E.isDeterministic&&typeof ResizeObserver<"u"&&(g=new ResizeObserver(()=>{if(A||!D)return;S()&&v&&E.reinit()}),g.observe(t)),E.onError=(a,k)=>{x?.(a,k)},{get tokenData(){return E.tokenData},get hostChannel(){return h},get assets(){return m},get audioBroker(){return u},get onError(){return x},set onError(a){x=a},mount(a,k={}){if(A)throw new Error("createRuntime: cannot mount on a destroyed runtime");D?.destroy(),v=!1,E.customState=k.initialState,E.setGameManager(k.gameManager);let V=k.onEvent?h.onEvent(k.onEvent):()=>{};if(u&&f&&u.authorize(f),!E.prepareCart(a))throw V(),new Error("createRuntime: failed to prepare cart");let B=!1,$={async start(){if(!B){if(S()&&E.isPrepared&&(E.init(),E.unloadCart(),!E.prepareCart(a)))throw new Error("createRuntime: failed to prepare cart");E.needsAudio&&(u?await u.unlock():await E.unlockAudio(),B)||(v=!0,E.beginPlayback())}},pause(){B||(E.paused=!0)},resume(){B||(E.paused=!1)},dispatch(K){B||h.dispatch(K)},snapshot(){if(B)return{seed:"",pngDataUrl:""};let K=E.canvas;return{seed:E.tokenData.hash,metadata:a.metadata,pngDataUrl:K?K.toDataURL("image/png"):""}},destroy(){B||(B=!0,v=!1,V(),h.clearInbound(),E.unloadCart(),D===$&&(D=null))},reload(){if(!B){if(!v){if(E.isPrepared&&(E.unloadCart(),!E.prepareCart(a)))throw new Error("createRuntime: failed to prepare cart");return}E.reloadCart()}},reinit(K){if(!B){if(!v){S();return}E.reinit(K)}},getCartState(){return E.animation?.cartState},exportState(){return B?Promise.reject(new Error("Cart handle has been destroyed")):E.exportState()},exportStateJSON(){return B?Promise.reject(new Error("Cart handle has been destroyed")):E.exportStateJSON()},async importState(K,q){if(B)throw new Error("Cart handle has been destroyed");let p=K,F=K;if(typeof K=="string")try{F=JSON.parse(K)}catch{await E.importState(K,q);return}if(F&&typeof F=="object"&&typeof F.schemaVersion=="number"){let H=Xn(F);if(H.ok===!1)throw new oe(He(H.errors));await E.importState(H.bundle,q);return}await E.importState(typeof p=="string"?p:F,q)},async exportSnapshot(K){if(B)throw new Error("Cart handle has been destroyed");let q=await E.exportState(),p=E.getClock(),F=pt(q,{...K,rng:E.getRandomState(),clock:{framesElapsed:q.framesElapsed,elapsedSinceStart:q.elapsedSinceStart,now:p.now,frameRate:p.frameRate}});if(F.ok===!1)throw new oe(He(F.errors));return F.snapshot},async exportSnapshotJSON(K){return JSON.stringify(await $.exportSnapshot(K))},async importSnapshot(K,q){if(B)throw new Error("Cart handle has been destroyed");let p=Qn(K);if(p.ok===!1)throw new oe(He(p.errors));await E.importState(p.snapshot.engineState,q)},peekExportedFramebuffer(){return B?null:E.peekExportedFramebuffer()},peekSeed(){if(!B)return E.peekSeed()},isGenerative(){return B?!1:E.isGenerative()},async step(K=1){if(B)throw new Error("Cart handle has been destroyed");await E.step(K)},async advance(K){if(B)throw new Error("Cart handle has been destroyed");await E.advance(K)},schedule(K){B||E.schedule(K)},getClock(){if(B)throw new Error("Cart handle has been destroyed");return E.getClock()},getRandomState(){if(B)throw new Error("Cart handle has been destroyed");return E.getRandomState()},getReplayMetadata(){return B?Promise.reject(new Error("Cart handle has been destroyed")):E.getReplayMetadata()},get canvas(){return E.canvas},get paused(){return E.paused},set paused(K){B||(E.paused=K)},get tokenData(){return E.tokenData},get isPrepared(){return E.isPrepared},get isLoopRunning(){return E.isLoopRunning},get needsAudio(){return E.needsAudio},get audioLibraries(){return E.audioLibraries}};return D=$,$},async unlockAudio(){if(u){E.needsAudio&&await u.unlock();return}await E.unlockAudio()},destroy(){A||(A=!0,D?.destroy(),D=null,u&&f&&u.teardown(f),g?.disconnect(),g=null,m?.dispose(),h.close(),E.destroy())}}}var ar="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",ur=320,dr=180,Vi="Headless harness has been destroyed",cr=!1;function mt(e={}){if(e.glyphAtlas&&Rt(e.glyphAtlas),typeof globalThis.ImageData>"u"){class n{constructor(i,o,s){this.colorSpace="srgb";typeof i=="number"?(this.width=i,this.height=o??0,this.data=new Uint8ClampedArray(this.width*this.height*4)):(this.data=i,this.width=o??0,this.height=s??i.length/4/this.width)}}globalThis.ImageData=n}gn();let t=HTMLCanvasElement.prototype;t.getContext=function(r,i){return String(r??"2d").toLowerCase()!=="2d"?null:It(this,{alpha:i?.alpha!==!1,glyphAtlas:e.glyphAtlas})},t.toDataURL=function(r){if(r&&r!=="image/png")throw new Y(`toDataURL(${r})`);return ln(this)??ar},cr=!0}function Bi(e,t){let n=document.createElement("div");return Object.defineProperty(n,"clientWidth",{value:e,configurable:!0}),Object.defineProperty(n,"clientHeight",{value:t,configurable:!0}),document.body.appendChild(n),n}function Gi(e){let t=e.indexOf(","),n=t>=0?e.slice(t+1):e,r=globalThis.atob(n),i=new Uint8Array(r.length);for(let o=0;o<r.length;o++)i[o]=r.charCodeAt(o);return i}function $i(){return typeof process<"u"&&!!process.versions?.node}async function Wi(e,t){if(!$i())throw new Error("captureFrame(path) requires Node.js; omit the path to get the snapshot only");let n;try{({writeFile:n}=await import("node:fs/promises"))}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`captureFrame(path) could not load node:fs/promises (${i}). Omit the path, or run under Node.`)}try{await n(e,Gi(t))}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`captureFrame could not write ${e}: ${i}`)}}function ji(e){cr||mt();let t=e.width??ur,n=e.height??dr,r=Bi(t,n),i=[],o=[],s=!1,u=e.onEvent,f=e.onError,b=ft({container:r,seed:e.seed,deterministic:{origin:e.origin,actions:e.actions??[]}});b.onError=(x,v)=>{o.push({error:x,info:v}),f?.(x,v)},Object.defineProperty(b,"onError",{configurable:!0,enumerable:!0,get(){return f},set(x){f=x}});let h=x=>{i.push(x),u?.(x)},m=b.mount(e.cart,{initialState:e.initialState,gameManager:e.gameManager,onEvent:h}),A=()=>{if(s)throw new Error(Vi)};return{runtime:b,container:r,get events(){return i.slice()},get errors(){return o.slice()},get cart(){return m},async step(x=1){A(),await m.step(x)},async advance(x){A(),await m.advance(x)},schedule(x){A(),m.schedule(x)},dispatch(x){A(),m.dispatch(x)},start(){return A(),m.start()},pause(){A(),m.pause()},resume(){A(),m.resume()},get paused(){return m.paused},key(x){A(),m.schedule({type:"key",atFrame:m.getClock().framesElapsed,key:x})},click(x,v){A(),m.schedule({type:"pointer",atFrame:m.getClock().framesElapsed,pointer:{kind:"down",x,y:v}})},async inspect(){A();let x=await m.getReplayMetadata();return{state:x.state,events:i.slice(),errors:o.slice(),replay:x,clock:m.getClock()}},async captureFrame(x){A();let v=m.snapshot();return x&&await Wi(x,v.pngDataUrl),v},remount(x={}){return A(),i.length=0,o.length=0,"onEvent"in x&&(u=x.onEvent),m=b.mount(e.cart,{initialState:x.initialState??e.initialState,gameManager:x.gameManager??e.gameManager,onEvent:h}),m},destroy(){if(!s){s=!0;try{m.destroy()}finally{try{b.destroy()}finally{r.remove()}}}}}}var lr="CYBERART_UPDATE_GOLDEN";function pr(e=typeof process<"u"?process.env:void 0){let t=e?.[lr];return t==="1"||t==="true"}function Jt(e){return Tt(Xe(e))}function fr(e,t,n={}){if(e.width!==t.width||e.height!==t.height){let h=qi(e,t);return{match:!1,differingPixels:e.width*e.height,width:e.width,height:e.height,artifacts:h,updatedGolden:!1}}let r=n.tolerance??0,i=n.perceptualThreshold,o=n.maxDifferingPixels??0,s=new Uint8ClampedArray(e.width*e.height*4),u=0;for(let h=0;h<e.data.length;h+=4){let m=Math.abs(e.data[h]-t.data[h]),A=Math.abs(e.data[h+1]-t.data[h+1]),D=Math.abs(e.data[h+2]-t.data[h+2]),x=Math.abs(e.data[h+3]-t.data[h+3]),v=.299*m+.587*A+.114*D,M=n.alphaTolerance??r;(i!==void 0?v<=i&&x<=M:m<=r&&A<=r&&D<=r&&x<=M)?(s[h]=0,s[h+1]=0,s[h+2]=0,s[h+3]=255):(u+=1,s[h]=255,s[h+1]=0,s[h+2]=255,s[h+3]=255)}let f=Xt(t,e,be(s,e.width,e.height),u);return n.updateGolden===!0||pr()?{match:!0,differingPixels:0,width:e.width,height:e.height,artifacts:Xt(e,e,be(s,e.width,e.height),0),updatedGolden:!0}:{match:u<=o,differingPixels:u,width:e.width,height:e.height,artifacts:f,updatedGolden:!1}}function mr(e,t,n={}){let r=fr(e,t,n);if(!r.match){let i=new Error(`Visual assertion failed: ${r.differingPixels} differing pixels (${r.width}\xD7${r.height}). Review expected/actual/diff PNG buffers on the result.`);throw i.visual=r,i}return r}function zi(e,t,n={}){return mr(Jt(e),Jt(t),n)}function Xt(e,t,n,r){let i=Ie(e.width,e.height,e.data),o=Ie(t.width,t.height,t.data),s=Ie(n.width,n.height,n.data);return{expectedPng:i,actualPng:o,diffPng:s,expectedDataUrl:Te(e.width,e.height,e.data),actualDataUrl:Te(t.width,t.height,t.data),diffDataUrl:Te(n.width,n.height,n.data),differingPixels:r}}function qi(e,t){let n=Math.max(e.width,t.width),r=Math.max(e.height,t.height),i=new Uint8ClampedArray(n*r*4);for(let o=0;o<i.length;o+=4)i[o]=255,i[o+1]=0,i[o+2]=255,i[o+3]=255;return Xt(t,e,be(i,n,r),n*r)}async function Yi(e,t,n={}){let{mkdir:r,writeFile:i}=await import("node:fs/promises"),{join:o}=await import("path");await r(e,{recursive:!0});let s=o(e,n.expected??"expected.png"),u=o(e,n.actual??"actual.png"),f=o(e,n.diff??"diff.png");return await i(s,t.expectedPng),await i(u,t.actualPng),await i(f,t.diffPng),{expectedPath:s,actualPath:u,diffPath:f}}var hr="cyberart.state.save",gr="cyberart.state.load";var ht=1,We="cyberart.diagnostic.rejected",Qt=8,Ji=new Set(["intent","state","diagnostic"]),Xi=new Set([hr,gr]);function yr(e){return typeof e=="string"&&Ji.has(e)}function Qi(e){if(e.kind!==void 0)return yr(e.kind)?e.kind:void 0;if(!(typeof e.type!="string"||e.type.length===0)){if(Xi.has(e.type))return"intent";for(let t of e.type.split("."))if(yr(t))return t}}function Zi(e,t){let n=e.split("."),r=t.split(".");if(n.length!==r.length)return!1;for(let i=0;i<n.length;i++)if(n[i]!=="*"&&n[i]!==r[i])return!1;return!0}function _e(e,t){for(let n of e)if(Zi(n,t))return!0;return!1}function eo(e){if(e===void 0)return{ok:!0,value:void 0};try{return{ok:!0,value:JSON.parse(JSON.stringify(e))}}catch{return{ok:!1}}}function Zt(e,t){if(!e||typeof e.type!="string"||e.type.length===0)return{ok:!1,reason:"malformed",detail:"type is required"};if(e.schemaVersion!==void 0&&e.schemaVersion!==ht)return{ok:!1,reason:"malformed",detail:`unsupported schemaVersion ${String(e.schemaVersion)}`};let n=Qi(e);if(!n)return{ok:!1,reason:"malformed",detail:`cannot infer kind from type "${e.type}"`};let r=eo(e.payload);if(!r.ok)return{ok:!1,reason:"malformed",detail:"payload is not JSON-serializable"};let i=t.createId(),o=typeof e.correlationId=="string"&&e.correlationId.length>0?e.correlationId:i,s=typeof e.causationId=="string"&&e.causationId.length>0?e.causationId:t.causationId,u=typeof e.target=="string"&&e.target.length>0?e.target:void 0,f=t.maxHops??Qt,b=t.parentHops===void 0?f:Math.max(0,t.parentHops-1),h=typeof e.idempotencyKey=="string"&&e.idempotencyKey.length>0?e.idempotencyKey:void 0,m={schemaVersion:ht,type:e.type,kind:n,source:t.source,id:i,correlationId:o,seq:t.seq,hops:b};return u&&(m.target=u),s&&(m.causationId=s),h&&(m.idempotencyKey=h),r.value!==void 0&&(m.payload=r.value),{ok:!0,envelope:m}}var to=new Set(["rate-limited","storm-detected","hop-limit","loop-detected","not-subscribed"]),no=8,ro=8,io=16,oo=256,so=256,ao=["*.intent.*"];function br(e={}){let t=e.hostSource??"host",n="router",r=e.maxPerTurn??no,i=e.maxCausationDepth??ro,o=e.maxHops??Qt,s=e.maxCorrelationPerTurn??io,u=e.maxIndex??oo,f=e.maxDecisions??so,b=e.maxPerWindow,h=e.windowMs??1e3,m=e.now??Date.now,A=0,D=e.createId??(()=>`evt-${++A}`),x=new Map,v=[],M=[],L=new Map,E=new Map,S=new Map,g=[],c=0,a=0,k=0;function V(l){try{return JSON.parse(JSON.stringify(l))}catch{return l}}function B(l){for(g.push(l);g.length>f;)g.shift();for(let C of M)try{C(V(l))}catch{}}function $(l,C){let P={outcome:C.outcome,source:C.source,type:l.type,kind:l.kind,envelopeId:l.id,deliveredTo:C.deliveredTo,hops:l.hops,seq:l.seq,correlationId:l.correlationId,schemaVersion:l.schemaVersion,turn:k,time:m()};return C.reason&&(P.reason=C.reason),C.detail&&(P.detail=C.detail),C.priorEnvelopeId&&(P.priorEnvelopeId=C.priorEnvelopeId),l.target&&(P.target=l.target),l.causationId&&(P.causationId=l.causationId),l.idempotencyKey&&(P.idempotencyKey=l.idempotencyKey),l.payload!==void 0&&(P.payload=V(l.payload)),P}let K=[],q=!1;function p(l,C,P){for(l.set(C,P);l.size>u;){let _=l.keys().next().value;if(_===void 0)break;l.delete(_)}}function F(l){p(L,l.id,{type:l.type,source:l.source,causationId:l.causationId,hops:l.hops,correlationId:l.correlationId,idempotencyKey:l.idempotencyKey})}function H(l,C){C&&(l.correlationId||(l.correlationId=C.correlationId),l.causationId||(l.causationId=C.id),!l.idempotencyKey&&C.idempotencyKey&&(l.idempotencyKey=`${C.idempotencyKey}::${l.type}`))}function j(l,C){if(l){let P=L.get(l);return P?P.hops:o}return C}function d(l,C){return`${l}\0${C}`}function y(l,C){l.idempotencyKey&&p(S,d(l.source,l.idempotencyKey),C)}function w(l,C){if(C)return S.get(d(l,C))}function I(l){return w(l.source,l.idempotencyKey)}function R(l){return l.seq+=1,l.seq}function T(l,C){if(!(typeof C.causationId=="string"&&C.causationId.length>0))return l.lastDelivered}function O(l){let C=new Set,P=new Set([`${l.type}\0${l.source}`]),_=l.causationId,N=0;for(;_;){if(N+=1,N>i||C.has(_))return!0;C.add(_);let W=L.get(_);if(!W)break;let le=`${W.type}\0${W.source}`;if(P.has(le))return!0;P.add(le),_=W.causationId}return!1}function U(l){let C=(E.get(l)??0)+1;return E.set(l,C),C}function G(l,C){b!==void 0&&(l.emitTimestamps=l.emitTimestamps.filter(P=>C-P<h))}function z(l,C){return(C.kind==="state"||C.kind==="diagnostic")&&!l.authoritative?!1:_e(l.emit,C.type)}function Z(l){for(let C of v)if(_e(C.patterns,l.type))try{C.listener(l)}catch{}}function X(l){let C=[];if(l.target){let P=x.get(l.target);return!P||!_e(P.subscribe,l.type)||(P.channel.dispatch(l),P.lastDelivered={id:l.id,hops:l.hops,correlationId:l.correlationId,idempotencyKey:l.idempotencyKey},C.push(P.id)),C}for(let P of x.values())_e(P.subscribe,l.type)&&(P.channel.dispatch(l),P.lastDelivered={id:l.id,hops:l.hops,correlationId:l.correlationId,idempotencyKey:l.idempotencyKey},C.push(P.id));return C}function se(l,C,P,_,N,W,le){let re={reason:_,eventType:C,source:P};N&&(re.detail=N),a+=1;let me=D(),Se={schemaVersion:ht,type:We,kind:"diagnostic",source:n,id:me,correlationId:W??me,seq:a,hops:0,payload:re};le&&(Se.causationId=le),F(Se);let ze=x.get(l);ze&&ze.channel.dispatch(Se),Z(Se)}function ee(l,C,P,_,N){if(se(l,N?.type??(typeof C.type=="string"?C.type:""),N?.source??l,P,_,N?.correlationId,N?.id),N?.idempotencyKey&&!to.has(P)&&y(N,{status:"rejected"}),N)B($(N,{outcome:"rejected",reason:P,detail:_,source:l,deliveredTo:[]}));else{let W={outcome:"rejected",reason:P,source:l,type:typeof C.type=="string"?C.type:"",deliveredTo:[],turn:k,time:m()};_&&(W.detail=_),typeof C.idempotencyKey=="string"&&(W.idempotencyKey=C.idempotencyKey),B(W)}}function ce(l,C){F(l),y(l,{status:"accepted",envelope:l}),U(l.correlationId),Z(l);let P=X(l);B($(l,{outcome:"accepted",source:C,deliveredTo:P}))}function ae(l,C,P,_){let N=_?.type??(typeof C.type=="string"?C.type:""),W={outcome:"duplicate",reason:"duplicate",detail:P.status==="accepted"?"idempotent accepted":"idempotent rejected",source:l,type:N,deliveredTo:[],turn:k,time:m()};_?(W.kind=_.kind,W.envelopeId=_.id,W.hops=_.hops,W.seq=_.seq,W.correlationId=_.correlationId,W.schemaVersion=_.schemaVersion,_.target&&(W.target=_.target),_.causationId&&(W.causationId=_.causationId),_.idempotencyKey&&(W.idempotencyKey=_.idempotencyKey),_.payload!==void 0&&(W.payload=V(_.payload))):typeof C.idempotencyKey=="string"&&(W.idempotencyKey=C.idempotencyKey),P.status==="accepted"&&(W.priorEnvelopeId=P.envelope.id,W.envelopeId||(W.envelopeId=P.envelope.id)),B(W)}function Q(l,C,P,_){if(!P.ok){ee(l,C,"malformed",P.detail);return}let N=P.envelope,W=I(N);if(W)return ae(l,C,W,N),W.status==="accepted"?W.envelope:void 0;if(N.hops<1){ee(l,C,"hop-limit","no hops remaining",N);return}if(N.target&&N.target!==t){let le=x.get(N.target);if(!le){ee(l,C,"unknown-target",`unknown target "${N.target}"`,N);return}if(!_e(le.subscribe,N.type)){ee(l,C,"not-subscribed",`target "${N.target}" does not subscribe to ${N.type}`,N);return}}if(_){if(!z(_,N)){ee(l,C,"unauthorized","source may not emit this event",N);return}if(_.emitsThisTurn+=1,_.emitsThisTurn>r){ee(l,C,"rate-limited","maxPerTurn exceeded",N);return}if(b!==void 0){let re=m();if(G(_,re),_.emitTimestamps.push(re),_.emitTimestamps.length>b){ee(l,C,"rate-limited","maxPerWindow exceeded",N);return}}if(O(N)){ee(l,C,"loop-detected","causation chain cycle or depth exceeded",N);return}if((E.get(N.correlationId)??0)+1>s){ee(l,C,"storm-detected","correlationId storm",N);return}if(e.validate){let re;try{re=e.validate(N)}catch(me){let Se=me instanceof Error?me.message:"validate threw";ee(l,C,"host-rejected",Se,N);return}if(re!==!0){ee(l,C,"host-rejected",re.detail,N);return}}}else{if(O(N)){ee(l,C,"loop-detected","causation chain cycle or depth exceeded",N);return}if((E.get(N.correlationId)??0)+1>s){ee(l,C,"storm-detected","correlationId storm",N);return}}return ce(N,l),N}function ne(l,C){let P=x.get(l);if(!P)return;let _={...C},N=T(P,_);H(_,N);let W=w(P.id,_.idempotencyKey);if(W){ae(l,_,W);return}let le=R(P),re=Zt(_,{source:P.id,createId:D,seq:le,causationId:N?.id,maxHops:o,parentHops:j(_.causationId??N?.id,N?.hops)});Q(l,_,re,P)}function xe(l,C){let P=C?.cause,_={...l};H(_,P);let N=w(t,_.idempotencyKey);if(N)return ae(t,_,N),N.status==="accepted"?N.envelope:void 0;c+=1;let W=Zt(_,{source:t,createId:D,seq:c,causationId:_.causationId,maxHops:o,parentHops:j(_.causationId,P?.hops)});return Q(t,_,W,void 0)}function Ee(){if(!q){q=!0;try{for(;K.length>0;){let l=K.shift();l&&(l.kind==="cart"?ne(l.participantId,l.event):l.result=xe(l.event,l.extras))}}finally{q=!1}}}function ve(l){K.push(l),Ee()}return{attach(l,C,P={}){if(l===t||l===n)throw new Error(`createEventRouter: "${l}" is a reserved participant id`);for(let W of x.values())if(W.channel===C&&W.id!==l)throw new Error(`createEventRouter: channel already attached as "${W.id}"`);x.get(l)?.unsubscribe();let N={id:l,channel:C,emit:P.emit??ao,subscribe:P.subscribe??[],authoritative:P.authoritative===!0,seq:0,emitsThisTurn:0,emitTimestamps:[],unsubscribe:()=>{}};N.unsubscribe=C.onEvent(W=>{ve({kind:"cart",participantId:l,event:W})}),x.set(l,N)},detach(l){let C=x.get(l);C&&(C.unsubscribe(),x.delete(l))},publish(l,C){let P={kind:"publish",event:l,extras:C};return ve(P),P.result},subscribe(l,C){let P={patterns:l,listener:C};return v.push(P),()=>{let _=v.indexOf(P);_>=0&&v.splice(_,1)}},subscribeDecision(l){return M.push(l),()=>{let C=M.indexOf(l);C>=0&&M.splice(C,1)}},inspectParticipants(){return[...x.values()].map(l=>({id:l.id,emit:l.emit.slice(),subscribe:l.subscribe.slice(),authoritative:l.authoritative}))},inspectDecisions(){return g.map(l=>V(l))},turn(){k+=1,E.clear();for(let l of x.values())l.emitsThisTurn=0,l.lastDelivered=void 0,b!==void 0&&G(l,m())}}}var uo=320,co=180,lo=1024,po="Runtime group has been destroyed";function fo(e){let t="";for(let n=0;n<32;n++){let r=e.charCodeAt(n%Math.max(e.length,1))+n*17&255;t+=r.toString(16).padStart(2,"0")}return`0x${t}`}function mo(e,t){let n=document.createElement("div");return Object.defineProperty(n,"clientWidth",{value:e,configurable:!0}),Object.defineProperty(n,"clientHeight",{value:t,configurable:!0}),document.body.appendChild(n),n}function Sr(e){let t=e.capability,n={},r=e.emit??t?.emit,i=e.subscribe??t?.subscribe,o=e.authoritative??t?.authoritative;return r&&(n.emit=r),i&&(n.subscribe=i),o!==void 0&&(n.authoritative=o),n}function vr(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function ho(e){let t=new Set([We,"*.*","*.*.*","*.*.*.*","*.*.*.*.*"]);for(let n of e){let r=Sr(n);for(let i of r.emit??[])t.add(i);for(let i of r.subscribe??[])t.add(i)}return[...t]}function wr(e){if(!e.participants.length)throw new Error("createRuntimeGroup: at least one participant is required");let t=new Set;for(let a of e.participants){if(!a.id)throw new Error("createRuntimeGroup: participant id is required");if(t.has(a.id))throw new Error(`createRuntimeGroup: duplicate participant id "${a.id}"`);t.add(a.id)}let n=e.origin??0,r=e.width??uo,i=e.height??co,o=e.maxTrace??lo,s=[...e.participants].sort((a,k)=>a.id.localeCompare(k.id)),u=[],f=new Map,b=0,h=e.createId??e.router?.createId??(()=>`evt-${++b}`),m=e.now??e.router?.now??(()=>{let a=u[0];if(!a)return n;try{return a.cart.getClock().now}catch{return n}}),A=br({...e.router,createId:h,now:m,validate:e.validate??e.router?.validate}),D=[],x=!1,v=!1,M=()=>{},L=a=>k=>{a.events.push(k),a.userOnEvent?.(k)},E=()=>{if(v)throw new Error(po)},S=()=>{M();for(let a of u){try{A.detach(a.id)}catch{}try{a.runtime.destroy()}catch{}a.ownsContainer&&a.container.remove()}u.length=0,f.clear()};try{for(let a of s){let k=a.width??r,V=a.height??i,B=!a.container,$=a.container??mo(k,V),K=ft({container:$,seed:a.seed??fo(a.id),deterministic:{origin:n},audioBroker:e.audioBroker,audioParticipantId:e.audioBroker?a.id:void 0}),q={id:a.id,kind:a.kind??"render",cartDef:a.cart,initialState:a.initialState,gameManager:a.gameManager,userOnEvent:a.onEvent,runtime:K,container:$,ownsContainer:B,cart:void 0,events:[],errors:[]};K.onError=(p,F)=>{q.errors.push({error:p,info:F})},A.attach(a.id,K.hostChannel,Sr(a)),q.cart=K.mount(a.cart,{initialState:a.initialState,gameManager:a.gameManager,onEvent:L(q)}),u.push(q),f.set(q.id,q)}M=A.subscribe(ho(s),a=>{for(D.push(vr(a));D.length>o;)D.shift()})}catch(a){throw S(),a}let g=a=>({id:a.id,kind:a.kind,runtime:a.runtime,container:a.container,get events(){return a.events.slice()},get errors(){return a.errors.slice()},get cart(){return a.cart}});return{router:A,origin:n,get paused(){return x},get audioBroker(){return e.audioBroker},participant(a){E();let k=f.get(a);if(!k)throw new Error(`createRuntimeGroup: unknown participant "${a}"`);return g(k)},async step(a=1){if(E(),x)return;let k=Math.max(0,Math.floor(a));for(let V=0;V<k;V++){A.turn();for(let B of u)try{await B.cart.step(1)}catch($){B.errors.push({error:$,info:{phase:"update",consecutive:B.errors.length+1,stopped:!1}})}}},pause(){E(),x=!0;for(let a of u)a.cart.pause()},resume(){E(),x=!1;for(let a of u)a.cart.resume()},reset(){E(),D.length=0;for(let a of u)a.events.length=0,a.errors.length=0,a.cart=a.runtime.mount(a.cartDef,{initialState:a.initialState,gameManager:a.gameManager,onEvent:L(a)});A.turn()},resize(a,k){E();let V=Math.max(1,a|0),B=Math.max(1,k|0);for(let $ of u){Object.defineProperty($.container,"clientWidth",{value:V,configurable:!0}),Object.defineProperty($.container,"clientHeight",{value:B,configurable:!0});let K=$.cart.canvas;K&&(K.width=V,K.height=B)}},detach(a){E();let k=f.get(a);if(!k)throw new Error(`createRuntimeGroup: unknown participant "${a}"`);try{A.detach(k.id)}catch{}try{k.runtime.destroy()}catch{}e.audioBroker&&e.audioBroker.teardown(k.id),k.ownsContainer&&k.container.remove();let V=u.indexOf(k);V>=0&&u.splice(V,1),f.delete(a)},dispatch(a,k){E();let V=f.get(a);if(!V)throw new Error(`createRuntimeGroup: unknown participant "${a}"`);V.cart.dispatch(k)},publish(a,k){return E(),A.publish(a,k)},inspectParticipants(){E();let a=new Map(u.map(k=>[k.id,k.kind]));return A.inspectParticipants().map(k=>({...k,kind:a.get(k.id)??"render"}))},async inspect(){E();let a={},k={},V=new Map(A.inspectParticipants().map($=>[$.id,$]));for(let $ of u){let K=await $.cart.getReplayMetadata(),q=$.cart.getClock();k[$.id]=q;let p=V.get($.id);a[$.id]={state:K.state,events:$.events.slice(),errors:$.errors.slice(),kind:$.kind,clock:q,emit:p?.emit.slice()??[],subscribe:p?.subscribe.slice()??[],authoritative:p?.authoritative===!0}}let B=D.map($=>vr($));return{participants:a,trace:B,diagnostics:{paused:x,participantIds:u.map($=>$.id),clocks:k,rejections:B.filter($=>$.type===We).map($=>$.payload)}}},destroy(){if(!v){v=!0,x=!1;try{S()}finally{D.length=0}}}}}function go(e){return mt(),wr(e)}var en=1,yo=512,bo="[REDACTED]",vo=new Set([Ce,ke]);function de(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function gt(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(i=>gt(i,t));if(typeof e!="object")return e;let n=e,r={};for(let[i,o]of Object.entries(n))r[i]=t.has(i)?bo:gt(o,t);return r}function So(e){return e instanceof Error&&typeof e.message=="string"?e.message:"error"}function wo(e,t){return t?!(t.types&&!t.types.includes(e.type)||t.sources&&!t.sources.includes(e.source)||t.outcomes&&!t.outcomes.includes(e.outcome)||t.correlationId&&e.correlationId!==t.correlationId):!0}function Ar(e){return JSON.stringify({outcome:e.outcome,reason:e.reason,source:e.source,target:e.target,type:e.type,kind:e.kind,envelopeId:e.envelopeId,priorEnvelopeId:e.priorEnvelopeId,correlationId:e.correlationId,causationId:e.causationId,hops:e.hops,seq:e.seq,idempotencyKey:e.idempotencyKey,deliveredTo:e.deliveredTo,payload:e.payload})}function Ao(e,t){if(e.length!==t.length)return{ok:!1,detail:`record count ${t.length} !== ${e.length}`};for(let n=0;n<e.length;n++){let r=Ar(e[n]),i=Ar(t[n]);if(r!==i)return{ok:!1,detail:`record ${n} differs`}}return{ok:!0}}function Er(e){let t=new Map,n=[];for(let o of e){if(o.outcome==="duplicate"){n.push(void 0);continue}let s={envelopeId:o.envelopeId,type:o.type,source:o.source,outcome:o.outcome,children:[]};o.reason&&(s.reason=o.reason),n.push(s),o.envelopeId&&!t.has(o.envelopeId)&&t.set(o.envelopeId,s)}let r=new Set;for(let o=0;o<e.length;o++){let s=e[o],u=n[o];if(!u)continue;let f=s.causationId?t.get(s.causationId):void 0;f&&f!==u&&(f.children.push(u),r.add(u))}let i=[];for(let o of n)o&&!r.has(o)&&i.push(o);return i}function Cr(e,t){let n={id:e.id,emit:e.emit.slice(),subscribe:e.subscribe.slice(),authoritative:e.authoritative,errorCount:0};return t&&(n.kind=t),n}function Eo(e,t,n){let r=t.errors[t.errors.length-1],i={id:e,kind:t.kind,emit:t.emit.slice(),subscribe:t.subscribe.slice(),authoritative:t.authoritative,clock:de(t.clock),state:gt(t.state,n),errorCount:t.errors.length};return r&&(i.lastError=So(r.error)),i}function kr(e={}){let t=new Set(e.redactedKeys??[]),n=e.maxRecords??yo,r=e.registry,i=0,o=0,s=!1,u=[],f=[],b,h=[],m=0,A=[],D={},x=()=>{},v=()=>{if(s)throw new Error("Replay inspector has been destroyed")},M=g=>{let c=r?.get(g.type),a={index:o,turn:g.turn,time:g.time,outcome:g.outcome,source:g.source,type:g.type,deliveredTo:g.deliveredTo.slice(),payload:gt(g.payload,t)};for(o+=1,g.reason&&(a.reason=g.reason),g.detail&&(a.detail=g.detail),g.target&&(a.target=g.target),g.kind&&(a.kind=g.kind),g.envelopeId&&(a.envelopeId=g.envelopeId),g.priorEnvelopeId&&(a.priorEnvelopeId=g.priorEnvelopeId),g.correlationId&&(a.correlationId=g.correlationId),g.causationId&&(a.causationId=g.causationId),g.hops!==void 0&&(a.hops=g.hops),g.seq!==void 0&&(a.seq=g.seq),g.idempotencyKey&&(a.idempotencyKey=g.idempotencyKey),g.schemaVersion!==void 0&&(a.schemaVersion=g.schemaVersion),c&&(a.payloadSchemaVersion=c.payloadSchema.version),u.push(a);u.length>n;)u.shift(),i+=1},L=g=>u.filter(c=>wo(c,g)).map(c=>de(c)),E=g=>g?g.inspectParticipants().map(c=>Cr(c,c.kind)):A.map(c=>de(c)),S={watchRouter(g){if(v(),x(),A=g.inspectParticipants().map(a=>Cr(a)),u.length===0)for(let a of g.inspectDecisions())M(a);let c=g.subscribeDecision(a=>M(a));return x=()=>{c(),x=()=>{}},f.push(x),x},bind(g){v(),b&&x(),b=g,m=g.origin,S.watchRouter(g.router),A=E(g);let c={publish(a,k){v();let V={kind:"publish",event:de(a)};return k?.cause&&(V.extras={cause:de(k.cause)}),h.push(V),g.publish(a,k)},dispatch(a,k){v();let V=de(k);typeof V.type=="string"&&vo.has(V.type)?h.push({kind:"asset",participantId:a,event:V}):h.push({kind:"dispatch",participantId:a,event:V}),g.dispatch(a,k)},async step(a=1){v(),h.push({kind:"step",frames:a}),await g.step(a)},async report(){v();let a=await g.inspect(),k=[];for(let V of Object.keys(a.participants).sort())k.push(Eo(V,a.participants[V],t));A=k,D={};for(let V of k)D[V.id]=de(V.state);return S.report()},async exportTrace(a){return await c.report(),S.exportTrace(a)},unbind(){x(),b=void 0}};return c},importTrace(g){v();let c=typeof g=="string"?JSON.parse(g):g;if(c.schemaVersion!==en)throw new Error("Replay inspector: unsupported export schemaVersion");i=0,o=0,u.length=0,h=de(c.tape??[]),m=c.origin??0,A=de(c.participants??[]),D=de(c.snapshots??{});for(let a of c.records??[])M({outcome:a.outcome,reason:a.reason,detail:a.detail,source:a.source,type:a.type,kind:a.kind,envelopeId:a.envelopeId,priorEnvelopeId:a.priorEnvelopeId,target:a.target,deliveredTo:a.deliveredTo,hops:a.hops,seq:a.seq,correlationId:a.correlationId,causationId:a.causationId,idempotencyKey:a.idempotencyKey,schemaVersion:a.schemaVersion,payload:a.payload,turn:a.turn,time:a.time})},exportTrace(g){return v(),{schemaVersion:en,origin:m,redactedKeys:[...t],participants:de(A),tape:de(h),records:L(g),snapshots:de(D)}},report(g){v();let c=L(g);return{schemaVersion:en,participants:de(A),records:c,trees:Er(c),dropped:i}},causationTree(g){v();let c=L(g?{correlationId:g}:void 0);return Er(c)},records(){return v(),u.map(g=>de(g))},reset(){v(),u.length=0,h=[],i=0,o=0,D={},b&&(A=E(b))},destroy(){if(!s){for(s=!0,x();f.length>0;)f.pop()?.();u.length=0,h=[],A=[],D={},b=void 0}}};return S}async function Co(e,t,n={}){let r=kr({redactedKeys:n.redactedKeys??e.redactedKeys,maxRecords:n.maxRecords,registry:n.registry}),i=r.bind(t);try{for(let s of e.tape)s.kind==="publish"?i.publish(s.event,s.extras):s.kind==="dispatch"||s.kind==="asset"?i.dispatch(s.participantId,s.event):await i.step(s.frames);let o=await i.report();return{inspector:r,report:o}}catch(o){throw r.destroy(),o}}var bt="cue.started",nn="cue.completed",vt="cue.cancelled",je="cue.replaced";function ko(e,t){let n=e<0?0:e>1?1:e;return t==="ease-out"?1-(1-n)*(1-n):n}function xr(e){return{type:e.type,atFrame:e.atFrame,name:e.name,idempotencyKey:e.idempotencyKey,progress:e.progress}}function yt(e){return{name:e.name,idempotencyKey:e.idempotencyKey,phase:e.phase,startFrame:e.startFrame,durationFrames:e.durationFrames,delayFrames:e.delayFrames,easing:e.easing,progress:e.progress,repeatIndex:e.repeatIndex}}function tn(e){return e.startFrame+e.delayFrames}function xo(e,t){if(!e||typeof e!="object")return{ok:!1,reason:"invalid",detail:"spec is required"};if(typeof e.name!="string"||e.name.length===0)return{ok:!1,reason:"invalid",detail:"name is required"};if(typeof e.idempotencyKey!="string"||e.idempotencyKey.length===0)return{ok:!1,reason:"invalid",detail:"idempotencyKey is required"};if(typeof e.durationFrames!="number"||!Number.isFinite(e.durationFrames)||e.durationFrames<0)return{ok:!1,reason:"invalid",detail:"durationFrames must be a non-negative finite number"};let n=e.startFrame===void 0?t:e.startFrame;if(typeof n!="number"||!Number.isFinite(n))return{ok:!1,reason:"invalid",detail:"startFrame must be finite"};let r=e.delayFrames??0;if(typeof r!="number"||!Number.isFinite(r)||r<0)return{ok:!1,reason:"invalid",detail:"delayFrames must be a non-negative finite number"};let i=e.easing??"linear";if(i!=="linear"&&i!=="ease-out")return{ok:!1,reason:"invalid",detail:"unsupported easing"};let o=e.onDuplicate??"replace";if(o!=="ignore"&&o!=="replace"&&o!=="reject")return{ok:!1,reason:"invalid",detail:"unsupported onDuplicate"};let s=0;if(e.repeat)if("forever"in e.repeat&&e.repeat.forever)s="forever";else if("count"in e.repeat){if(typeof e.repeat.count!="number"||!Number.isFinite(e.repeat.count)||e.repeat.count<0)return{ok:!1,reason:"invalid",detail:"repeat.count must be >= 0"};s=Math.floor(e.repeat.count)}else return{ok:!1,reason:"invalid",detail:"unsupported repeat"};let u=e.reducedMotion??"complete";return u!=="skip"&&u!=="complete"&&(typeof u!="object"||typeof u.durationFrames!="number"||!Number.isFinite(u.durationFrames)||u.durationFrames<0)?{ok:!1,reason:"invalid",detail:"unsupported reducedMotion"}:{name:e.name,idempotencyKey:e.idempotencyKey,startFrame:n,durationFrames:e.durationFrames,delayFrames:r,easing:i,repeatRemaining:s,repeatIndex:0,reducedMotion:u,onDuplicate:o,phase:"scheduled",progress:0}}function Ro(e,t){if(!t)return e;let n=e.reducedMotion;return n==="skip"||n==="complete"?{...e,durationFrames:0,delayFrames:0,startFrame:e.startFrame}:{...e,durationFrames:n.durationFrames}}function Rr(e={}){let t=!!e.reducedMotion,n=e.originFrame??0,r=new Map,i=[];function o(v){i.push(v)}function s(v,M){let L=tn(v)-tn(M);return L!==0?L:v.name<M.name?-1:v.name>M.name?1:v.idempotencyKey<M.idempotencyKey?-1:v.idempotencyKey>M.idempotencyKey?1:0}function u(v,M){o({type:M,atFrame:n,name:v.name,idempotencyKey:v.idempotencyKey,progress:v.progress})}function f(v){if(v.phase="completed",v.progress=1,u(v,nn),v.repeatRemaining==="forever"||v.repeatRemaining>0){if(typeof v.repeatRemaining=="number"&&(v.repeatRemaining-=1),v.repeatIndex+=1,v.phase="scheduled",v.progress=0,v.startFrame=n,v.delayFrames=0,v.durationFrames===0){r.delete(v.idempotencyKey);return}v.phase="active",u(v,bt)}else r.delete(v.idempotencyKey)}function b(v){if(v.phase==="cancelled"||v.phase==="completed")return;let M=tn(v);if(!(n<M)){if(v.phase==="scheduled"&&(v.phase="active",v.progress=v.durationFrames===0?1:0,u(v,bt),v.durationFrames===0)){f(v);return}if(v.phase==="active"){let L=n-M;L>=v.durationFrames?(v.progress=1,f(v)):v.progress=ko(v.durationFrames===0?1:L/v.durationFrames,v.easing)}}}function h(){let v=[...r.values()].sort(s);for(let M of v)b(M)}function m(v){let M=xo(v,n);if("ok"in M&&M.ok===!1)return M;let L=Ro(M,t),E=r.get(L.idempotencyKey);if(E&&(E.phase==="scheduled"||E.phase==="active")){if(E.onDuplicate==="reject"||L.onDuplicate==="reject")return{ok:!1,reason:"duplicate",detail:`cue ${L.idempotencyKey} is already ${E.phase}`};if(E.onDuplicate==="ignore"||L.onDuplicate==="ignore")return{ok:!0,cue:yt(E)};E.phase="cancelled",E.progress=E.progress,u(E,je),r.delete(E.idempotencyKey)}r.set(L.idempotencyKey,L),b(L);let S=r.get(L.idempotencyKey)??L;return{ok:!0,cue:yt(S)}}function A(v){let M=r.get(v);return!M||M.phase==="completed"||M.phase==="cancelled"?!1:(M.phase="cancelled",u(M,vt),r.delete(v),!0)}function D(){for(let v of[...r.values()].sort(s))(v.phase==="scheduled"||v.phase==="active")&&(v.phase="cancelled",u(v,vt));r.clear(),i.length=0,n=e.originFrame??0}function x(v=1){let M=Number.isFinite(v)?Math.max(0,Math.floor(v)):0,L=i.length;for(let E=0;E<M;E++)n+=1,h();return i.slice(L).map(xr)}return{play:m,step:x,cancel:A,reset:D,snapshot(){return{frame:n,reducedMotion:t,cues:[...r.values()].sort(s).map(yt),events:i.map(xr)}},get(v){let M=r.get(v);return M?yt(M):void 0},get frame(){return n},get reducedMotion(){return t}}}var Io="audio.cue.scheduled",To="audio.cue.started",Po="audio.cue.skipped",Do="audio.cue.failed";function rn(e){let t={type:e.type,atFrame:e.atFrame,name:e.name,idempotencyKey:e.idempotencyKey,assetId:e.assetId,channelId:e.channelId,progress:e.progress};return e.participantId!==void 0&&(t.participantId=e.participantId),e.reason!==void 0&&(t.reason=e.reason),t}function Mo(e){return{name:e.name,idempotencyKey:e.idempotencyKey,startFrame:e.startFrame,durationFrames:e.durationFrames,delayFrames:e.delayFrames,easing:e.easing,repeat:e.repeat,reducedMotion:e.reducedMotion,onDuplicate:e.onDuplicate}}function St(e,t,n){return{name:e.name,idempotencyKey:e.idempotencyKey,phase:t?.phase??(e.audioPhase==="started"?"active":"scheduled"),startFrame:t?.startFrame??n,durationFrames:t?.durationFrames??0,delayFrames:t?.delayFrames??0,easing:t?.easing??"linear",progress:t?.progress??0,repeatIndex:t?.repeatIndex??0,assetId:e.assetId,channelId:e.channelId,participantId:e.participantId,priority:e.priority,audioPhase:e.audioPhase}}function Fo(e={}){let t=e.broker,n=!!(e.reducedSensory??t?.reducedSensory),r=Rr({originFrame:e.originFrame}),i=new Map,o=[],s=new Set,u=0;function f(c){o.push(c)}function b(c,a,k){let V=r.get(a.idempotencyKey);return rn({type:c,atFrame:r.frame,name:a.name,idempotencyKey:a.idempotencyKey,assetId:a.assetId,channelId:a.channelId,participantId:a.participantId,reason:k?.reason,progress:k?.progress??V?.progress??0})}function h(c,a){s.delete(c.idempotencyKey),t?.noteCueEnded(c.idempotencyKey),c.audioPhase="failed",f(b(Do,c,{reason:a})),r.cancel(c.idempotencyKey),i.delete(c.idempotencyKey)}function m(c,a){s.delete(c.idempotencyKey),c.audioPhase="skipped",f(b(Po,c,{reason:a}))}function A(c){s.delete(c.idempotencyKey),c.audioPhase="started",t?.noteCueStarted({idempotencyKey:c.idempotencyKey,channelId:c.channelId,participantId:c.participantId,priority:c.priority}),f(b(To,c))}function D(c){if(c.audioPhase!=="scheduled")return;if(t&&!t.isAuthorized(c.participantId)){m(c,"unauthorized"),r.cancel(c.idempotencyKey),i.delete(c.idempotencyKey);return}if(n||t?.reducedSensory){m(c,"reduced-sensory");return}if(t?.muted||t&&t.effectiveGain(c.channelId)===0){m(c,"muted");return}let a=t?.assetStatus(c.assetId);if(!t){A(c);return}if(a==="failed"){h(c,"asset-failed");return}if(a==="ready"){A(c);return}s.add(c.idempotencyKey)}function x(c,a){for(let k of[...s]){let V=i.get(k);if(!V){s.delete(k);continue}if(!(c&&V.assetId!==c)){if(a==="failed"||t?.assetStatus(V.assetId)==="failed"){h(V,"asset-failed");continue}(a==="ready"||t?.assetStatus(V.assetId)==="ready")&&D(V)}}}function v(c){for(let a of[...i.values()])a.participantId===c&&(a.audioPhase==="scheduled"||a.audioPhase==="started")&&h(a,"torn-down")}function M(c){for(let a of c){let k=i.get(a.idempotencyKey);if(k)if(a.type===bt)D(k);else if(a.type===nn){if(s.delete(k.idempotencyKey),t?.noteCueEnded(k.idempotencyKey),r.get(k.idempotencyKey)){k.audioPhase="scheduled";continue}k.audioPhase==="scheduled"?h(k,"asset-failed"):(k.audioPhase==="started"&&(k.audioPhase="completed"),i.delete(k.idempotencyKey))}else a.type===vt?(s.delete(k.idempotencyKey),t?.noteCueEnded(k.idempotencyKey),(k.audioPhase==="scheduled"||k.audioPhase==="started")&&(k.audioPhase="failed"),i.delete(k.idempotencyKey)):a.type===je&&(s.delete(k.idempotencyKey),t?.noteCueEnded(k.idempotencyKey),i.delete(k.idempotencyKey))}}function L(){let c=o.slice(u).map(rn);return u=o.length,c}let E=t?.onNotice(c=>{if(c.type==="asset"){if(c.status==="failed"){for(let a of[...i.values()])a.assetId===c.id&&(a.audioPhase==="scheduled"||a.audioPhase==="started")&&h(a,"asset-failed");return}x(c.id,c.status);return}if(c.type==="teardown"){v(c.participantId);return}if(c.type==="destroy")for(let a of[...i.values()])(a.audioPhase==="scheduled"||a.audioPhase==="started")&&h(a,"torn-down")});function S(){for(let c of i.values())t?.noteCueEnded(c.idempotencyKey);i.clear(),s.clear(),o.length=0,u=0,r.reset()}function g(c){if(!c||typeof c!="object")return{ok:!1,reason:"invalid",detail:"spec is required"};if(typeof c.assetId!="string"||c.assetId.length===0)return{ok:!1,reason:"invalid",detail:"assetId is required"};let a=r.snapshot().events.length,k=r.play(Mo(c));if(!k.ok)return k;let V=r.snapshot().events.slice(a),B=V.some(H=>H.type===je);if(!B&&i.has(c.idempotencyKey)){let H=i.get(c.idempotencyKey);return{ok:!0,cue:St(H,k.cue,r.frame)}}if(B){let H=i.get(c.idempotencyKey);H&&(s.delete(H.idempotencyKey),t?.noteCueEnded(H.idempotencyKey),i.delete(H.idempotencyKey))}let $=c.channelId??c.participantId??"master",K={name:c.name,idempotencyKey:c.idempotencyKey,assetId:c.assetId,channelId:$,participantId:c.participantId,priority:Number.isFinite(c.priority)?c.priority:0,audioPhase:"scheduled"};i.set(K.idempotencyKey,K),typeof c.gain=="number"&&t?.setChannelGain($,c.gain,c.participantId),typeof c.priority=="number"&&t?.setPriority($,c.priority,c.participantId),f(b(Io,K)),M(V.filter(H=>H.type!==je));let q=i.get(K.idempotencyKey);q&&q.audioPhase==="scheduled"&&t?.assetStatus(q.assetId)==="failed"&&h(q,"asset-failed"),L();let p=i.get(K.idempotencyKey)??K,F=r.get(K.idempotencyKey)??k.cue;return{ok:!0,cue:St(p,F,r.frame)}}return{play:g,step(c=1){let a=r.step(c);return M(a),L()},cancel(c){let a=i.get(c),k=r.cancel(c);return a&&(s.delete(c),t?.noteCueEnded(c),i.delete(c)),k},reset:S,snapshot(){return{frame:r.frame,reducedSensory:n,cues:[...i.values()].map(c=>St(c,r.get(c.idempotencyKey),r.frame)).sort((c,a)=>c.name!==a.name?c.name<a.name?-1:1:c.idempotencyKey<a.idempotencyKey?-1:c.idempotencyKey>a.idempotencyKey?1:0),events:o.map(rn)}},get(c){let a=i.get(c);if(a)return St(a,r.get(c),r.frame)},dispose(){E?.(),S()},get frame(){return r.frame},get reducedSensory(){return n}}}function Ho(e={}){let t=or({toneStart:async()=>{},reducedSensory:e.reducedSensory}),n=Fo({broker:t,originFrame:e.originFrame,reducedSensory:e.reducedSensory});return{broker:t,timeline:n,unlock(){return t.unlock()},play(r){return n.play(r)},step(r){return n.step(r)},handleHostEvent(r){t.handleHostEvent(r)},snapshot(){return{...n.snapshot(),unlock:t.status(),muted:t.muted}},destroy(){n.dispose(),t.destroy()}}}async function Ea(e,t){let n=e.captureComposedFrame();if(!t)return n;let{writeFile:r}=await import("node:fs/promises");return await r(t,Xe(n.pngDataUrl)),{...n,path:t}}export{dr as DEFAULT_HEADLESS_HEIGHT,ur as DEFAULT_HEADLESS_WIDTH,ar as HEADLESS_PNG_DATA_URL,Y as HeadlessUnsupportedOperationError,lr as UPDATE_GOLDEN_ENV,mr as assertPixelsEqual,zi as assertPngDataUrlsEqual,It as attachHeadlessCanvas2D,fr as compareImageData,Ao as compareReplayTraces,mn as createDefaultGlyphAtlas,Ho as createHeadlessAudioAdapter,ji as createHeadlessHarness,go as createHeadlessMultiCartHarness,Dr as createImageFixture,kr as createReplayInspector,Tt as decodePng,Ie as encodePng,Te as encodePngDataUrl,Mr as getHeadlessSurface,Jt as imageDataFromPngDataUrl,mt as installHeadlessCanvas,be as makeImageData,Co as replayExportedTrace,Rt as setDefaultGlyphAtlas,pr as shouldUpdateGolden,Ea as writeComposedFrame,Yi as writeVisualArtifacts};