@cyberart-io/engine 0.0.4 → 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/README.md +102 -21
- package/dist/headless.d.ts +779 -68
- package/dist/headless.js +1 -1
- package/dist/index.d.ts +1144 -9
- package/dist/index.js +1 -1
- package/docs/asset-resolver.md +4 -4
- package/docs/audio.md +152 -0
- package/docs/browser-harness.md +126 -0
- package/docs/capability-manifest.md +18 -7
- package/docs/compositor.md +103 -0
- package/docs/deterministic-mode.md +1 -1
- package/docs/events.md +75 -13
- package/docs/executable-modules.md +112 -0
- package/docs/headless-harness.md +44 -14
- package/docs/midi.md +128 -0
- package/docs/presentation-adapter.md +8 -8
- package/docs/presentation-cue.md +2 -2
- package/docs/replay-inspector.md +88 -0
- package/docs/runtime-group.md +9 -7
- package/docs/snapshots.md +102 -0
- package/package.json +1 -1
package/dist/headless.js
CHANGED
|
@@ -5,4 +5,4 @@
|
|
|
5
5
|
* Not an OSI open-source license.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
var Kt=(e,t)=>()=>(e&&(t=e(e=0)),t);var Jt={};function qt(e,t){let n=e.indexOf(ct);if(n===-1)return null;let r=n+ct.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 Ie,we,zt,le,ct,lt=Kt(()=>{"use strict";Ie=/AudioWorkletProcessor with name:\s*["'`][^"'`]+["'`]\s+is already registered/i,we="__cyberartWorkletPatchApplied";typeof window<"u"&&!window[we]&&(window.addEventListener("error",e=>{let t=e?.message??"";Ie.test(t)&&(e.preventDefault(),e.stopImmediatePropagation())},!0),window.addEventListener("unhandledrejection",e=>{let t=e?.reason,n=typeof t=="string"?t:t?.message??"";Ie.test(n)&&e.preventDefault()}),window[we]=!0);zt=!1,le=(...e)=>{zt&&console.log("[workletPatch]",...e)},ct="((AudioWorkletProcessor,registerProcessor)=>{";if(typeof AudioWorklet<"u"&&!AudioWorklet.prototype[we]){let e=new WeakMap,t=/registerProcessor\s*\(\s*['"`]([^'"`]+)['"`]/g,n=AudioWorklet.prototype.addModule,r=0;AudioWorklet.prototype.addModule=async function(o,u){let p=++r,m=e.get(this);m||(m=new Set,e.set(this,m)),le(`#${p} addModule`,{url:o.slice(0,64),isBlob:o.startsWith("blob:"),knownBefore:[...m]});let C=o,v=null;if(o.startsWith("blob:")){let l=null;try{l=await(await fetch(o)).text()}catch(w){le(`#${p} blob fetch failed`,w)}if(l!==null){let w=new Set;for(let E of l.matchAll(t))w.add(E[1]);if(w.size>0){let E=[...w].filter(M=>m.has(M)),b=[...w].filter(M=>!m.has(M));if(E.length>0&&b.length===0){le(`#${p} short-circuit \u2014 all processors already registered`,E);return}if(E.length>0&&b.length>0){let M=qt(l,E);if(M!==null){let h=new Blob([M],{type:"application/javascript"});v=URL.createObjectURL(h),C=v,le(`#${p} rewrote blob; skipping`,E,"allowing",b)}else le(`#${p} blob rewrite failed; passing original through`)}b.forEach(M=>m.add(M))}}}return n.call(this,C,u).then(()=>{v&&URL.revokeObjectURL(v)},l=>{v&&URL.revokeObjectURL(v);let w=(l&&l.message)??"";if(!(Ie.test(w)||/already registered/i.test(w)))throw l})},AudioWorklet.prototype[we]=!0}});var Je=()=>{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"]},G=window.devicePixelRatio||1,re=/Headless/i.test(navigator.userAgent),jn=/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)||/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform);function Ye(){return Math.min(window.innerWidth,window.innerHeight)}var Te="data-cyberart-canvas",ie=class{constructor(t,n,r=1,a={}){this.width=t,this.height=n;let o=a.container,u=a.adoptFromDocument??!o,p=o?o.querySelector(`canvas[${Te}]`)??o.querySelector("canvas"):null;if(p)this.canvas=p,this.adopted=!0;else if(u){let m=document.getElementById("canvas")??document.querySelector("canvas");m?(this.canvas=m,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(Te)||this.canvas.setAttribute(Te,""),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/G}px`,this.canvas.style.height=`${n/G}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 Xe(e,t){let n=e/t,r,a;return n>1?(r=e,a=~~(e/n)):(a=t,r=~~(t*n)),{width:r,height:a,iWidth:1/r,iHeight:1/a,area:r*a,largeDim:Math.max(r,a),smallDim:Math.min(r,a),aspectRatio:n}}function Qe(e,t=window.innerWidth,n=window.innerHeight){let r=Ye(),a,o;return n<t?e>1?t>=r*e?(a=r*e,o=r):(a=t,o=a/e):(a=r*e,o=r):e>1?(a=r,o=r/e):n<r/e?(o=n,a=o*e):(a=r,o=r/e),[a,o]}var Pe=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={}}},Ze=Pe;var Me=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))}},et=Me;function ge(){return{now:()=>performance.now()}}function tt(e=0){let t=e;return{now:()=>t,set(n){t=n},advance(n){t+=n}}}var nt=(e,t,n,r)=>({now:e,startTime:t,elapsedSinceStart:e-t,deltaSinceLastUpdate:n===null?0:e-n,deltaSinceLastRender:r===null?0:e-r}),ye=class{constructor(t,n,r,a,o,u={}){this.startTime=0;this.lastUpdateAt=null;this.lastRenderAt=null;this.clockOffsetMs=0;this.pauseStartedAt=null;this.renderAnimation=this.renderAnimation.bind(this),this.dimensionContext=Xe(t,n),this.R=r,this.gameManager=u.gameManager,this.hostChannel=u.hostChannel,this.clock=u.clock??ge(),this.canvas=new ie(this.dimensionContext.width,this.dimensionContext.height,1,u.canvasMount),this.drawingContext=this.canvas.ctx,this.keyboardManager=new Ze(!1,u.captureKeyboard??!0),this.pointerManager=new et(this.canvas.canvas,{listen:u.listenToPointer!==!1}),this.animationCart=o;let p=u.customState;this.featureState=o.getDefaultFeatureState?.(this.R,this.dimensionContext,a,this.keyboardManager,p,this.pointerManager,this.gameManager,this.hostChannel),this.cartState=o.getDefaultState(this.R,this.dimensionContext,a,this.keyboardManager,p,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 a=this.resolveNow(r),o=nt(a,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=a}async renderAnimation(t,n,r=this.clock.now()){let a=this.resolveNow(r),o=nt(a,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=a}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 ie{constructor(t,n,r=1,a=!0,o={}){if(super(t,n,r,o),this.adopted)return;let u=o.container;if(u){this.canvas.parentNode!==u&&u.appendChild(this.canvas);return}if(a){let p=document.getElementById("canvas");p&&p!==this.canvas&&p.parentNode===document.body&&document.body.removeChild(p),document.body.appendChild(this.canvas)}}};function rt(e){let t=parseInt(e.substring(0,8),16),n=parseInt(e.substring(8,8),16),r=parseInt(e.substring(16,8),16),a=parseInt(e.substring(24,8),16);return{next:()=>{t|=0,n|=0,r|=0,a|=0;let u=(t+n|0)+a|0;return a=a+1|0,t=n^n>>>9,n=r+(r<<3)|0,r=r<<21|r>>>11,r=r+u|0,(u>>>0)/4294967296},getRegs:()=>({a:t,b:n,c:r,d:a}),setRegs:u=>{t=u.a,n=u.b,r=u.c,a=u.d}}}var ve=class{constructor(t){this.seed=t.hash,this.useA=!1,this.genA=rt(t.hash.substring(2,32)),this.genB=rt(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 st="bafybeicjwcq5lxxtfnyj4p2ugcr7ctyb5wl62cbcechj6tsabdq5whcs7u",it="https://ipfs.io/ipfs/";function $t(e){return e.endsWith("/")?e:`${e}/`}var ce=null;function Wt(e){return[...Array(e)].map(()=>Math.floor(Math.random()*16).toString(16)).join("")}function Gt(e){return e&&e.length>0?e:[{cid:st}]}function Bt(e){return e.startsWith("0x")?e:`0x${e}`}var ot=/^(0[xX])?[0-9a-fA-F]{64}$/;function Vt(e){let t="",n=2166136261,r=522970236;for(let a=0;t.length<64;a++){for(let o=0;o<e.length;o++)n^=e.charCodeAt(o)+a,n=Math.imul(n,16777619),r^=e.charCodeAt(o)+a*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 at(e){let t=typeof e=="number"?String(e):e;return ot.test(t)?`0x${(t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t).toLowerCase()}`:Vt(t)}function dt(e,t){if(typeof e=="number"||t==="deterministic")return at(e);let n=String(e);return ot.test(n)?at(n):n.startsWith("0x")||n.startsWith("0X")?n:`0x${n}`}function jt(e){if(!e&&typeof tokenData<"u"&&tokenData?.hash)return{hash:tokenData.hash,tokenId:String(tokenData.tokenId),externalAssetDependencies:Gt(tokenData.externalAssetDependencies),preferredIPFSGateway:$t(tokenData.preferredIPFSGateway||it),preferredArweaveGateway:tokenData.preferredArweaveGateway};let t=typeof window<"u"?new URLSearchParams(window.location.search):new URLSearchParams;return{hash:e?Bt(e):t.get("hash")||`0x${Wt(64)}`,tokenId:"18009999",externalAssetDependencies:[{cid:st}],preferredIPFSGateway:it}}function De(e){let t=e?.useCache!==!1;if(t&&ce&&!e?.hash)return ce;let n=jt(e?.hash);return t?ce=n:ce||(ce=n),n}function ut(e){return new Array(32).fill(null).map((t,n)=>parseInt(e.hash.slice(2+n*2,4+n*2),16))}async function He(){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 pt={id:"tone",async load(){await Promise.resolve().then(()=>(lt(),Jt))},async unlock(){await pt.load(),await(await He()).start()},async resumeIfSuspended(){let e=await He();e.context.state==="suspended"&&await e.context.resume()},async suspendIfRunning(){let t=(await He()).context.rawContext;"suspend"in t&&t.state==="running"&&await t.suspend()}},ht={tone:pt};function Fe(e){if(!e)return[];let t=Array.isArray(e)?e:[e],n=[];for(let r of t){if(!(r in ht)){console.warn(`Unknown audio library "${r}"`);continue}let a=r;n.includes(a)||n.push(a)}return n}function Le(e){return e.map(t=>ht[t])}var Ae="$cyberartTa",j=class extends Error{constructor(t){super(t),this.name="IncompatibleCartStateError"}},Oe={Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array};function Yt(e){for(let t of Object.keys(Oe))if(e instanceof Oe[t])return t}function gt(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function z(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function _e(e){return z(e)?typeof e[Ae]=="string"&&Array.isArray(e.d):!1}function Xt(e){return e==null?!1:typeof e=="function"?!0:!(typeof e!="object"||Array.isArray(e)||gt(e)||z(e))}var Qt=new Set(["audioContextStarted","midiSynths","keepRatioPrimed","audioInitStarted","musicSeekApplied"]);function mt(e){return e===null?"null":_e(e)?String(e[Ae]):Array.isArray(e)?"array":z(e)?"object":typeof e}function Zt(e,t){return e===t||e==="null"||t==="null"}function ft(e){return e.trim().toLowerCase().replace(/^0x/,"")}function yt(e,t,n,r){if(!(!n&&!r)&&ft(e)!==ft(t))throw new j(`Generative cart state is for seed "${t}", but the live token is "${e}"`)}function ae(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function bt(e,t){let n=e.dimensions;if(n&&ae(n.width)&&ae(n.height))return n;if(t&&ae(t.width)&&ae(t.height))return{width:t.width,height:t.height};if(z(e.state)){let r=e.state.containerWidth,a=e.state.containerHeight;if(ae(r)&&ae(a))return{width:r,height:a}}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(gt(e)){let n=Yt(e);return n?{[Ae]:n,d:Array.from(e)}:void 0}if(typeof e=="object"&&!t.has(e)){t.add(e);try{if(Array.isArray(e)){let a=[],o=0;for(let u of e){let p=se(u,t);p!==void 0&&(a.push(p),o++)}return e.length>0&&o===0?void 0:a}if(!z(e)||Xt(e))return;let n=Object.keys(e),r={};for(let a of n){if(Qt.has(a))continue;let o=se(e[a],t);o!==void 0&&(r[a]=o)}return n.length>0&&Object.keys(r).length===0?void 0:r}finally{t.delete(e)}}}}function pe(e){if(_e(e)){let t=Oe[e[Ae]];return t?new t(e.d.map(n=>Number(n))):e}if(Array.isArray(e))return e.map(t=>pe(t));if(z(e)){let t={};for(let n of Object.keys(e))t[n]=pe(e[n]);return t}return e}function Ne(e,t,n,r,a=!0){if(a&&n&&r&&n!==r)throw new j(`Cart state is for "${r}", but the live cart is "${n}"`);if(!z(t)){if(a)throw new j("Cart state snapshot is empty");return}let o=Object.keys(t);if(o.length===0){if(a)throw new j("Cart state snapshot is empty");return}let u=se(e);if(!z(u)||Object.keys(u).length===0){if(a)throw new j("Live cart has no serializable state");return}let p=o.filter(m=>m in u);if(p.length===0){if(a)throw new j("Cart state snapshot does not overlap the live cart shape");return}for(let m of p){let C=mt(u[m]),v=mt(t[m]);if(!Zt(C,v))throw new j(`Cart state field "${m}" has type ${v}, live cart expects ${C}`);if(C==="object"){let l=t[m],w=e[m];z(l)&&!_e(l)&&Ne(w,l,void 0,void 0,!1)}}}function vt(e,t){if(!z(e)||!z(t))return;let n=se(e);if(z(n))for(let r of Object.keys(t))r in n&&(e[r]=pe(t[r]))}function wt(e){let t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")throw new j("Cart state bundle is not an object");if(t.version!==1)throw new j(`Unsupported cart state version ${String(t.version)}`);if(typeof t.seed!="string"||typeof t.framesElapsed!="number")throw new j("Cart state bundle is missing seed or framesElapsed");return t}var Ue="cyberart.asset.ready",Ke="cyberart.asset.failed";function ee(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function At(e){return{type:e.status==="ready"?Ue:Ke,kind:"state",payload:e.detail===void 0?{id:e.id}:{id:e.id,detail:e.detail}}}function tn(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 nn(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)),a=Math.max(0,window.outerWidth-window.innerWidth),o=Math.max(0,window.outerHeight-window.innerHeight);try{window.resizeTo(n+a,r+o)}catch{return!1}return Math.abs(window.innerWidth-n)<=8&&Math.abs(window.innerHeight-r)<=8}var rn=[[0,0],[16,9],[9,16],[4,3],[3,4],[2,1],[1,2],[3,1],[1,3],[1,1]],We=rn[0],an=We[0]/We[1],$e=30,sn=120,on=3840/2160,dn=2160/3840,Ee=class{constructor(t=$e,n=!1,r=window.innerWidth,a=window.innerHeight,o=!0,u,p={}){this.framesElapsed=0;this.frameRate=$e;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=p.container,this.seed=p.seed,this.captureKeyboard=p.captureKeyboard??!0,this.customState=p.customState,this.hostChannel=p.hostChannel,this.fallbackAudio=Fe(p.audio),this.audioLibrariesInternal=this.fallbackAudio;let m=p.deterministic;this.deterministic=!!m;let C=m&&typeof m=="object"?m:{};if(this.deterministic){if(p.clock){let v=p.clock;if(typeof v.advance!="function")throw new Error("deterministic mode requires a virtual clock with advance()");this.virtualClock=v,this.clock=v}else this.virtualClock=tt(C.origin??0),this.clock=this.virtualClock;this.initialScriptedActions=ee(C.actions??[]),this.scriptedActions=ee(this.initialScriptedActions)}else this.clock=p.clock??ge();this.isBodyCanvas=this.container?!1:o,this.autoMode=n,this.aspectRatio=an,this.selectedAsp=We,this.isFullscreen=!!document.fullscreenElement,this.updateFrameRate(t),this.tempUnpause=!1,this.synchronous=re,this.containerWidth=r,this.containerHeight=a,this.gameManager=u,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?De({hash:this.seed,useCache:!1}):De(),this.rawParams=ut(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,a]=Qe(n,this.containerWidth,this.containerHeight);r*=G,a*=G,this.width=~~r,this.height=~~a,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),a=new ve(this.tokenData),o=new ye(n,r,a,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=ee(this.initialScriptedActions),this.appliedActions=[],this.consumedActionIndexes=new Set,this.outboundUnsubscribe?.(),this.outboundUnsubscribe=void 0,this.deterministic&&this.hostChannel&&(this.outboundUnsubscribe=this.hostChannel.onEvent(u=>{this.outboundEvents.push(u)})),this.R=a,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,a=r?.frameRate??$e,o=n.cartState?.visualMode??n.featureState?.visualMode,u=o&&r?.frameRateByVisualMode?r.frameRateByVisualMode[o]:void 0;this.updateFrameRate(typeof u=="number"&&u>0?u:a)}get audioLibraries(){return this.audioLibrariesInternal}get needsAudio(){return this.audioLibrariesInternal.length>0}resolveAudioLibraries(t){this.audioLibrariesInternal=Fe(t.metadata?.audio)}async unlockAudio(){if(this.audioLibrariesInternal.length===0)return;let t=Le(this.audioLibrariesInternal);if(re){for(let n of t)await n.load();return}for(let n of t)await n.unlock()}async resumeAudioLibraries(){if(!(this.paused||re))for(let t of Le(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(ee(t))}async getReplayMetadata(){let t=await this.exportState();return{seed:this.tokenData.hash,clock:this.getClock(),rng:this.getRandomState(),actions:ee(this.scriptedActions),applied:ee(this.appliedActions),events:ee(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 a=this.framesElapsed;if(this.applyScheduledActions(a),await this.processFrame(this.clock.now(),{ignorePause:!0,scheduleNext:!1}),this.framesElapsed===a||(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,a)=>{r.atFrame===t&&(this.consumedActionIndexes.has(a)||(this.consumedActionIndexes.add(a),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(At(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:G},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(),a=wt(t),o=this._paused,u=this.loopRunning;this.paused=!0,await this.waitUntilUpdateIdle(),Ne(r.cartState,a.state,this.animationCart?.metadata?.id,a.cartId),yt(this.tokenData.hash,a.seed,this.animationCart?.metadata?.generative,a.generative),clearTimeout(this.reinitTimeout),this.reinitPending=!1,this.importing=!0;let p=bt(a,n?.framebuffer??this.lastExportedFramebuffer);if(p){this.pinOutputSize(p);let v=p.cssWidth??p.width/G,l=p.cssHeight??p.height/G;nn(v,l),this.syncContainerFromDom(),this.pinViewportAtImport={w:this.containerWidth,h:this.containerHeight}}let m=this.customState,C=!1;try{if(this.customState=pe(a.state),this.unloadCart(),!this.prepareCart(this.animationCart))throw new Error("Failed to prepare cart while loading state");this.animation.cartState!==this.customState&&vt(this.animation.cartState,a.state),this.framesElapsed=a.framesElapsed;let v=this.animation,l=v.cartState,w=typeof a.elapsedSinceStart=="number"?a.elapsedSinceStart:tn(l);v.restoreClock(w,typeof l?.startTime=="number"?l.startTime:void 0),o&&v.setPaused(!0);let E=n?.framebuffer??this.lastExportedFramebuffer;E&&v.restoreFramebuffer(E)?l.keepRatioPrimed=!0:await v.renderAnimation(this.framesElapsed,this.rawParams),this.fitPinnedCanvas(),C=!0}catch(v){throw this.clearPinnedOutput(),this.customState=m,this.paused=o,this.animationCart&&(this.syncContainerFromDom(),this.init(),this.reloadCart()),v}finally{this.importing=!1,C&&(this.customState=m,this.paused=o,u&&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&&!re&&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/G,h:t.cssHeight??t.height/G}}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,a=this.containerHeight||window.innerHeight,o=t.width/G,u=t.height/G;if(o<1||u<1||r<1||a<1)return;let p=Math.min(r/o,a/u),m=o*p,C=u*p;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=`${m}px`,n.style.height=`${C}px`,n.style.imageRendering=Math.abs(p-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,a=n.scheduleNext!==!1;if(!this.loopRunning&&!r)return;let o=!1,u,p="update";try{if(r||!this.paused||this.tempUnpause){if(!re&&!r&&this.tuneFramerate(t),!this.animation)return;if(p="update",this.updateInProgress=!0,await this.animation.updateAnimationState(this.framesElapsed,this.rawParams,t),this.updateInProgress=!1,p="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 v=localStorage.getItem("goodones"),l=JSON.stringify(v?[...JSON.parse(v),this.tokenData.hash]:[this.tokenData.hash]);localStorage.setItem("goodones",l),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)}p="draw",this.drawIt()}catch(m){o=!0,u=m,this.handleFrameError(m,p)}finally{this.updateInProgress=!1}o?(this.consecutiveErrorCount++,this.consecutiveErrorCount>=sn&&(this.loopRunning=!1,this.onError?.(u,{phase:p,consecutive:this.consecutiveErrorCount,stopped:!0}))):this.consecutiveErrorCount=0,!(!this.loopRunning||!a)&&(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,a=this.containerHeight||window.innerHeight,o=r/a;this.aspectRatio=Math.min(on,Math.max(dn,o))}else this.aspectRatio=t[0]/t[1]}};var un="HostChannel has been destroyed",Ce=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(un)}};var cn=["image","audio","font","spritesheet"],ln=["timeout","cors","not-found","invalid","aborted","resolver"],he="cyberart:fallback/silent",Et="Asset preloader has been destroyed",pn=4,hn=new Set(cn),mn=new Set(ln),fn={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 gn(e){return typeof e=="string"&&hn.has(e)}function yn(e){return typeof e=="string"&&mn.has(e)}function Ge(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.id=="string"&&typeof t.ref=="string"&&yn(t.code)&&typeof t.message=="string"}function N(e){return{id:e.id,ref:e.ref,code:e.code,message:e.message&&e.message.length>0?e.message:fn[e.code]}}function oe(e,t){return{type:e==="ready"?Ue:Ke,kind:"state",payload:t}}function bn(e){return e instanceof Error&&e.name==="AbortError"||typeof DOMException<"u"&&e instanceof DOMException&&e.name==="AbortError"}function Be(e){return e?{...e}:void 0}function Q(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=Be(e.provenance)),e.cors!==void 0&&(t.cors=e.cors),e.usedFallback&&(t.usedFallback=!0),e.managed&&(t.managed=!0),t}function me(e){return{id:e.id,ref:e.ref,code:e.code,message:e.message}}function vn(e){if(e.state==="ready"){let t={state:"ready",resource:Q(e.resource)};return e.failure&&(t.failure=me(e.failure)),t}return e.state==="failed"?{state:"failed",failure:me(e.failure)}:{state:e.state}}function wn(e){if(!e||typeof e!="object")return N({id:"",ref:"",code:"invalid",message:"declaration is required"});if(typeof e.id!="string"||e.id.length===0)return N({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 N({id:e.id,ref:"",code:"invalid",message:"ref is required"});if(!gn(e.type))return N({id:e.id,ref:e.ref,code:"invalid",message:`unsupported type ${String(e.type)}`});if(e.integrity!==void 0&&typeof e.integrity!="string")return N({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 N({id:e.id,ref:e.ref,code:"invalid",message:"timeoutMs must be a non-negative finite number"})}function Ct(e){return{id:e.id,ref:he,type:e.type,url:he,usedFallback:!0,cors:"omit"}}function St(e,t){return Ge(t)?{id:e.id,ref:e.ref,code:t.code,message:t.message}:bn(t)?N({id:e.id,ref:e.ref,code:"aborted"}):N({id:e.id,ref:e.ref,code:"resolver",message:t instanceof Error?t.message:String(t)})}function kt(e,t){if(!t||typeof t.url!="string"||t.url.length===0)throw N({id:e.id,ref:e.ref,code:"invalid",message:"resolver returned no url"});if(t.integrity&&e.integrity&&t.integrity!==e.integrity)throw N({id:e.id,ref:e.ref,code:"invalid",message:"integrity mismatch"});let n=Q(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=Be(e.provenance)),n}function Rt(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,a=[],o=new Map,u=new Map,p=new Map,m=new Map,C=new Map,v=new Set,l=!1;function w(i){return i.code==="aborted"||i.code==="timeout"}function E(i,g,y){let x=St(i,y);return x.code==="timeout"?x:g.aborted?N({id:i.id,ref:i.ref,code:"aborted"}):x}function b(i,g){let y=C.get(i);y||(y=new Set,C.set(i,y)),y.add(g)}function M(i){if(i?.state==="ready")return`${i.resource.type}\0${i.resource.ref}`}function h(i,g){for(let[y,x]of C)if(y!==g&&x.has(i))return!0;for(let[y,x]of r)if(y!==g&&M(x)===i)return!0;return!1}function K(i,g){let y=new Set(C.get(i)),x=M(g);x&&y.add(x),C.delete(i);for(let U of y)h(U,i)||p.delete(U)}function $(){let i=0,g=0,y=0,x=0,U={};for(let[I,P]of r)U[I]=vn(P),P.state==="pending"||P.state==="loading"?i+=1:P.state==="failed"?y+=1:(g+=1,(P.resource.usedFallback||P.failure)&&(x+=1));return{total:r.size,pending:i,ready:g,failed:y,fallbacks:x,items:U,failures:a.map(me)}}function J(){if(v.size===0)return;let i=$();for(let g of v)g(i)}function F(i){a.push(me(i))}function d(i){l||!t||!e.dispatch||e.dispatch(i)}function T(i){if(i?.managed&&i.url.startsWith("blob:")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(i.url)}catch{}}function A(i,g){if(l)return;let y=r.get(i);y?.state==="ready"&&T(y.resource),r.set(i,g),J()}function D(i){if(i.fallback!==void 0)return i.fallback==="silent"?{id:`${i.id}::fallback`,ref:he,type:i.type}:typeof i.fallback=="string"?{id:`${i.id}::fallback`,ref:i.fallback,type:i.type}:{...i.fallback,id:typeof i.fallback.id=="string"&&i.fallback.id.length>0?i.fallback.id:`${i.id}::fallback`}}function H(i,g,y){let x=`${i.type}\0${i.ref}`,U=p.get(x);if(U)return g.aborted?Promise.reject(N({id:i.id,ref:i.ref,code:"aborted"})):(b(y,x),Promise.resolve(Q(U.resource)));if(g.aborted)return Promise.reject(N({id:i.id,ref:i.ref,code:"aborted"}));let I=m.get(x);if(!I){let R=new AbortController,L={id:i.id,ref:i.ref,type:i.type};i.integrity!==void 0&&(L.integrity=i.integrity),i.provenance&&(L.provenance=Be(i.provenance)),I={promise:Promise.resolve().then(()=>e.resolver.resolve(L,R.signal)).then(O=>{let X=kt(i,O);if(R.signal.aborted)throw N({id:i.id,ref:i.ref,code:"aborted"});return p.set(x,{resource:Q(X)}),X}).catch(O=>{throw St(i,O)}).finally(()=>{m.delete(x)}),controller:R,waiters:0},m.set(x,I)}let P=I;return P.waiters+=1,new Promise((R,L)=>{let Y=!1,O=(Z,xe)=>{Y||(Y=!0,g.removeEventListener("abort",X),P.waiters-=1,xe&&P.waiters<=0&&P.controller.abort(),Z())},X=()=>{O(()=>L(N({id:i.id,ref:i.ref,code:"aborted"})),!0)};if(g.aborted){X();return}g.addEventListener("abort",X,{once:!0}),P.promise.then(Z=>{if(!Y){if(g.aborted){X();return}b(y,x),O(()=>R(Q(Z)),!1)}},Z=>{if(!Y){if(g.aborted){X();return}O(()=>L(Z),!1)}})})}function W(i,g,y){if(g.aborted)return Promise.reject(N({id:i.id,ref:i.ref,code:"aborted"}));if(i.ref===he)return Promise.resolve(Ct(i));let x=new AbortController,U=()=>x.abort();g.addEventListener("abort",U,{once:!0});let I=i.timeoutMs??e.timeoutMs,P,R=!1;return n&&I!==void 0&&I>0&&Number.isFinite(I)&&(P=setTimeout(()=>{R=!0,x.abort()},I)),H(i,x.signal,y).then(L=>{let Y=kt(i,L);return Y.id=i.id,Y}).catch(L=>{throw R?N({id:i.id,ref:i.ref,code:"timeout"}):L}).finally(()=>{P!==void 0&&clearTimeout(P),g.removeEventListener("abort",U)})}async function B(i,g,y,x){try{return{resource:await W(i,g,x)}}catch(U){let I=E(i,g,U);if(w(I)||g.aborted||y>=pn)throw I;let P=D(i);if(!P)throw I;if(g.aborted)throw N({id:i.id,ref:i.ref,code:"aborted"});if(i.fallback==="silent"||P.ref===he)return{resource:Ct(i),failure:I};try{let R=await B(P,g,y+1,x);return{resource:{...Q(R.resource),id:i.id,usedFallback:!0},failure:I}}catch(R){let L=Ge(R)&&!w(R)&&!g.aborted?R:E(i,g,R);throw!w(L)&&!g.aborted&&F(I),L}}}async function te(i,g){if(l)throw new Error(Et);let y=r.get(i.id);if(y?.state==="ready"||y?.state==="failed")return;let x=o.get(i.id);if(x){await x;return}let U=(async()=>{let I=wn(i);if(I){A(i.id,{state:"failed",failure:I}),F(I),d(oe("failed",{id:i.id,ref:i.ref,failure:I}));return}A(i.id,{state:"loading"});let P=u.get(i.id)??new AbortController;u.has(i.id)||u.set(i.id,P);try{let R=await B(i,P.signal,g,i.id);if(l)return;if(P.signal.aborted){let L=N({id:i.id,ref:i.ref,code:"aborted"});A(i.id,{state:"failed",failure:L}),F(L),d(oe("failed",{id:i.id,ref:i.ref,failure:L}));return}if(R.resource.id=i.id,R.failure){A(i.id,{state:"ready",resource:R.resource,failure:R.failure}),F(R.failure),d(oe("failed",{id:i.id,ref:i.ref,failure:R.failure,resource:Q(R.resource)})),d(oe("ready",{id:i.id,ref:R.resource.ref,resource:Q(R.resource),failure:R.failure}));return}A(i.id,{state:"ready",resource:R.resource}),d(oe("ready",{id:i.id,ref:i.ref,resource:Q(R.resource)}))}catch(R){if(l)return;let L=Ge(R)&&!w(R)&&!P.signal.aborted?{...me(R),id:i.id}:E(i,P.signal,R);A(i.id,{state:"failed",failure:L}),F(L),d(oe("failed",{id:i.id,ref:i.ref,failure:L}))}finally{u.get(i.id)===P&&u.delete(i.id)}})();o.set(i.id,U);try{await U}finally{o.delete(i.id)}}return{async preload(i){if(l)throw new Error(Et);let g=Array.isArray(i)?i:[];for(let y of g)y&&typeof y.id=="string"&&y.id.length>0&&(r.has(y.id)||r.set(y.id,{state:"pending"}),u.has(y.id)||u.set(y.id,new AbortController));return J(),await Promise.all(g.map(y=>te(y,0))),$()},get(i){let g=r.get(i);if(g?.state==="ready")return Q(g.resource)},getProgress(){return $()},onProgress(i){return v.add(i),()=>{v.delete(i)}},abort(i){if(!l){if(i!==void 0){u.get(i)?.abort();return}for(let g of u.values())g.abort()}},forget(i){if(l)return;if(i===void 0){for(let y of r.values())y.state==="ready"&&T(y.resource);r.clear(),a.length=0,p.clear(),C.clear(),J();return}let g=r.get(i);g?.state==="ready"&&T(g.resource),K(i,g),r.delete(i);for(let y=a.length-1;y>=0;y--)a[y].id===i&&a.splice(y,1);J()},dispose(){if(!l){l=!0;for(let i of u.values())i.abort();u.clear();for(let i of r.values())i.state==="ready"&&T(i.resource);r.clear(),a.length=0,o.clear();for(let i of m.values())i.controller.abort();p.clear(),m.clear(),C.clear(),v.clear()}}}}function Se(e){Je();let{container:t,seed:n,captureKeyboard:r=!1,audio:a,deterministic:o,assets:u}=e,p=n===void 0?void 0:dt(n,o?"deterministic":"live"),m=new Ce;if(u&&typeof u.resolver?.resolve!="function")throw new Error("createRuntime: assets.resolver is required");let C=u?Rt({resolver:u.resolver,timeoutMs:u.timeoutMs,emitEvents:u.emitEvents??!o,wallClockTimeout:!o,dispatch:F=>m.dispatch(F)}):void 0,v=!1,l=null,w,E=!1,b=t.clientWidth||window.innerWidth,M=t.clientHeight||window.innerHeight,h=new Ee(30,!1,b,M,!1,void 0,{container:t,seed:p,captureKeyboard:r,hostChannel:m,audio:a,deterministic:o}),K=()=>{let F=t.clientWidth||window.innerWidth,d=t.clientHeight||window.innerHeight;return F===h.containerWidth&&d===h.containerHeight?!1:(h.containerWidth=F,h.containerHeight=d,!0)},$=null;return!h.isDeterministic&&typeof ResizeObserver<"u"&&($=new ResizeObserver(()=>{if(v||!l)return;K()&&E&&h.reinit()}),$.observe(t)),h.onError=(F,d)=>{w?.(F,d)},{get tokenData(){return h.tokenData},get hostChannel(){return m},get assets(){return C},get onError(){return w},set onError(F){w=F},mount(F,d={}){if(v)throw new Error("createRuntime: cannot mount on a destroyed runtime");l?.destroy(),E=!1,h.customState=d.initialState,h.setGameManager(d.gameManager);let T=d.onEvent?m.onEvent(d.onEvent):()=>{};if(!h.prepareCart(F))throw T(),new Error("createRuntime: failed to prepare cart");let A=!1,D={async start(){if(!A){if(K()&&h.isPrepared&&(h.init(),h.unloadCart(),!h.prepareCart(F)))throw new Error("createRuntime: failed to prepare cart");h.needsAudio&&(await h.unlockAudio(),A)||(E=!0,h.beginPlayback())}},pause(){A||(h.paused=!0)},resume(){A||(h.paused=!1)},dispatch(H){A||m.dispatch(H)},snapshot(){if(A)return{seed:"",pngDataUrl:""};let H=h.canvas;return{seed:h.tokenData.hash,metadata:F.metadata,pngDataUrl:H?H.toDataURL("image/png"):""}},destroy(){A||(A=!0,E=!1,T(),m.clearInbound(),h.unloadCart(),l===D&&(l=null))},reload(){if(!A){if(!E){if(h.isPrepared&&(h.unloadCart(),!h.prepareCart(F)))throw new Error("createRuntime: failed to prepare cart");return}h.reloadCart()}},reinit(H){if(!A){if(!E){K();return}h.reinit(H)}},getCartState(){return h.animation?.cartState},exportState(){return A?Promise.reject(new Error("Cart handle has been destroyed")):h.exportState()},exportStateJSON(){return A?Promise.reject(new Error("Cart handle has been destroyed")):h.exportStateJSON()},async importState(H,W){if(A)throw new Error("Cart handle has been destroyed");await h.importState(H,W)},peekExportedFramebuffer(){return A?null:h.peekExportedFramebuffer()},peekSeed(){if(!A)return h.peekSeed()},isGenerative(){return A?!1:h.isGenerative()},async step(H=1){if(A)throw new Error("Cart handle has been destroyed");await h.step(H)},async advance(H){if(A)throw new Error("Cart handle has been destroyed");await h.advance(H)},schedule(H){A||h.schedule(H)},getClock(){if(A)throw new Error("Cart handle has been destroyed");return h.getClock()},getRandomState(){if(A)throw new Error("Cart handle has been destroyed");return h.getRandomState()},getReplayMetadata(){return A?Promise.reject(new Error("Cart handle has been destroyed")):h.getReplayMetadata()},get canvas(){return h.canvas},get paused(){return h.paused},set paused(H){A||(h.paused=H)},get tokenData(){return h.tokenData},get isPrepared(){return h.isPrepared},get isLoopRunning(){return h.isLoopRunning},get needsAudio(){return h.needsAudio},get audioLibraries(){return h.audioLibraries}};return l=D,D},async unlockAudio(){await h.unlockAudio()},destroy(){v||(v=!0,l?.destroy(),l=null,$?.disconnect(),$=null,C?.dispose(),m.close(),h.destroy())}}}var xt="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",Tt=320,Pt=180,An="Headless harness has been destroyed",Mt=!1;function ke(){if(typeof globalThis.ImageData>"u"){class t{constructor(r,a){this.colorSpace="srgb";this.width=r,this.height=a,this.data=new Uint8ClampedArray(r*a*4)}}globalThis.ImageData=t}let e=HTMLCanvasElement.prototype;e.getContext=function(){return{globalAlpha:1,imageSmoothingEnabled:!1,fillStyle:"",save(){},restore(){},fillRect(){},putImageData(){},createImageData(r,a){return{data:new Uint8ClampedArray(r*a*4),width:r,height:a}}}},e.toDataURL=()=>xt,Mt=!0}function En(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 Cn(e){let t=e.indexOf(","),n=t>=0?e.slice(t+1):e,r=globalThis.atob(n),a=new Uint8Array(r.length);for(let o=0;o<r.length;o++)a[o]=r.charCodeAt(o);return a}function Sn(){return typeof process<"u"&&!!process.versions?.node}async function kn(e,t){if(!Sn())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 a=r instanceof Error?r.message:String(r);throw new Error(`captureFrame(path) could not load node:fs/promises (${a}). Omit the path, or run under Node.`)}try{await n(e,Cn(t))}catch(r){let a=r instanceof Error?r.message:String(r);throw new Error(`captureFrame could not write ${e}: ${a}`)}}function Rn(e){Mt||ke();let t=e.width??Tt,n=e.height??Pt,r=En(t,n),a=[],o=[],u=!1,p=e.onEvent,m=e.onError,C=Se({container:r,seed:e.seed,deterministic:{origin:e.origin,actions:e.actions??[]}});C.onError=(b,M)=>{o.push({error:b,info:M}),m?.(b,M)},Object.defineProperty(C,"onError",{configurable:!0,enumerable:!0,get(){return m},set(b){m=b}});let v=b=>{a.push(b),p?.(b)},l=C.mount(e.cart,{initialState:e.initialState,gameManager:e.gameManager,onEvent:v}),w=()=>{if(u)throw new Error(An)};return{runtime:C,container:r,get events(){return a.slice()},get errors(){return o.slice()},get cart(){return l},async step(b=1){w(),await l.step(b)},async advance(b){w(),await l.advance(b)},schedule(b){w(),l.schedule(b)},dispatch(b){w(),l.dispatch(b)},start(){return w(),l.start()},pause(){w(),l.pause()},resume(){w(),l.resume()},get paused(){return l.paused},key(b){w(),l.schedule({type:"key",atFrame:l.getClock().framesElapsed,key:b})},click(b,M){w(),l.schedule({type:"pointer",atFrame:l.getClock().framesElapsed,pointer:{kind:"down",x:b,y:M}})},async inspect(){w();let b=await l.getReplayMetadata();return{state:b.state,events:a.slice(),errors:o.slice(),replay:b,clock:l.getClock()}},async captureFrame(b){w();let M=l.snapshot();return b&&await kn(b,M.pngDataUrl),M},remount(b={}){return w(),a.length=0,o.length=0,"onEvent"in b&&(p=b.onEvent),l=C.mount(e.cart,{initialState:b.initialState??e.initialState,gameManager:b.gameManager??e.gameManager,onEvent:v}),l},destroy(){if(!u){u=!0;try{l.destroy()}finally{try{C.destroy()}finally{r.remove()}}}}}}var Dt="cyberart.state.save",It="cyberart.state.load";var Re=1,fe="cyberart.diagnostic.rejected",Ve=8,xn=new Set(["intent","state","diagnostic"]),Tn=new Set([Dt,It]);function Ht(e){return typeof e=="string"&&xn.has(e)}function Pn(e){if(e.kind!==void 0)return Ht(e.kind)?e.kind:void 0;if(!(typeof e.type!="string"||e.type.length===0)){if(Tn.has(e.type))return"intent";for(let t of e.type.split("."))if(Ht(t))return t}}function Mn(e,t){let n=e.split("."),r=t.split(".");if(n.length!==r.length)return!1;for(let a=0;a<n.length;a++)if(n[a]!=="*"&&n[a]!==r[a])return!1;return!0}function de(e,t){for(let n of e)if(Mn(n,t))return!0;return!1}function Dn(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 je(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!==Re)return{ok:!1,reason:"malformed",detail:`unsupported schemaVersion ${String(e.schemaVersion)}`};let n=Pn(e);if(!n)return{ok:!1,reason:"malformed",detail:`cannot infer kind from type "${e.type}"`};let r=Dn(e.payload);if(!r.ok)return{ok:!1,reason:"malformed",detail:"payload is not JSON-serializable"};let a=t.createId(),o=typeof e.correlationId=="string"&&e.correlationId.length>0?e.correlationId:a,u=typeof e.causationId=="string"&&e.causationId.length>0?e.causationId:t.causationId,p=typeof e.target=="string"&&e.target.length>0?e.target:void 0,m=t.maxHops??Ve,C=t.parentHops===void 0?m:Math.max(0,t.parentHops-1),v=typeof e.idempotencyKey=="string"&&e.idempotencyKey.length>0?e.idempotencyKey:void 0,l={schemaVersion:Re,type:e.type,kind:n,source:t.source,id:a,correlationId:o,seq:t.seq,hops:C};return p&&(l.target=p),u&&(l.causationId=u),v&&(l.idempotencyKey=v),r.value!==void 0&&(l.payload=r.value),{ok:!0,envelope:l}}var In=new Set(["rate-limited","storm-detected","hop-limit","loop-detected","not-subscribed"]),Hn=8,Fn=8,Ln=16,On=256,_n=["*.intent.*"];function Ft(e={}){let t=e.hostSource??"host",n="router",r=e.maxPerTurn??Hn,a=e.maxCausationDepth??Fn,o=e.maxHops??Ve,u=e.maxCorrelationPerTurn??Ln,p=e.maxIndex??On,m=e.maxPerWindow,C=e.windowMs??1e3,v=e.now??Date.now,l=0,w=e.createId??(()=>`evt-${++l}`),E=new Map,b=[],M=new Map,h=new Map,K=new Map,$=0,J=0,F=[],d=!1;function T(s,c,S){for(s.set(c,S);s.size>p;){let k=s.keys().next().value;if(k===void 0)break;s.delete(k)}}function A(s){T(M,s.id,{type:s.type,source:s.source,causationId:s.causationId,hops:s.hops,correlationId:s.correlationId,idempotencyKey:s.idempotencyKey})}function D(s,c){c&&(s.correlationId||(s.correlationId=c.correlationId),s.causationId||(s.causationId=c.id),!s.idempotencyKey&&c.idempotencyKey&&(s.idempotencyKey=`${c.idempotencyKey}::${s.type}`))}function H(s,c){if(s){let S=M.get(s);return S?S.hops:o}return c}function W(s,c){return`${s}\0${c}`}function B(s,c){s.idempotencyKey&&T(K,W(s.source,s.idempotencyKey),c)}function te(s,c){if(c)return K.get(W(s,c))}function i(s){return te(s.source,s.idempotencyKey)}function g(s){return s.seq+=1,s.seq}function y(s,c){if(!(typeof c.causationId=="string"&&c.causationId.length>0))return s.lastDelivered}function x(s){let c=new Set,S=new Set([`${s.type}\0${s.source}`]),k=s.causationId,f=0;for(;k;){if(f+=1,f>a||c.has(k))return!0;c.add(k);let _=M.get(k);if(!_)break;let V=`${_.type}\0${_.source}`;if(S.has(V))return!0;S.add(V),k=_.causationId}return!1}function U(s){let c=(h.get(s)??0)+1;return h.set(s,c),c}function I(s,c){m!==void 0&&(s.emitTimestamps=s.emitTimestamps.filter(S=>c-S<C))}function P(s,c){return(c.kind==="state"||c.kind==="diagnostic")&&!s.authoritative?!1:de(s.emit,c.type)}function R(s){for(let c of b)if(de(c.patterns,s.type))try{c.listener(s)}catch{}}function L(s){if(s.target){let c=E.get(s.target);if(!c||!de(c.subscribe,s.type))return;c.channel.dispatch(s),c.lastDelivered={id:s.id,hops:s.hops,correlationId:s.correlationId,idempotencyKey:s.idempotencyKey};return}for(let c of E.values())de(c.subscribe,s.type)&&(c.channel.dispatch(s),c.lastDelivered={id:s.id,hops:s.hops,correlationId:s.correlationId,idempotencyKey:s.idempotencyKey})}function Y(s,c,S,k,f,_,V){let q={reason:k,eventType:c,source:S};f&&(q.detail=f),J+=1;let ue=w(),ne={schemaVersion:Re,type:fe,kind:"diagnostic",source:n,id:ue,correlationId:_??ue,seq:J,hops:0,payload:q};V&&(ne.causationId=V),A(ne);let qe=E.get(s);qe&&qe.channel.dispatch(ne),R(ne)}function O(s,c,S,k,f){Y(s,f?.type??(typeof c.type=="string"?c.type:""),f?.source??s,S,k,f?.correlationId,f?.id),f?.idempotencyKey&&!In.has(S)&&B(f,{status:"rejected"})}function X(s){A(s),B(s,{status:"accepted",envelope:s}),U(s.correlationId),R(s),L(s)}function Z(s,c,S,k){if(!S.ok){O(s,c,"malformed",S.detail);return}let f=S.envelope,_=i(f);if(_)return _.status==="accepted"?_.envelope:void 0;if(f.hops<1){O(s,c,"hop-limit","no hops remaining",f);return}if(f.target&&f.target!==t){let V=E.get(f.target);if(!V){O(s,c,"unknown-target",`unknown target "${f.target}"`,f);return}if(!de(V.subscribe,f.type)){O(s,c,"not-subscribed",`target "${f.target}" does not subscribe to ${f.type}`,f);return}}if(k){if(!P(k,f)){O(s,c,"unauthorized","source may not emit this event",f);return}if(k.emitsThisTurn+=1,k.emitsThisTurn>r){O(s,c,"rate-limited","maxPerTurn exceeded",f);return}if(m!==void 0){let q=v();if(I(k,q),k.emitTimestamps.push(q),k.emitTimestamps.length>m){O(s,c,"rate-limited","maxPerWindow exceeded",f);return}}if(x(f)){O(s,c,"loop-detected","causation chain cycle or depth exceeded",f);return}if((h.get(f.correlationId)??0)+1>u){O(s,c,"storm-detected","correlationId storm",f);return}if(e.validate){let q;try{q=e.validate(f)}catch(ue){let ne=ue instanceof Error?ue.message:"validate threw";O(s,c,"host-rejected",ne,f);return}if(q!==!0){O(s,c,"host-rejected",q.detail,f);return}}}else{if(x(f)){O(s,c,"loop-detected","causation chain cycle or depth exceeded",f);return}if((h.get(f.correlationId)??0)+1>u){O(s,c,"storm-detected","correlationId storm",f);return}}return X(f),f}function xe(s,c){let S=E.get(s);if(!S)return;let k={...c},f=y(S,k);if(D(k,f),te(S.id,k.idempotencyKey))return;let V=g(S),q=je(k,{source:S.id,createId:w,seq:V,causationId:f?.id,maxHops:o,parentHops:H(k.causationId??f?.id,f?.hops)});Z(s,k,q,S)}function Nt(s,c){let S=c?.cause,k={...s};D(k,S);let f=te(t,k.idempotencyKey);if(f)return f.status==="accepted"?f.envelope:void 0;$+=1;let _=je(k,{source:t,createId:w,seq:$,causationId:k.causationId,maxHops:o,parentHops:H(k.causationId,S?.hops)});return Z(t,k,_,void 0)}function Ut(){if(!d){d=!0;try{for(;F.length>0;){let s=F.shift();s&&(s.kind==="cart"?xe(s.participantId,s.event):s.result=Nt(s.event,s.extras))}}finally{d=!1}}}function ze(s){F.push(s),Ut()}return{attach(s,c,S={}){if(s===t||s===n)throw new Error(`createEventRouter: "${s}" is a reserved participant id`);for(let _ of E.values())if(_.channel===c&&_.id!==s)throw new Error(`createEventRouter: channel already attached as "${_.id}"`);E.get(s)?.unsubscribe();let f={id:s,channel:c,emit:S.emit??_n,subscribe:S.subscribe??[],authoritative:S.authoritative===!0,seq:0,emitsThisTurn:0,emitTimestamps:[],unsubscribe:()=>{}};f.unsubscribe=c.onEvent(_=>{ze({kind:"cart",participantId:s,event:_})}),E.set(s,f)},detach(s){let c=E.get(s);c&&(c.unsubscribe(),E.delete(s))},publish(s,c){let S={kind:"publish",event:s,extras:c};return ze(S),S.result},subscribe(s,c){let S={patterns:s,listener:c};return b.push(S),()=>{let k=b.indexOf(S);k>=0&&b.splice(k,1)}},turn(){h.clear();for(let s of E.values())s.emitsThisTurn=0,s.lastDelivered=void 0,m!==void 0&&I(s,v())}}}var Nn=320,Un=180,Kn="Runtime group has been destroyed";function $n(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 Wn(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 Ot(e){let t=e.capability,n={},r=e.emit??t?.emit,a=e.subscribe??t?.subscribe,o=e.authoritative??t?.authoritative;return r&&(n.emit=r),a&&(n.subscribe=a),o!==void 0&&(n.authoritative=o),n}function Lt(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function Gn(e){let t=new Set([fe,"*.*","*.*.*","*.*.*.*","*.*.*.*.*"]);for(let n of e){let r=Ot(n);for(let a of r.emit??[])t.add(a);for(let a of r.subscribe??[])t.add(a)}return[...t]}function _t(e){if(!e.participants.length)throw new Error("createRuntimeGroup: at least one participant is required");let t=new Set;for(let d of e.participants){if(!d.id)throw new Error("createRuntimeGroup: participant id is required");if(t.has(d.id))throw new Error(`createRuntimeGroup: duplicate participant id "${d.id}"`);t.add(d.id)}let n=e.origin??0,r=e.width??Nn,a=e.height??Un,o=[...e.participants].sort((d,T)=>d.id.localeCompare(T.id)),u=[],p=new Map,m=0,C=e.createId??e.router?.createId??(()=>`evt-${++m}`),v=e.now??e.router?.now??(()=>{let d=u[0];if(!d)return n;try{return d.cart.getClock().now}catch{return n}}),l=Ft({...e.router,createId:C,now:v,validate:e.validate??e.router?.validate}),w=[],E=!1,b=!1,M=()=>{},h=d=>T=>{d.events.push(T),d.userOnEvent?.(T)},K=()=>{if(b)throw new Error(Kn)},$=()=>{M();for(let d of u){try{l.detach(d.id)}catch{}try{d.runtime.destroy()}catch{}d.ownsContainer&&d.container.remove()}u.length=0,p.clear()};try{for(let d of o){let T=d.width??r,A=d.height??a,D=!d.container,H=d.container??Wn(T,A),W=Se({container:H,seed:d.seed??$n(d.id),deterministic:{origin:n}}),B={id:d.id,kind:d.kind??"render",cartDef:d.cart,initialState:d.initialState,gameManager:d.gameManager,userOnEvent:d.onEvent,runtime:W,container:H,ownsContainer:D,cart:void 0,events:[],errors:[]};W.onError=(te,i)=>{B.errors.push({error:te,info:i})},l.attach(d.id,W.hostChannel,Ot(d)),B.cart=W.mount(d.cart,{initialState:d.initialState,gameManager:d.gameManager,onEvent:h(B)}),u.push(B),p.set(B.id,B)}M=l.subscribe(Gn(o),d=>{w.push(Lt(d))})}catch(d){throw $(),d}let J=d=>({id:d.id,kind:d.kind,runtime:d.runtime,container:d.container,get events(){return d.events.slice()},get errors(){return d.errors.slice()},get cart(){return d.cart}});return{router:l,origin:n,get paused(){return E},participant(d){K();let T=p.get(d);if(!T)throw new Error(`createRuntimeGroup: unknown participant "${d}"`);return J(T)},async step(d=1){if(K(),E)return;let T=Math.max(0,Math.floor(d));for(let A=0;A<T;A++){l.turn();for(let D of u)await D.cart.step(1)}},pause(){K(),E=!0;for(let d of u)d.cart.pause()},resume(){K(),E=!1;for(let d of u)d.cart.resume()},reset(){K(),w.length=0;for(let d of u)d.events.length=0,d.errors.length=0,d.cart=d.runtime.mount(d.cartDef,{initialState:d.initialState,gameManager:d.gameManager,onEvent:h(d)});l.turn()},dispatch(d,T){K();let A=p.get(d);if(!A)throw new Error(`createRuntimeGroup: unknown participant "${d}"`);A.cart.dispatch(T)},publish(d,T){return K(),l.publish(d,T)},async inspect(){K();let d={},T={};for(let D of u){let H=await D.cart.getReplayMetadata(),W=D.cart.getClock();T[D.id]=W,d[D.id]={state:H.state,events:D.events.slice(),errors:D.errors.slice(),kind:D.kind,clock:W}}let A=w.map(D=>Lt(D));return{participants:d,trace:A,diagnostics:{paused:E,participantIds:u.map(D=>D.id),clocks:T,rejections:A.filter(D=>D.type===fe).map(D=>D.payload)}}},destroy(){if(!b){b=!0,E=!1;try{$()}finally{w.length=0}}}}}function Bn(e){return ke(),_t(e)}export{Pt as DEFAULT_HEADLESS_HEIGHT,Tt as DEFAULT_HEADLESS_WIDTH,xt as HEADLESS_PNG_DATA_URL,Rn as createHeadlessHarness,Bn as createHeadlessMultiCartHarness,ke as installHeadlessCanvas};
|
|
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};
|